Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Need help with my very first c# application

Need help with my very first c# application

Scheduled Pinned Locked Moved C#
csharphelpquestionlearning
25 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S S Houghtelin

    If the book store is too much bother, another link to M$, at least it doesn't contain the words ...in 7 days. :-D though you could probably cover it in less. http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx[^]

    It was broke, so I fixed it.

    L Offline
    L Offline
    Luc Pattyn
    wrote on last edited by
    #16

    That is not an introduction or a tutorial, that is reference material. Which comes in handy once you start programming in some language, but first you need the intro, the fundamentals. :)

    Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

    Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

    S 1 Reply Last reply
    0
    • L Luc Pattyn

      That is not an introduction or a tutorial, that is reference material. Which comes in handy once you start programming in some language, but first you need the intro, the fundamentals. :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

      S Offline
      S Offline
      S Houghtelin
      wrote on last edited by
      #17

      :-O Sorry, wrong link, had several pages open. See, it doesn't get easier. http://msdn.microsoft.com/en-us/library/aa288436(VS.71).aspx[^]

      It was broke, so I fixed it.

      1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        So your first port of call is to find out just what args[0] is. Google can help: Google args[0] c#[^] This second result explains it, and gives examples: MSDN on command line arguments[^] This is your second (or first-and-a-half) port of call: MSDN. It knows everything (hah!) about C# and .NET And it's free. Impenetrable at times, but free. And very often worth tagging into a Google search: "args[0] c# MSDN" would give the article above as the first hit. So, args[0] is the first command line argument to your console app. (or Winforms or whatever, but don't worry about that yet). This explains why it gave an ArgumentOutOfRange error when you tried to use it: you haven't supplied any command line arguments! So, change your code to:

        string host = "192.168.0.1"; // Default to my router
        if (args.Count > 0)
        {
        host = args[0];
        }

        And it would work with either a default value - my router - or the IP address you specify as a command line argument. This means you can run your console app with:

        myPing

        (which would ping your router) or

        myPing 92.27.41.80

        (which would ping me, for an hour or so until I turn the router off.) Now do you see what I mean about it being important to work out why something isn't working, rather than just "fixing it"? :laugh:

        Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

        T Offline
        T Offline
        turbosupramk3
        wrote on last edited by
        #18

        Thank you. Even though I have some reading to do now :) I will try and implement this and get it working.

        1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          So your first port of call is to find out just what args[0] is. Google can help: Google args[0] c#[^] This second result explains it, and gives examples: MSDN on command line arguments[^] This is your second (or first-and-a-half) port of call: MSDN. It knows everything (hah!) about C# and .NET And it's free. Impenetrable at times, but free. And very often worth tagging into a Google search: "args[0] c# MSDN" would give the article above as the first hit. So, args[0] is the first command line argument to your console app. (or Winforms or whatever, but don't worry about that yet). This explains why it gave an ArgumentOutOfRange error when you tried to use it: you haven't supplied any command line arguments! So, change your code to:

          string host = "192.168.0.1"; // Default to my router
          if (args.Count > 0)
          {
          host = args[0];
          }

          And it would work with either a default value - my router - or the IP address you specify as a command line argument. This means you can run your console app with:

          myPing

          (which would ping your router) or

          myPing 92.27.41.80

          (which would ping me, for an hour or so until I turn the router off.) Now do you see what I mean about it being important to work out why something isn't working, rather than just "fixing it"? :laugh:

          Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

          T Offline
          T Offline
          turbosupramk3
          wrote on last edited by
          #19

          Here is what I have, did I do something wrong because it is still telling me I am outside of the bounds of the array

          using System;
          using System.Net;
          using System.Net.NetworkInformation;
          using System.Text;

          namespace Examples.System.Net.NetworkInformation.PingTest
          {
          public class PingExample
          {
          // args[0] can be an IPaddress or host name.

              public static void Main(string \[\] args)
              {
                  
                  Ping pingSender = new Ping();
                  PingOptions options = new PingOptions();
          
                  //string host = "servername";
          
                  string host = "servername";  
                  if (args.Length > 0)
                  {
                      host = args\[0\];
                  }
          
          
                  // Use the default Ttl value which is 128,
                  // but change the fragmentation behavior.
                  options.DontFragment = true;
          
                  // Create a buffer of 32 bytes of data to be transmitted.
                  string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                  byte\[\] buffer = Encoding.ASCII.GetBytes(data);
                  int timeout = 120;
          
                  
          
                  PingReply reply = pingSender.Send(args\[0\], timeout, buffer, options);
                  if (reply.Status == IPStatus.Success)
                  {
                      Console.WriteLine("Reply from {0}", reply.Address.ToString());
                      Console.WriteLine("Bytes {0}", reply.Buffer.Length);
                      Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                      Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                      //Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                      
          
                     
                      Console.ReadLine();
                  }
          
          
          
              }
          
          }
          

          }

          OriginalGriffO 1 Reply Last reply
          0
          • L Luc Pattyn

            I think nothing beats a book, for a couple of reasons: 1. The quality tends to be much higher than anything on the web. 2. You can process material on your own pace, anything that moves may end up being watched as a TV show. 3. You can make little notes and apply highlights in a book (assuming you own it). I do a quick video if I need to get some insight in new stuff, not to study it thoroughly. :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

            Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

            C Offline
            C Offline
            Charles Cox
            wrote on last edited by
            #20

            Books are very good. Considering everything I know about C# was gained through library books and books bought at used book stores (no formal training) they are a priceless source of information. As a side note, args[0] sounds like the argument passed to all Console applications in the Main method. So args[0] would be the first command line argument for the application e.g. ping.exe 255.255.255.255. This being a hypothetical situation from the fact that replacing it with a variable called host (assuming it is the IP Adress to ping) made it work. Anyway. Books are good.

            1 Reply Last reply
            0
            • T turbosupramk3

              Here is what I have, did I do something wrong because it is still telling me I am outside of the bounds of the array

              using System;
              using System.Net;
              using System.Net.NetworkInformation;
              using System.Text;

              namespace Examples.System.Net.NetworkInformation.PingTest
              {
              public class PingExample
              {
              // args[0] can be an IPaddress or host name.

                  public static void Main(string \[\] args)
                  {
                      
                      Ping pingSender = new Ping();
                      PingOptions options = new PingOptions();
              
                      //string host = "servername";
              
                      string host = "servername";  
                      if (args.Length > 0)
                      {
                          host = args\[0\];
                      }
              
              
                      // Use the default Ttl value which is 128,
                      // but change the fragmentation behavior.
                      options.DontFragment = true;
              
                      // Create a buffer of 32 bytes of data to be transmitted.
                      string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                      byte\[\] buffer = Encoding.ASCII.GetBytes(data);
                      int timeout = 120;
              
                      
              
                      PingReply reply = pingSender.Send(args\[0\], timeout, buffer, options);
                      if (reply.Status == IPStatus.Success)
                      {
                          Console.WriteLine("Reply from {0}", reply.Address.ToString());
                          Console.WriteLine("Bytes {0}", reply.Buffer.Length);
                          Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                          Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                          //Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                          
              
                         
                          Console.ReadLine();
                      }
              
              
              
                  }
              
              }
              

              }

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #21

              Yes! You are still using args[0]

                     PingReply reply = pingSender.Send(args\[0\], timeout, buffer, options);
              

              Try:

                     PingReply reply = pingSender.Send(host, timeout, buffer, options);
              

              Also change the comment near the top:

                  // args\[0\] can be an IPaddress or host name.
              

              It may be accurate, but it isn't very helpfull! How about:

                  // Command line arguments can be an IPaddress or host name to ping.
              

              That describes better what you are trying to do, rather than how you are achieving them. However, you get a 5 just for putting comments in your first program. :laugh: Not a bad effort - keep it up! Later, you may want to put in a loop, so you can use a number of addresses in the command line. See foreach for details.

              Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              T 1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                Yes! You are still using args[0]

                       PingReply reply = pingSender.Send(args\[0\], timeout, buffer, options);
                

                Try:

                       PingReply reply = pingSender.Send(host, timeout, buffer, options);
                

                Also change the comment near the top:

                    // args\[0\] can be an IPaddress or host name.
                

                It may be accurate, but it isn't very helpfull! How about:

                    // Command line arguments can be an IPaddress or host name to ping.
                

                That describes better what you are trying to do, rather than how you are achieving them. However, you get a 5 just for putting comments in your first program. :laugh: Not a bad effort - keep it up! Later, you may want to put in a loop, so you can use a number of addresses in the command line. See foreach for details.

                Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

                T Offline
                T Offline
                turbosupramk3
                wrote on last edited by
                #22

                Thanks and be proud, I touched it up to this, this morning and it actually works!!! :-D Next on the list is to import a text file through streamreader? or textreader? Hopefully I can find some more code like this basic ping tool on MSDN or something and then I'll be able to import each server with my foreach loop?

                using System;
                using System.Net;
                using System.Net.NetworkInformation;
                using System.Text;
                using System.IO;

                namespace Examples.System.Net.NetworkInformation.PingTest
                {
                public class PingExample
                {
                // args[0] can be an IPaddress or host name.

                    public static void Main(string \[\] args)
                    {
                        
                        Ping pingSender = new Ping();
                        PingOptions options = new PingOptions();
                
                
                
                        // Use the default Ttl value which is 128,
                        // but change the fragmentation behavior.
                        options.DontFragment = true;
                
                        // Create a buffer of 32 bytes of data to be transmitted.
                        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                        byte\[\] buffer = Encoding.ASCII.GetBytes(data);
                        int timeout = 120;
                
                        string\[\] arr = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                
                        foreach (string i in arr)
                
                        {
                           int pingloop = 0;
                           Console.WriteLine(i);
                
                           do
                           {
                
                               PingReply reply = pingSender.Send(i, timeout, buffer, options);
                               if (reply.Status == IPStatus.Success)
                               {
                                   Console.WriteLine("Reply from {0}", reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms" + " TTL=" + reply.Options.Ttl);
                                   pingloop = pingloop +1;
                                   //Console.WriteLine("Bytes {0}", reply.Buffer.Length);
                                   //Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                                   //Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                                   //Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                                   
                               }
                           }
                
                           while (pingloop < 4);
                           Console.WriteLine();     
                           
                            
                        }
                        Console.ReadLine();
                    }
                
                }
                
                OriginalGriffO 1 Reply Last reply
                0
                • T turbosupramk3

                  Thanks and be proud, I touched it up to this, this morning and it actually works!!! :-D Next on the list is to import a text file through streamreader? or textreader? Hopefully I can find some more code like this basic ping tool on MSDN or something and then I'll be able to import each server with my foreach loop?

                  using System;
                  using System.Net;
                  using System.Net.NetworkInformation;
                  using System.Text;
                  using System.IO;

                  namespace Examples.System.Net.NetworkInformation.PingTest
                  {
                  public class PingExample
                  {
                  // args[0] can be an IPaddress or host name.

                      public static void Main(string \[\] args)
                      {
                          
                          Ping pingSender = new Ping();
                          PingOptions options = new PingOptions();
                  
                  
                  
                          // Use the default Ttl value which is 128,
                          // but change the fragmentation behavior.
                          options.DontFragment = true;
                  
                          // Create a buffer of 32 bytes of data to be transmitted.
                          string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                          byte\[\] buffer = Encoding.ASCII.GetBytes(data);
                          int timeout = 120;
                  
                          string\[\] arr = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                  
                          foreach (string i in arr)
                  
                          {
                             int pingloop = 0;
                             Console.WriteLine(i);
                  
                             do
                             {
                  
                                 PingReply reply = pingSender.Send(i, timeout, buffer, options);
                                 if (reply.Status == IPStatus.Success)
                                 {
                                     Console.WriteLine("Reply from {0}", reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms" + " TTL=" + reply.Options.Ttl);
                                     pingloop = pingloop +1;
                                     //Console.WriteLine("Bytes {0}", reply.Buffer.Length);
                                     //Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                                     //Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                                     //Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                                     
                                 }
                             }
                  
                             while (pingloop < 4);
                             Console.WriteLine();     
                             
                              
                          }
                          Console.ReadLine();
                      }
                  
                  }
                  
                  OriginalGriffO Offline
                  OriginalGriffO Offline
                  OriginalGriff
                  wrote on last edited by
                  #23

                  Well done!:thumbsup: I think you are getting there. A couple of style things, that make it easier to read when you go back to it:

                          string\[\] arr = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                          foreach (string i in arr)
                  

                  Don't call it "i" - there are a couple of reasons (one of which is that old programmers assume "i" is always an int). Always use descriptive names for variables, it makes it a lot easier to work out what you are trying to do. Since Visual Studio list possible names for you, it isn't a lot of extra typing, and it does make it more readable. Try using "server" instead:

                          string\[\] servers = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                          foreach (string server in servers)
                             {
                             ...
                             }
                  

                  And try using a for loop instead of a do...while - it makes it more obvious by keeping the whole thing together:

                          int pingloop = 0;
                          do
                             {
                  
                             PingReply reply = pingSender.Send(i, timeout, buffer, options);
                             if (reply.Status == IPStatus.Success)
                                 {
                                 Console.WriteLine("Reply from {0}", reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms" + " TTL=" + reply.Options.Ttl);
                                 pingloop = pingloop +1;
                                 }
                             }
                             while (pingloop < 4);
                  

                  becomes

                          for (int retries = 0; retries < 4; retries++)
                             {
                             PingReply reply = pingSender.Send(i, timeout, buffer, options);
                             if (reply.Status == IPStatus.Success)
                                 {
                                 Console.WriteLine("Reply from {0}", reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms" + " TTL=" + reply.Options.Ttl);
                                 break;
                                 }
                             }
                  

                  It's all about keeping thing together, and making it obvious what is going on. Doing it your way means that "pingloop" is available after the loop, implying that it will be relevant and probably used after the loop. With the for loop, "retries" is not available outside the loop at all. I also added the "break" to prevent repeated pinging once it has succeeded. Good effort though, well done!:cool:

                  Real men d

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                  T 1 Reply Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    Well done!:thumbsup: I think you are getting there. A couple of style things, that make it easier to read when you go back to it:

                            string\[\] arr = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                            foreach (string i in arr)
                    

                    Don't call it "i" - there are a couple of reasons (one of which is that old programmers assume "i" is always an int). Always use descriptive names for variables, it makes it a lot easier to work out what you are trying to do. Since Visual Studio list possible names for you, it isn't a lot of extra typing, and it does make it more readable. Try using "server" instead:

                            string\[\] servers = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                            foreach (string server in servers)
                               {
                               ...
                               }
                    

                    And try using a for loop instead of a do...while - it makes it more obvious by keeping the whole thing together:

                            int pingloop = 0;
                            do
                               {
                    
                               PingReply reply = pingSender.Send(i, timeout, buffer, options);
                               if (reply.Status == IPStatus.Success)
                                   {
                                   Console.WriteLine("Reply from {0}", reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms" + " TTL=" + reply.Options.Ttl);
                                   pingloop = pingloop +1;
                                   }
                               }
                               while (pingloop < 4);
                    

                    becomes

                            for (int retries = 0; retries < 4; retries++)
                               {
                               PingReply reply = pingSender.Send(i, timeout, buffer, options);
                               if (reply.Status == IPStatus.Success)
                                   {
                                   Console.WriteLine("Reply from {0}", reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms" + " TTL=" + reply.Options.Ttl);
                                   break;
                                   }
                               }
                    

                    It's all about keeping thing together, and making it obvious what is going on. Doing it your way means that "pingloop" is available after the loop, implying that it will be relevant and probably used after the loop. With the for loop, "retries" is not available outside the loop at all. I also added the "break" to prevent repeated pinging once it has succeeded. Good effort though, well done!:cool:

                    Real men d

                    T Offline
                    T Offline
                    turbosupramk3
                    wrote on last edited by
                    #24

                    Here is my latest code, thanks to all that helped

                    using System;
                    using System.Net;
                    using System.Net.NetworkInformation;
                    using System.Text;
                    using System.IO;
                    using System.Collections.Generic;
                    using System.ComponentModel;
                    using System.Threading;

                    namespace Examples.System.Net.NetworkInformation.PingTest
                    {
                    public class PingExample
                    {
                    public static void Main(string[] args)
                    {
                    const string f = @"c:\temp\servernames.txt";
                    List<string> servers = new List<string>();

                            Ping pingSender = new Ping();
                            PingOptions options = new PingOptions();
                            //PingCompletedEventArgs e = new PingCompletedEventArgs();
                            string line = null; //line in a file
                            PingReply reply = null; // variable reply is set to null and referenced to the object type PingReply
                            //string lineerror = null;
                    
                            // Use the default Ttl value which is 128,
                            // but change the fragmentation behavior.
                            options.DontFragment = true;
                    
                            // Create a buffer of 32 bytes of data to be transmitted.
                            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                            byte\[\] buffer = Encoding.ASCII.GetBytes(data);
                            int timeout = 250;
                            using (StreamReader r = new StreamReader(f))
                            {
                                // 3
                                // Use while != null pattern for loop
                                while ((line = r.ReadLine()) != null)
                                {
                                    // 4
                                    // Insert logic here.
                                    // ...
                                    // "line" is a line in the file. Add it to our List.
                                    if (string.IsNullOrEmpty(line))
                                    {
                                        // 3
                                        // Test with IsNullOrEmpty
                                        //lineerror = "Line appears to be empty";
                                    }
                                    else
                                    {
                                        servers.Add(line);
                                    }
                                }//end of while
                            }//end fo using
                    
                            //string\[\] arr = new string\[\] { "server1", "server2", "server3" }; // server names you want to ping
                    
                            foreach (string i in servers)
                            {
                    
                                Console.WriteLine(i);
                                for (int retries = 0; retries < 4; retries++)
                                {
                                    try
                                    {
                                        reply = pingSender.Send(i, timeout, buffer, options);
                    
                    1 Reply Last reply
                    0
                    • T turbosupramk3

                      I would like to build a basic ping application. I've seen a few ping applications here that are well developed and a little complicated for me to dissect and figure out how they work at this point in my learning. Does anyone have a console ping application that is bare bones, that I can build off of while I learn? Something that I can launch and hard code variables into, and break and the put back and see how it functions? Thank you!

                      M Offline
                      M Offline
                      MasttsaM
                      wrote on last edited by
                      #25

                      Hope this example can help you: Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; if (p.Start()) { p.StandardInput.WriteLine("net use " + strFileName + " " + strPwd + " /user:" + strDomain + "\\" + strId); p.StandardInput.WriteLine("exit"); p.WaitForExit(); string ReturnText = p.StandardOutput.ReadToEnd(); if (ReturnText.IndexOf("成功") >= 0) Dts.TaskResult = (int)ScriptResults.Success; else throw new Exception("fail"); } else throw new Exception("fail"); Reference: http://www.programlive.tk

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups