none
Retrieve Results from List<string> C# RRS feed

  • Question

  • Hi i've added 2 string on the other form  

    addIP.Add("1");
    addIP.Add("2");

    public static List<string> retrieveAllIP()
            {
                var t = new List<string>();
                foreach (string s in addIP)
                {
                    string returnIP = s;
                    t.Add(returnIP);
                }
                    return addIP;

    after which on the other form i retrieve the results out but why the results will print 10 times? i tried debugging the Count shown is 10 but i only added 2 items 

     List<string> host = Control.retrieveAllIP().ToList();

                foreach (string h in host)
                //for(int j = 0; j < host.Count; j++)
                {

                    Debug.Write(h);

         }

    please help! thanks!

                              
    Wednesday, September 18, 2013 6:50 PM

Answers

  • Please clear your collection before add

                                addIP.Clear();
                                addIP.Add("192.168.1.121");
                                addIP.Add("192.168.1.113");
                                item.SubItems.Add(deviceType);


    Happy Coding, RDRaja

    • Marked as answer by Myusic Friday, September 20, 2013 7:21 PM
    Friday, September 20, 2013 6:25 PM
  • DisplayReply method is called repeatly,without clearing addIP collection

    thatwhy it is added more than onetime

    try to add the collection values in static constructor

            static Control()
            {
                addIP.Add("192.168.1.121");
                addIP.Add("192.168.1.113");
            }


    Happy Coding, RDRaja


    • Edited by Dharmalinga Raja Friday, September 20, 2013 6:38 PM
    • Marked as answer by Myusic Friday, September 20, 2013 7:21 PM
    Friday, September 20, 2013 6:34 PM

All replies

  • First of all, your "retrieveAllIP" function doesn't do anything. You do some work to put together a new List<string>, then just return "addIP" anyway. It's equivalent to this:

    public static List<string> retrieveAllIP()
    {
        return addIP;
    }

    You also haven't shown enough code to figure out why your Count is 10. Please show all areas where you are modifying "addIP".


    • Edited by tnw Wednesday, September 18, 2013 7:21 PM
    Wednesday, September 18, 2013 7:18 PM
  • Hi

    I think,this may be problem of uncleared debug window

    please try one more time


    Happy Coding, RDRaja


    Thursday, September 19, 2013 1:48 AM
  • Hi raja I've tried a few times but it will print 10 times where I only added 2 IP address in the string array. pls help
    Thursday, September 19, 2013 2:28 AM
  • Hi tnw I only added 2 into the string array but on the other form I get back 10 results when I tried to do a Debug.Write
    Thursday, September 19, 2013 2:29 AM
  • Hi 

    Did you try to show the results in ListBox

    please try the below code with listBox named as listBox1

                listBox1.Items.Clear();
                int iCount = 1;
                foreach (string h in host)
                {
                    listBox1.Items.Add(iCount.ToString() +" " + h);
                    iCount = iCount + 1;
                }
    it will show you,how many times strings will added to the list box


    Happy Coding, RDRaja

    Thursday, September 19, 2013 5:37 PM
  • Hi raja, I only try to print my results in debug.writeline can this be done on debug window mode? one question, why iCount = 1? sorry I'm a newbie and not good in programming though
    Friday, September 20, 2013 2:33 AM
  • Hi myusic,

    iCount=1 ,initialize the integer variable to 1

    which project type you are used

    windows application or console application or any others


    Happy Coding, RDRaja

    Friday, September 20, 2013 3:24 AM
  • In you original code you are returning addip.  You should be returning "t".

    public static List<string> retrieveAllIP()
            {
                var t = new List<string>();
                foreach (string s in addIP)
                {
                    string returnIP = s;
                    t.Add(returnIP);
                }
                    return addIP;


    jdweng

    Friday, September 20, 2013 3:32 AM
  • Hi raja I use this examples from here http://www.codeproject.com/Articles/13540/Remote-Shutdown-in-VB-NET-2003-and-C-NET-2008?msg=3135268#xx3135268xx because the IP address I've found contains router, switch printer and PC but this program only could shut down PC is there any way to let the program shut down PC without hard coding the IP address in the List?
    Friday, September 20, 2013 4:24 AM
  • ok I will try that later on. one question , why when we return the List i need to create another List ("t") to add the previous List (addIP) to return?
    Friday, September 20, 2013 4:27 AM
  • Your code is doing a lot of work for no reason.  Delete the returnAllIP procedure entirely.  Delete the line which declares host - "List<string> host = ...".  Change the foreach to be

    foreach(string h in addIP)

    You will see 10 entries if 10 entries have been added to the list.  What are the entries in the list?  Are they "1", "2", "1", "2", "1", "2", "1", "2", "1" and "2"?  Or something else?

    Put a breakpoint on the line which adds "1" to addIP.  When the program breaks at that line, press F5 to continue running.  Does the code come back to the line?  How many times does that get executed?  (Note that this question is not "How many times do you want it to be executed" or "How many times do you think it is executed" but "How many times IS it executed".


    Paul Linton

    Friday, September 20, 2013 5:00 AM
  • The list<string> host is I getting the List from other class that is why I did that. Yes the code printed out is "1","2","1","2",1","2","1","2",1","2"
    • Edited by Myusic Friday, September 20, 2013 5:25 AM
    Friday, September 20, 2013 5:24 AM
  • Using the debugger, why are you executing the add statements five times?  You haven't shown us any code so we can't help you with that question.

    Is allIP a property of the Control class?

    foreach (string h in Control.allIP)

    if allIp has restricted access then you could make a public property

    public List<string> AllIP { return allIP;}

    and use

    foreach (string h in Control.AllIP)


    Paul Linton

    Friday, September 20, 2013 5:29 AM
  • Yes allIP list is in the Control class. Because I'm not at home now I can't try the codes.. So you mean I create a method at my control class public List<string> allIP () { return allIP; }. ? because my original code was something like that you see above so that my other class can access the List shown above..
    Friday, September 20, 2013 5:45 AM
  • Not a method, a property.  Sorry, I got the sample wrong

    public List<string> AllIP {get {return allIP;} }


    Paul Linton

    Friday, September 20, 2013 5:55 AM
  • Ok I will try it when I get home and will update you again! Do you have any idea not to shut down the router,switch and printers? my intention is to shutdown all the PC but the results I get from allIP contains the IP address of the router, switches and printers..
    Friday, September 20, 2013 6:00 AM
  • shutdown? What? Who said anything about shutdown?  How do you shutdown a router, switch or a printer?  However you do it the way to stop it happening is to not do it!

    Paul Linton

    Friday, September 20, 2013 6:03 AM
  • ok will try it later and let you know
    Friday, September 20, 2013 8:03 AM
  • Hi Paul ive tried your method it still printed out many times i use the debugger shows that the Count = 6. why is this happening?
    Friday, September 20, 2013 5:47 PM
  • Hi Myusic,

    can you post the source of that form


    Happy Coding, RDRaja

    Friday, September 20, 2013 6:02 PM
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Threading;
    using System.Net.NetworkInformation;
    using System.Text;
    using System.Net;
    using SnmpSharpNet;
    using System.Diagnostics;
    using System.IO;
    using System.Drawing;
    
    namespace TestingPing
    {
        class Control
        {
            Thread t;
            ListView listResults;
            bool stop = false;
            string deviceType = "";
            static List<String> addIP = new List<string>();
    
            public Control()
            { 
    
            }
            public Control(ListView lv)
            {
                this.listResults = lv;
            }
    
    
            public void sendAsyncPingPacket(string hostToPing)
            {
    
                try
                {
                    int timeout = 1000;
                    AutoResetEvent waiter = new AutoResetEvent(false);
                    Ping pingPacket = new Ping();
    
                    //ping completed to call method PingCompletedCallback
                    pingPacket.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
    
                    string data = "Ping test check";
                    byte[] byteBuffer = Encoding.ASCII.GetBytes(data);
                    PingOptions pingOptions = new PingOptions(64, true);
                                                                                                //Console.WriteLine("Time to live: {0}", pingOptions.Ttl);
                    //Console.WriteLine("Don't fragment: {0}", pingOptions.DontFragment);
                    pingPacket.SendAsync(hostToPing, timeout, byteBuffer, pingOptions, waiter);
                    //waiter.WaitOne();
                }
                catch (Exception ee)
                {
    
                }
                
    
    
            }
            public void PingCompletedCallback(object sender, PingCompletedEventArgs e)
            {
                try
                {
                    if (e.Cancelled)
                    {
                        Debug.WriteLine("Ping Canceled.");
    
                        // Let the main thread resume. 
                        // UserToken is the AutoResetEvent object that the main thread 
                        // is waiting for.
                        ((AutoResetEvent)e.UserState).Set();
                    }
    
                    // If an error occurred, display the exception to the user.
                    if (e.Error != null)
                    {
                        Debug.WriteLine("Ping Failed!");
                        //this will print exception
                        Debug.WriteLine(e.Error.ToString());
    
                        // Let the main thread resume. 
                        ((AutoResetEvent)e.UserState).Set();
                    }
                    else
                    {
                        PingReply reply = e.Reply;
    
                        DisplayReply(reply);
    
                        // Let the main thread resume.
                        ((AutoResetEvent)e.UserState).Set();
    
                    }
                }
    
                catch (Exception ex)
                {
                    MessageBox.Show("Exception " + ex.Message);
                }
            }
            public void DisplayReply(PingReply reply)
            {
                if (reply == null)
                    return;
    
                //Console.WriteLine("Ping Status: {0}", reply.Status);
                    
                else if (reply.Status == IPStatus.Success)
                {
                    
                   
                   
                 
    
                    
                        stop = true;
                        if (listResults.InvokeRequired == true)
                            this.listResults.Invoke((MethodInvoker)delegate()
                            {
                                
                                ListViewItem item = new ListViewItem();
                                
                                item.Text = reply.Address.ToString();
                                
                                //addIP.Add(reply.Address.ToString());
                                addIP.Add("192.168.1.121");
                                addIP.Add("192.168.1.113");
                                item.SubItems.Add(deviceType);
                                
                                //  item.SubItems[2].BackColor = Color.FromArgb(-16711936);
    
                                //item.UseItemStyleForSubItems = false;
                                //Debug.WriteLine(deviceType);
                             
            public long ToInt(string addr)
            {
                try
                {
                    return (long)(uint)System.Net.IPAddress.NetworkToHostOrder(
                       (int)System.Net.IPAddress.Parse(addr).Address);
                }
                catch (Exception x)
                {
                    MessageBox.Show("Empty or Incorrect IP address specify",
        "Note",
        MessageBoxButtons.OK,
        MessageBoxIcon.Exclamation,
        MessageBoxDefaultButton.Button1);
                    
                    return 0;
                }
                
            }
            public string ToAddr(long address)
            {
                return System.Net.IPAddress.Parse(address.ToString()).ToString();
            }
            public void scanLiveHosts(string ipFrom, string ipTo)
            {
                long from = ToInt(ipFrom);
                long to = ToInt(ipTo);
    
                
    
                while (from < to)
                {
                    string address = ToAddr(from);
                    sendAsyncPingPacket(address);
                    from++;
                }
    
            }
    
            
            //public static List<string> retrieveAllIP()
            //{
            //    var t = new List<string>();
            //    foreach (string s in addIP)
            //    {
            //        string returnIP = s;
            //        t.Add(returnIP);
            //    }
            //        return addIP;
    
                
            //}
            public static List<string> AllIP { 
                get {
     
                    return addIP; 
                } 
            }
    
        }
    }
    
    Hi this is my form for the Control form as for the form to retrieve is below 
        public void shutdownAllPC(string i)
            {
                //List<string> host = Control.retrieveAllIP().ToList();
                int port = 63000;
                foreach (string h in Control.AllIP)
                   
                    {
                        //for(int j = 0; j < host.Count; j++)
                        {
                            //getHosts = h;
                            Debug.Write(h);
    
                          
                        }
                    }
    }

    Friday, September 20, 2013 6:18 PM
  • Please clear your collection before add

                                addIP.Clear();
                                addIP.Add("192.168.1.121");
                                addIP.Add("192.168.1.113");
                                item.SubItems.Add(deviceType);


    Happy Coding, RDRaja

    • Marked as answer by Myusic Friday, September 20, 2013 7:21 PM
    Friday, September 20, 2013 6:25 PM
  • finally it worked! why do i need to clear??
    Friday, September 20, 2013 6:27 PM
  • DisplayReply method is called repeatly,without clearing addIP collection

    thatwhy it is added more than onetime

    try to add the collection values in static constructor

            static Control()
            {
                addIP.Add("192.168.1.121");
                addIP.Add("192.168.1.113");
            }


    Happy Coding, RDRaja


    • Edited by Dharmalinga Raja Friday, September 20, 2013 6:38 PM
    • Marked as answer by Myusic Friday, September 20, 2013 7:21 PM
    Friday, September 20, 2013 6:34 PM
  • i see. what is static constructor? sorry im still a newbie in programming..
    Friday, September 20, 2013 6:39 PM
  • static constructor is used to initialize static variables.

    it is called when first time this static variable is accessed


    Happy Coding, RDRaja

    Friday, September 20, 2013 6:42 PM
  • i see. so by doing this i dont need to clear the List everytime? but why? do you mean everytime before this class is run the data is already added? am i right to say that?
    Friday, September 20, 2013 6:47 PM
  • yes, DisplayReply method is called 5times before call shutdownAllPC method



    Happy Coding, RDRaja

    Friday, September 20, 2013 6:52 PM
  • i see thanks very much for your help Raja! :)
    Friday, September 20, 2013 7:05 PM
  • Hi Myusic

    if you got the result,mark this thread as answered


    Happy Coding, RDRaja

    Friday, September 20, 2013 7:20 PM