<<<Prev   1   2   3   Next > > >

Here's a fasttrack arrangement of code samples for learning C#.

  1. Code Samples:
    1. The obligatory example for any language,

       
      using System;
      public class HelloWorld
      {
          public static void Main(string[] args) {
      	Console.Write("Hello World!");
          }
      }
      
    2. Raw CSharp compiler

      You can compile c# using the command line version

      csc HelloWorld.cs
      
      and then run the new program by entering
      HelloWorld
      

      You can get Nant, a build tool like the old 'make', from http://sourceforge.net/projects/nant.

    3. Read a file with a single call to sReader.ReadToEnd()

       
           public static string getFileAsString(string fileName) {
               StreamReader sReader = null;
               string contents = null;
               try {
                  FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                  sReader = new StreamReader(fileStream);
                  contents = sReader.ReadToEnd();
               } finally {
                 if(sReader != null) {
                     sReader.Close();
                  }
               }
               return contents;
            }
      
    4. Read a file line by line with no error checking

      StreamReader sr = new StreamReader("fileName.txt");
      string line;
      while((line= sr.ReadLine()) != null) {
      	Console.WriteLine("xml template:"+line);
      }
      if (sr != null)sr.Close();  //should be in finally block
      
    5. Write a line to a file

      using System;
      using System.IO;
      
      public class WriteFileStuff {
      
      public static void Main() {
             FileStream fs = new FileStream("c:\\tmp\\WriteFileStuff.txt", FileMode.OpenOrCreate, FileAccess.Write);			
             StreamWriter sw = new StreamWriter(fs);
             try {
      		sw.WriteLine("Howdy World.");
      	} finally {
      		if(sw != null) { sw.Close(); }
      	}
      }
      }
      
    6. Access files with "using"

      "using" does an implicit call to Dispose() when the using block is complete. With files this will close the file. The following code shows that using does indeed close the file, otherwise 5000 open files would clutter your machine.

      using System;
      using System.IO;
      
      class Test {
          private static void Main() {
              for (int i = 0; i < 5000; i++) {
                  using (TextWriter w = File.CreateText("C:\\tmp\\test\\log" + i + ".txt")) {
                      string msg = DateTime.Now + ", " + i;
                      w.WriteLine(msg);
                      Console.Out.WriteLine(msg);
                  }
              }
              Console.In.ReadLine();
          }
      }
      
    7. Write a very simple XML fragment the hard way.

      static void writeTree(XmlNode xmlElement, int level) {
         String levelDepth = "";
         for(int i=0;i<level;i++) 
         {
            levelDepth += "   ";
         }
         Console.Write("\n{0}<{1}",levelDepth,xmlElement.Name);
         XmlAttributeCollection xmlAttributeCollection = xmlElement.Attributes;
         foreach(XmlAttribute x in xmlAttributeCollection) 
         {
            Console.Write(" {0}='{1}'",x.Name,x.Value);
         }
         Console.Write(">");
         XmlNodeList xmlNodeList = xmlElement.ChildNodes;
         ++level;
         foreach(XmlNode x in xmlNodeList) 
         {
            if(x.NodeType == XmlNodeType.Element) 
            {
               writeTree((XmlNode)x,  level);
            }
            else if(x.NodeType == XmlNodeType.Text) 
            {
               Console.Write("\n{0}   {1}",levelDepth,(x.Value).Trim());
            }
         }
         Console.Write("\n{0}</{1}>",levelDepth,xmlElement.Name);
      }
      
    8. Write a very simple XML fragment the easy way

      StringWriter stringWriter = new StringWriter();
      XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
      xmlTextWriter.Formatting = Formatting.Indented;
      xmlDocument.WriteTo(xmlTextWriter); //xmlDocument can be replaced with an XmlNode
      xmlTextWriter.Flush();
      Console.Write(stringWriter.ToString());
      
    9. Write formated output:

      int k = 16;
      Console.WriteLine(" '{0,-8}'",k);     // produces:  '16      '
      Console.WriteLine(" '{0,8}'",k);      // produces:   '      16'
      Console.WriteLine(" '{0,8}'","Test"); // produces:  '    Test'
      Console.WriteLine(" '{0,-8}'","Test");// produces: 'Test    '
      Console.WriteLine(" '{0:X}'",k);      //(in HEX) produces: '10'
      Console.WriteLine(" '{0:X10}'",k);    //(in HEX) produces:'0000000010'
      
    10. Formatting decimals in strings using String.Format()

      More info at www.codeproject.com

      s.Append(String.Format("Completion Ratio: {0:##.#}%",100.0*completes/count));
      
      or use the ToString() method on the double object:
      s.Append(myDouble.ToString("###.###")
      
      or
      String.Format("{0,8:F3}",this.OnTrack)
      
    11. Format DateTime objects

      DateTime.Now.ToString("yyyyMMdd-HHmm"); // will produce '20060414-1529'
      
    12. Example of Constructors, static Constructor and Destructor:

      class Test2
         {
         static int i;
      
            static Test2() { // a constructor for the entire class called 
                             //once before the first object created
                    i = 4;
               Console.Out.WriteLine("inside static construtor...");
            }
            public Test2() {
               Console.Out.WriteLine("inside regular construtor... i={0}",i);
            }
            ~Test2() { // destructor (hopefully) called for each object
             Console.Out.WriteLine("inside destructor");
            }
            
            [STAThread]
            static void Main(string[] args)
            {
               Console.Out.WriteLine("Test2");
               new Test2();
               new Test2();
      
               Console.ReadLine();
            }
         }
      
    13. Example of Virtual Functions:

      namespace Test2 {
      
         class Plane {
      
            public double TopSpeed() {
               return 300.0D;
            }
         }
         class Jet : Plane {
      
            public double TopSpeed() {
               return 900.0D;
            }
         }
         class Airport {
            [STAThread]
            static void Main(string[] args) {
               Plane plane = new Jet();
               Console.WriteLine("planes top speed: {0}",plane.TopSpeed());
               Console.ReadLine();
            }
         }
      }
      
      

      This, oddly enough will print "300" for the planes speed, since TopSpeed() is not virtual. To fix the problem we need to declare the method virtual *and* that the subclass "override"s the method. If we don't set Jet's method to override, we still get "300")

         class Plane {
      
            public virtual double TopSpeed() {
               return 300.0D;
            }
         }
         class Jet : Plane {
      
            public override double TopSpeed() {
               return 900.0D;
            }
         }
      

      This will not give "900" as the top speed. You can omit the virtual and override methods and be ok as long as you don't expect classes to ever be referred to as a superclass (which is extremely bad practice). For example:

      class Plane {
            public double TopSpeed() {
               return 300.0D;
            }
         }
         class Jet : Plane {
      
            public double TopSpeed() {
               return 900.0D;
            }
         }
         class Airport {
            [STAThread]
            static void Main(string[] args) {
               Plane plane = new Jet();
               Console.WriteLine("plane's top speed: {0}",plane.TopSpeed());
               Jet jet = new Jet();
               Console.WriteLine("jet's top speed: {0}",jet.TopSpeed());
               Console.ReadLine();
            }
         }
      
      This prints the following:

      plane's top speed: 300
      jet's top speed: 900
      
    14. Example of overloading an operator. Note many operators MUST be overloaded as a pair, eg, > , <

         public class Plane {
            public virtual double TopSpeed() { return 300.0D;}
            public static bool operator>(Plane one, Plane two) {   
               return one.TopSpeed() > two.TopSpeed();
            }
            public static bool operator<(Plane one, Plane two) {   
               return one.TopSpeed() < two.TopSpeed();
            }
         }
         class Jet : Plane {
            public override double TopSpeed() { return 900.0D; }
            public override string ToString() { return "I'm a Jet"; }
         }
            class Airport {
            [STAThread]
            static void Main(string[] args) {
               Plane plane = new Jet();
               Console.WriteLine("plane's top speed: {0}",plane.TopSpeed());
               Jet jet = new Jet();
               Console.WriteLine("jet's top speed: {0}",jet.TopSpeed());
               Console.WriteLine("Plane > Jet = {0}", plane > jet);
               Console.ReadLine();
            }
         }
      
      
    15. Example of using Properties instead of accessor methods. Note the special use of the "value" variable in "set".

      public class Plane {
            protected double mySpeed = 300.0D;
            public double TopSpeed { 
                                    get {return mySpeed;} 
                                    set { mySpeed = value; } 
                                    }
         }
         class Jet : Plane {
            public Jet() { TopSpeed = 900.0D; }
         }
            class Airport {
            [STAThread]
            static void Main(string[] args) {
               Plane plane = new Plane();
               Console.WriteLine("plane's top speed: {0}",plane.TopSpeed);
               Jet jet = new Jet();
               Console.WriteLine("jet's top speed: {0}",jet.TopSpeed);
               Console.ReadLine();
            }
         }
      
    16. Write the current time

      DateTime dt = DateTime.Now;
      Console.WriteLine("Current Time is {0} ",dt.ToString());
      

      To specify a format: dt.ToString("yyyy/MM/dd")

      The cultural-independent universal format: dt.ToString("u")
      which prints "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"

    17. Write a few lines to a file

      using System.IO;
      ...
      try {
       StreamWriter streamWriter = new StreamWriter("tmp.txt");
      
       streamWriter.WriteLine("This is the first line.");
       streamWriter.WriteLine("This is the second line.");
      } finally {
       if(streamWriter != null) {
           streamWriter.Close();
           }
      }
      
      
    18. Download a web page and print to console all the urls on the command line

      using System;
      using System.Net;
      using System.Text;
      using System.IO;
      namespace Test {
      
         class GetWebPage {
            public static void Main(string[] args) {
               for(int i=0;i<args.Length;i++) {
                  HttpWebRequest httpWebRequest =
                     (HttpWebRequest)WebRequest.Create(args[i]);
      
                  HttpWebResponse httpWebResponse =
                          (HttpWebResponse)httpWebRequest.GetResponse();
                  Stream stream = httpWebResponse.GetResponseStream();
                  StreamReader streamReader = 
                     new StreamReader(stream, Encoding.ASCII);
                  Console.WriteLine(streamReader.ReadToEnd());
               }
                  
               Console.Read();
            }
         }
      
      }
      
      
    19. Calculate Elapsed Time

       DateTime startTime = DateTime.Now;
       // do stuff
       TimeSpan elapsed = DateTime.Now - startTime;
       Console.WriteLine("response time: {0}",elapsed.TotalSeconds);
      
    20. How to convert a string to an integer, a string to a double, a sting to a date...

      using System;
      class Parse {
      /// <summary>
      /// Example of various Parse methods
      /// </summary>
      private static void Main() {
      
          //all the types in .Net have a Parse method
          int i = int.Parse("34");
          bool b = bool.Parse("true");
          double d = double.Parse("234.333");
          DateTime dateTime = DateTime.Parse("2008-03-02 12:20am");
          
          //TryParse will return false if the parsing fails
          int intvalue;
          bool ok = int.TryParse("42", out intvalue); //ok = True, intvalue = 42
          ok = int.TryParse("abc", out intvalue); //ok = False, intvalue = 0
          
          //ParseExtact takes a format
          DateTime dt = DateTime.ParseExact("02-03-2008", "dd-MM-yyyy",
              System.Globalization.CultureInfo.CurrentCulture); //dt = 3/2/2008 12:00:00 AM
      
          Console.Out.WriteLine("dt = " + dt);
          Console.In.ReadLine();
      }
      }
      
    21. How to convert a double to an integer

      System.Convert contains many nifty little conversion routines.

      Convert.ToInt32(mydouble);
      
    22. Tiny Browser

      Source Code.

    23. Example ASP.NET html code

      Print the time to a web page

       DateTime startTime = DateTime.Now;
       // do stuff
       TimeSpan elapsed = DateTime.Now - startTime;
       Console.WriteLine("response time: {0}",elapsed.TotalSeconds);
      

      Validate a textbox widget

      Enter your name 
      <asp:TextBox Runat=server id=TextBox1 />
              <asp:RequiredFieldValidator ControlToValidate=TextBox1
              Runat="server">
              You must supply a name.
              </asp:RequiredFieldValidator>
      
    24. Set an item in a dropdownlist as the currently selected

      System.Web.UI.WebControls.DropDownList StatusDropDownList;
      //...(add members)
      StatusDropDownList.Items[StatusDropDownList.SelectedIndex].Selected = 
          false;
      StatusDropDownList.Items.FindByValue(surveyDescriptor.Status).Selected = 
          true;
      
    25. Read a string from the console

      using System;
      class ReadLine
      {
          public static void Main()
          {
          Console.Write("Please enter your favorite animal: ");
          string animal = Console.ReadLine();
          Console.WriteLine("Good choice: " + animal);
          }
      }
      
      
    26. Read an xml file into a string

      using System;
      using System.IO;
      using System.Xml;
      
      class WriteXMLToString
      {
          //read an xml file and then write to a string 
          //(no error checking)
          //by mitchfincher@yahoo.com
          public static void Main(string[] args)
          {
          XmlDocument xmlDocument = new XmlDocument();
          xmlDocument.Load(args[0]);
          StringWriter stringWriter = new StringWriter();
          XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
          xmlTextWriter.Formatting = Formatting.Indented;
          xmlDocument.WriteTo(xmlTextWriter);
          xmlTextWriter.Flush();
          Console.Write(stringWriter.ToString());
          }
      }
      
      
    27. Read an xml file, twist it with an xsl file and then write to a string (no error checking)

      using System;
      using System.IO;
      using System.Xml;
      using System.Xml.Xsl;
      
      class WriteXMLViaXSL
      {
          //read an xml file, twist it with an xsl file and then write to a string (no error checking)
          //by mitchfincher@yahoo.com
          public static void Main(string[] args)
          {
          XmlDocument xmlDocument = new XmlDocument();
          xmlDocument.Load(args[0]);
      
          XslTransform xslTransform = new XslTransform();
          xslTransform.Load(args[1]);
      
      
          StringWriter stringWriter = new StringWriter();
          XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
          xmlTextWriter.Formatting = Formatting.Indented;
          xslTransform.Transform(xmlDocument, null, xmlTextWriter);
      
          xmlTextWriter.Flush();
          Console.Write(stringWriter.ToString());
          }
      }
      
    28. Creates an xml doc programatically and writes to the console and a file

      using System;
      using System.IO;
      using System.Xml;
      
      class CreateXMLDoc
      {
          //creates an xml doc programatically and writes to the console and a file
          public static void Main(string[] args)
          {
          XmlDocument xmlDocument = new XmlDocument();
              xmlDocument.PrependChild(xmlDocument.CreateXmlDeclaration("1.0", "", "yes"));
          XmlElement element = xmlDocument.CreateElement("Book");
          element.SetAttribute("author","Xenophone");
          element.AppendChild(xmlDocument.CreateTextNode("The Persian Expedition"));
          xmlDocument.AppendChild(element);
      
          StringWriter stringWriter = new StringWriter();
          XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
          xmlTextWriter.Formatting = Formatting.Indented;
      
          xmlDocument.WriteTo(xmlTextWriter);
          xmlTextWriter.Flush();
          Console.Write(stringWriter.ToString());
              //get the value of the enviromental variable "TEMP"
          string filename = 
              System.Environment.GetEnvironmentVariable("TEMP")+"\\Book.xml";
          //write to a file in temp directory also
          xmlDocument.Save(filename);
          }
      }
      
      
    29. To get a value from a form page

      private void Page_Load(object sender, System.EventArgs e) {
         string survey = Request.Params.Get("survey"));
         ...
      }
      
    30. To include the contents of a file inside an asp page

      <!--#include file="w:/mydir/data/Xsl/Footer.xsl" -->
      
      

      To read a file line by line.

      using System;
      using System.IO;
      
      public class Cat
      {
          public static void Main(string[] args) {
            string fileName = args[0];
            FileStream fileStream = null;
            try {
                  fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                  StreamReader sReader = new StreamReader(fileStream);
                  string line;
                  while ((line = sReader.ReadLine()) != null) {
                  	Console.WriteLine(line);
                  }
            } catch(Exception e) {
                Console.WriteLine(e);
            } finally {
               if(fileStream != null) {
                   fileStream.Close();
               }
            }
          }
      }
      
    31. Read the QueryString and print to web page

      using System.Collections;
      using System.Collections.Specialized;
      ...
       NameValueCollection collection = Request.QueryString; 
       String[] keyArray = collection.AllKeys; 
       Response.Write("Keys:");
       foreach (string key in keyArray) {
          Response.Write("
      " + key +": "); String[] valuesArray = collection.GetValues(key); foreach (string myvalue in valuesArray) { Response.Write("\""+myvalue + "\" "); } }
    32. Example of dumping collection objects to HTML

      public static string ToHTML(Hashtable hashtable) {
           string tmp = "";
           IDictionaryEnumerator myEnumerator = hashtable.GetEnumerator();
           while ( myEnumerator.MoveNext() ) {
              tmp += "<br />" + myEnumerator.Key+", "+ myEnumerator.Value;
           }
           return tmp;
        }
      public static string ToHTML(ArrayList arrayList) {
         StringBuilder tmp = new StringBuilder(); //needs System.Text;
         foreach ( Object o in arrayList ) {
            tmp.Append("<br />" + o);
         }
         return tmp.ToString();
      }
      
    33. How to pass a variable number of arguments to a method using the ''params' method parameter modifier

      'params' must be the last parameter in the list.

      using System;
      
      public class Params {
      
      static private void Test(string name, params int[] list) {
         Console.Write("\n"+name);
         foreach(int i in list) {
            Console.Write(i);
         }
      }
      
      public static void Main(string[] args) {
         Test("test",1,2,3);
         Test("retest",1,2,3,4,5);
      }
      
      }
      

      The result looks like this:

       test123
       retest12345
      
    34. Example of executing commands from a csharp program

       ///<summary>
       ///executes a system command from inside csharp
       ///</summary>
       ///<param name="cmd">a dos type command like "isql ..."</param>
       ///<param name ="millsecTimeOut">how long to wait on the command</param>
      
       public static int executeCommand(string cmd, int millsecTimeOut) {
          System.Diagnostics.ProcessStartInfo processStartInfo = 
             new System.Diagnostics.ProcessStartInfo("CMD.exe", "/C "+cmd);
          processStartInfo.CreateNoWindow = true;
          processStartInfo.UseShellExecute = false;
          System.Diagnostics.Process process = 
             System.Diagnostics.Process.Start(processStartInfo);
          process.WaitForExit(millsecTimeOut); //wait for 20 sec
          int exitCode = process.ExitCode;
          process.Close();
          return exitCode;
       }
      
    35. Get an XML document from a web service

      Example of retrieving an XML document from a web service and then applying an XSLT stylesheet on the server side.

          public class ScreenerQuestionsToAsk : System.Web.UI.Page
          {
            private void Page_Load(object sender, System.EventArgs e) {
               GetSurveyDescriptorXMLService service = new
                                                 GetSurveyDescriptorXMLService();
               XmlDocument xmlDocument = service.GetAllSurveyDescriptorsAsXMLDoc();
      
               string output = Util.WriteXMLViaXSL(xmlDocument,
                      "w:/mydir/data/Xsl/ScreenerQuestionsToAsk.xsl");
               Response.Write(output);
            }
          }
      
      
    36. Write XMLNodeList to Console

            public static string ToHTML(XmlNodeList xmlNodeList) {
               StringWriter stringWriter = new StringWriter();
               XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
               xmlTextWriter.Formatting = Formatting.Indented;
               foreach(XmlNode xmlNode in xmlNodeList) {
                  xmlNode.WriteTo(xmlTextWriter);
               }
               return stringWriter.ToString();
            }
      
    37. Returning an attribute from an XmlDocument

               string total = xmlDocument.SelectSingleNode("Surveys/Survey[@name='Beer']/cellName[@name='MatureBlueCollarMen']").Attributes.GetNamedItem("total").Value; 
      
      
    38. Exit message

        Console.WriteLine("Initialization failed. sorry.\r\n");
        System.Threading.Thread.Sleep(5000);  //same as java's Sleep()
        Environment.Exit(1);  //same as java's System.Exit(0);
      
    39. Tokenize string

      code to tokenize string into ArrayList

         string[] tokens = surveyName.Split(new char[] {':'});
         foreach (string item in tokens) {
            arrayList.Add(item);
         }
      
    40. Using "Split"

      Example of the StringSplitOptions.RemoveEmptyEntries option. This will remove the blank entries from the array.

      using System;
      class Animals {
      private static void Main() {
              string[] animals = "monkey,kangaroo,,,wallaby,,devil,,".Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
              foreach (string animal in animals) {
                  Console.Out.WriteLine("animal = " + animal);
              }
              Console.In.ReadLine();
          }
      }
      
    41. Adding elements to an ArrayList with AddRange

      Instead of repeatedly calling Add() to initialize an arrayList, AddRange() can be used with the default initializer for an array.

      ArrayList ab = new ArrayList();
      ab.Add("a"); //old fashioned way
      ab.Add("b");
      ArrayList abcd = new ArrayList();
      abcd.AddRange(new string[] {"a","b","c","d"}); // new hip method
      
    42. Arrays

      Arrays can be jagged like C or Java, or true MultiDimensional arrays

      int[] iArray = new int[150]; //simple 1D array
      
        int [][]myArray = new int[2][]; //jagged array
        myArray[0] = new int[3];
        myArray[1] = new int[9];
      
      //MultiDimensional array
        string[,] AgeArray2D = {{"age","Young","14","50"}, 
                                {"age","Old","51","100"}};
       
      

      Shorthand for creating single dimension arrays

       double[] readings = new double[]{1.0, 2.4, 0.5, 77.2};
      
    43. NUnit

      Creating a master "TestAll" file to run other NUnit tests

      using NUnit.Framework;
      ...
       public void TestAllTests() {
          Test.write("\r\nStarting "+Name+" ...\r\n");
          TestSuite testSuite = new TestSuite("All Tests");
          TestResult testResult = new TestResult();
          //run setup fixtures
          testSuite.RunTest(
            new MyApplication11.TestRebuildDatabase("TestRebuildDatabase"),testResult);
          testSuite.RunTest(
            new MyApplication11.TestPopulateDatabase("TestPopulateDatabase"),testResult);
          //run the tests
          testSuite.AddTestSuite(typeof(MyApplication11.Test));
          testSuite.AddTestSuite(typeof(MyApplication11.TestSimple));
          testSuite.Run(testResult);
      
          Test.writeLine("Completed "+Name+" at "+DateTime.Now+"\r\n");
        }
      
      
    44. Register a delegate

      Example of adding an InforMessage handler.

           public static void MessageEventHandler( object sender, SqlInfoMessageEventArgs e ) {
               foreach( SqlError error in e.Errors ) {
                  Console.WriteLine("problem with sql: "+error);
                  throw new Exception("problem with sql: "+error);
               }
            }
            public static int executeSQLUpdate(string database, string command) {
               SqlConnection connection = null;
               SqlCommand sqlcommand = null;
               int rows = -1;
               try {
                  connection = getConnection(database);
                  connection.InfoMessage += new SqlInfoMessageEventHandler( MessageEventHandler );
                  sqlcommand = connection.CreateCommand();
                  sqlcommand.CommandText = command;
                  connection.Open();
                  rows = sqlcommand.ExecuteNonQuery();
                } catch (Exception e) {
                  Console.Write("executeSQLUpdate: problem with command:"+command+"e="+e);
                  Console.Out.Flush();
                  throw new Exception("executeSQLUpdate: problem with command:"+command,e);
               } finally {
                  if(connection != null) { connection.Close(); }
               } 
               return rows;
            }
      
      
    45. Array sorting

      To sort an array use the static method on Array class. (I don't know why array.sort() does not exist as a method)

      String[] keyArray = nameValueCollection.AllKeys;
      Array.Sort(keyArray);
      
    46. Using XPath

      The tricky thing about getting the attribute value is using the function 'string()' inside your XPath expression. Otherwise it returns a nodeSetIterator that you have to process.

      using System.Xml;
      using System.Xml.XPath;
      ...
      XPathDocument xPathDocument = new XPathDocument(fileName);
      XPathNavigator xPathNavigator = xPathDocument.CreateNavigator();
      
      string text = (string) xPathNavigator.Evaluate("string(//Survey[@name='"+survey+"']/@URL)");
      
    47. ExecuteScalar

      Example of a utility function that uses ExecuteScalar, and a utility function to free resources.

      public static int getSQLAsInt(string database, string command) {
               int i = -1;
               SqlConnection connection = null;
               SqlCommand sqlcommand = null;
               try {
                  connection = UtilSql.getConnection(database);
                  sqlcommand = connection.CreateCommand();
                  sqlcommand.CommandText = command;
                  connection.Open();
                  i = (int)sqlcommand.ExecuteScalar();
               } catch (Exception e) {
                  throw new Exception(Util.formatExceptionError("getSQLAsInt",command,e));
               } finally {
                  UtilSql.free(null,connection);
               }
               return i;
            }
      public static void free(SqlDataReader reader, SqlConnection connection) {
               try {
                  if(reader != null) { reader.Close(); }
               } catch (Exception) {}
               try {
                  if(connection != null) { connection.Close(); }
               } catch () {} // we don't have to declare Exception
            }
      
    48. using block

      C# provides a special way of disposing of objects after their use - it's the "using" block. The object of the "using" statement must implement the IDisposable interface which contains one member, Dispose(). As shown below, after the "using" block is executed, Dispose() is immediately called.

      using System;
      namespace Doodle {
          class DisposableExample : IDisposable {
              public void Dispose() {
                  Console.Out.WriteLine("I'm being disposed!");
              }
              public static void Main() {
                  DisposableExample de = new DisposableExample();
                  using (de) {
                      Console.Out.WriteLine("Inside using.");
                  } //the compiler puts:  if(de != null) { de.Dispose(); }
                  Console.Out.WriteLine("after using.");
                  Console.In.ReadLine();
              }
          }
      }
      

      Produces:

      Inside using.
      I'm being disposed!
      after using.
      
    49. Example of using "using" to avoid the finally block mess

      a "using" block will execute its contents and then immediately call "Dispose()" on the using object. For connections, this will close the connection.

      using System;
      using System.Data.SqlClient;
      
      class Test {
          private static readonly string connectionString = "Data Source=myMachine; Integrated Security=SSPI; database=Northwind";
          private static readonly string commandString = "SELECT count(*) FROM Customers";
      
          private static void Main() {
              using (SqlConnection sqlConnection = new SqlConnection(connectionString)) {
                  using (SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection)) {
                      sqlConnection.Open();
                      int count = (int)sqlCommand.ExecuteScalar();
                      Console.Out.WriteLine("count of customers is " + count);
                  }
              }
              Console.In.ReadLine();
          }
      }
      
    50. Example of Parameterized SQL

      To avoid SQL injection attacks you should always use parameters

      using System;
      using System.IO;
      using System.Collections.Generic;
      using System.Text;
      using System.Data.SqlClient;
      using System.Data;
      
      namespace SQLTest {
      class SqlParameterization {
      /// 
      /// example of using parameterized sql to avoid SQL injection attacks
      /// 
         static void Main() {
            Console.Out.WriteLine("Authors whose state is CA:");
            SqlConnection sqlConnection = null;
            string dbconn = "Application Name=SqlTest; Data Source=localhost; Trusted_Connection=yes;  database=pubs";
            try {
              sqlConnection = new SqlConnection(dbconn);
              sqlConnection.Open();
      
              SqlCommand cmd = new SqlCommand("SELECT au_lname FROM Authors WHERE state = @state", sqlConnection);
              cmd.CommandType = CommandType.Text;
              SqlParameter param = new SqlParameter("@state", SqlDbType.Char, 2);
              param.Direction = ParameterDirection.Input;
              param.Value = "CA";
              cmd.Parameters.Add(param);
              SqlDataReader reader = cmd.ExecuteReader();
              while (reader.Read()) {
                 Console.WriteLine(String.Format("{0}", reader[0]));
              }
            } finally {
              if (sqlConnection != null) { sqlConnection.Close(); }
            }
            Console.In.ReadLine();
         }
       }
      }
      
      

      These lines

                 SqlParameter param = new SqlParameter("@state", SqlDbType.Char, 2);
                 param.Direction = ParameterDirection.Input;
                 param.Value = "CA";
      

      can be shortened to

                 SqlParameter param = new SqlParameter("@state", "CA");
      

      Since the default direction is "Input". Performance implications of the shortcut method are not known.

    51. Using SqlDataAdapter with Parameters

      conn = ... //connection string
      strSql = ... //sql string with @ variables like SELECT * FROM Authors WHERE name = @name
      DataSet dataSet = new DataSet();
      SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, conn);
      dataAdapter.SelectCommand.Parameters.Add(new SqlParameter("name", "OHenry"));
      dataAdapter.Fill(dataSet, "dataTable1"); 
      
    52. Getting property values from "Web.config" while in standalone test mode

      /// <summary>
      /// gets a property value from the Web.config file
      /// The problem with just using System.Configuration.ConfigurationSettings.AppSettings
      /// is that is doesn't work in standalone mode for unit testing e.g., nunit.cs
      /// </summary>
      /// <param name="property">property key name</param>
      /// <returns></returns>
          public static string getProperty(string property) {
            string propValue = "";
            try {
              if(System.Configuration.ConfigurationSettings.AppSettings.Count == 0) { 
                // we are in standalone mode
                XmlNodeList xmlNodeList = null;
                if(appSettings == null) {
                  XmlDocument xmlDocument = new XmlDocument();
                  //TODO: use the system environment or config methods instead
                  // of hardcoded path
                  xmlDocument.Load("c:/Inetpub/wwwroot/MyApplication11/Web.config");
                  xmlNodeList =
                  xmlDocument.SelectNodes("/configuration/appSettings/add");
                  if(verbose) {
                    Console.Write("xmlNodeList.Count = " + xmlNodeList.Count); 
                    Console.Out.Flush();
                  }
                  appSettings = new NameValueCollection();
              
                  foreach(XmlNode xmlNode in xmlNodeList) {
                    appSettings.Add(
                      xmlNode.Attributes.GetNamedItem("key").Value,
                      xmlNode.Attributes.GetNamedItem("value").Value);
                  }
                }
                propValue = appSettings[property];
              } else { //we are in web mode
                propValue = (string)System.Configuration.ConfigurationSettings.AppSettings[property];
              }
            } catch (Exception e) {
              throw new Exception(Util.formatExceptionError("getProperty","getProperty:"+property,e));
            }
            return propValue;
          }
      
      
    53. Use Reflection to print all the fields and their values in an object.

      Often its convenient to print the state of an object. Instead of overriding the ToString() method and explicitly printing each field, you can let C# do the work for you with a little bit of Reflection. You could even add code to recursively print the state of the composition objects as well. This is left as an exercise for the student.

        public override string ToString() {
          StringBuilder sb = new StringBuilder();
          System.Type type = this.GetType();
          sb.Append("\r\nInformation for "+type.Name);
          sb.Append("\r\nFields:");
          System.Reflection.FieldInfo[] fi = type.GetFields();
          foreach(FieldInfo f in fi) {
            sb.Append("\r\n  "+f.ToString()+ " = \""+ f.GetValue(this)+"\"");
          }
          System.Reflection.PropertyInfo[] pi = type.GetProperties();
          sb.Append("\r\nProperties:");
          foreach(PropertyInfo p in pi) {
            sb.Append("\r\n  "+p.ToString()+ " = \""+ p.GetValue(this,null)+"\"");
          }
          return sb.ToString();
        }
      
    54. Call a parent's constructor

      To call the parent's constructor:

      public Group(string xmlstring) : base (xmlstring) {
            
      }
      
    55. Append a node from text into an existing DOM.

      To import a new node into a DOM, we use the handy 'ImportNode()' method to avoid the 'not in document context' error.

        using System.Xml;
        using System.Xml.XPath;
        ...
        //create initial DOM
        XmlDocument xmlDocument = new XmlDocument(); 
        xmlDocument.LoadXml("<TextDefinitions name='DataSource'></TextDefinitions>");
        ...
        //add new node from xml text
        XmlDocument newXmlDocument = new XmlDocument();
        newXmlDocument.LoadXml("<text lang='en-UK' name='exit'>Goodbye</text>");
        XmlNode newNode = xmlDocument.ImportNode(newXmlDocument.DocumentElement,true);
        xmlDocument.DocumentElement.AppendChild(newNode);
      
    56. Get a text value from a DOM using XPath.

      Example C# fragment:

        using System.Xml;
        using System.Xml.XPath;
        ...
        //create initial DOM
        XmlDocument xmlDocument = new XmlDocument();
          ///   <TextDefinitions>
          ///     <TextDefinition name="DefaultDemographicText">
          ///        <Text lang="en-UK">Thanks for taking our survey.</Text>
          ///        <Text lang="fr-FR">Merci pour prendre notre apercu.</Text>
          ///     </TextDefinition>
          ///     <TextDefinition name="ExitText">
          ///        <Text lang="en-UK">Goodbye</Text>
          ///        <Text lang="fr-FR">Au revoir </Text>
          ///     </TextDefinition>
          ///   </TextDefinitions>
        xmlDocument.LoadXml("<TextDefinitions>  <TextDefinition name='DefaultDemographicText'>      <Text lang='en-UK'>Thanks for taking our survey.</Text>       <Text lang='fr-FR'>Merci pour prendre notre apercu.</Text>   </TextDefinition>   <TextDefinition name='ExitText'>       <Text lang='en-UK'>Goodbye</Text>       <Text lang='fr-FR'>Au revoir </Text>   </TextDefinition></TextDefinitions>");
        XPathNavigator xPathNavigator = xmlDocument.CreateNavigator();
        ...
      
         private string GetTextFromDOM(string textName,string lang) {
               string query = "string(/TextDefinitions/TextDefinition[@name='"+textName+"']/Text[@lang = '"+lang+"'])";
               string text = (string) xPathNavigator.Evaluate(query);
               if(verbose) { Util.write("GetTextFromDOM(\""+textName+"\", \""+lang+"\"): \""+text+"\""); }
               return text;
            }
         }
      
    57. How to return a single node using XPath expressions with the XmlDocument

          public static Survey GetSurvey(string groupName, string surveyName) {
               XmlDocument xmlSurveys = new XmlDocument();
               xmlSurveys.Load(filename);
               XmlNode xmlNode = (XmlNode) xmlSurveys.SelectNodes("//Survey[@name='"+surveyName+"']").Item(0);
      ...
            }
       
      
    58. Sort an ArrayList of non-trivial objects

      The IComparable interface needs to be supported. Fortunately, its only one method, CompareTo(Object obj).

      public class MyObject : ParentObject, IComparable {
      ...
      
      public int CompareTo(Object obj ) {
          MyObject myObject = (MyObject) obj;
          //priority is a double, which complicates matters, otherwise
          //  return this.priority-myObject.priority works well
          if(this.priority > myObject.priority) {
             return 1;
          } else if(this.priority < myObject.priority) {
             return -1;
          } else {
             return 0;
          }
       }
      }
      
      
      Then you can sort an ArrayList with "myObjectArrayList.Sort();" and C sharp will use your "CompareTo" method
    59. Example of using Interfaces

      As the following code shows, interfaces can be extended and, unlike classes, multiple interfaces can be extended

      using System;
      //example of interfaces
      public class Animals
      {
      //simple interface
      interface IAnimal {
        void Breathes();
      }
      //interfaces can inherent from other interfaces
      interface IMammal : IAnimal {
        int HairLength();
      }
      //interfaces can implement other interfaces which implemented interfaces
      interface IMarsupial : IMammal {
        int PouchSize();
      }
      //interfaces can implement many other interfaces
      interface IGonerMammal : IMammal, IExtinct {
      }
      interface IExtinct {
        int HowLongExtinct();
      }
      //classes can implement multiple interfaces
      public class TasmanianTiger : IGonerMammal, IMarsupial {
      public int PouchSize() { return 2; }
      public int HowLongExtinct() { return 28; }
      public int HairLength() { return 4; }
      public void Breathes() { }
      }
      
          public static void Main(string[] args) {
      	Console.Write("The Tasmanian Tiger has been extinct for {0} years", new TasmanianTiger().HowLongExtinct());
          }
      }
      
      
    60. Randomize C# ArrayList

      Utility to pseudo-randomize elements of an ArrayList in linear time
       public static void RandomizeArrayList(ArrayList arrayList, Random random) {
          if(arrayList == null) { return; }
          int count = arrayList.Count;
          for(int i=0;i<count;i++) {
             Object tmp = arrayList[i];
             arrayList.RemoveAt(i);
             arrayList.Insert(random.Next(count), tmp);
          }
       }
      
    61. Print out objects in Assmebly

               Assembly assembly = Assembly.GetAssembly(this.GetType());
               Type[] types = assembly.GetTypes();
               foreach(Type type in types) {
                  write("type="+type);
               }
      
    62. Sort an ArrayList with an internal class

      class MyClass() {
      ...
      
         public class comparer: IComparer {
               public comparer() {}
               public int Compare(object obj1, object obj2) {
                  return obj1.GetType().ToString().CompareTo(obj2.GetType().ToString());
               }
            }
      ...
      ArrayList arrayList = ...
      arrayList.Sort(new comparer());
      ...
      
    63. Create an instance of an object given its type

       object[]  paramObject = new object[] {};
       object obj = Activator.CreateInstance(type, paramObject);
      

      or
      string className = "MyType";
      MyType myType = (MyType) Activator.CreateInstance(Type.GetType(className), new object[]{});
      
    64. Using attributes on classes

      Example of using an attribute to determine if the associated SQL code for this object should be autogenerated. The Attribute code:

      using System;
      using System.Text;
      
      namespace MyApplication.Attributes {
      	[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
      	public sealed class GenerateSQL : Attribute {
      		public bool YesOrNo;
      		public GenerateSQL(bool YesOrNo) {
      			this.YesOrNo = YesOrNo;
      		}
      	}
      }
      

      The placing of the attribute in a class

      namespace MyApplication {
      	[GenerateSQL(false)]
      	public class KQLogic : SDObjectSAS {
      ...
      

      The retrieving of the attribute from classes.

      object[] attr = sdObjectDb.GetType().GetCustomAttributes(  Type.GetType("MyApplication.Attributes.GenerateSQL"),false);
      if(attr != null && attr.Length > 0) {
         MyApplication.Attributes.GenerateSQL gs = (MyApplication.Attributes.GenerateSQL)attr[0];
         if(gs.YesOrNo == false) { //class has attribute and its set to false
             ....
      
    65. Utility to write a string to a file, and append to file

           public static void WriteStringToFile(string fileName, string contents) {
               StreamWriter sWriter = null;
               try {
                  FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                  sWriter = new StreamWriter(fileStream);
                  sWriter.Write(contents);
               } finally {
                  if(sWriter != null) {
                     sWriter.Close();
                  }
               }
            }
            public static void AppendStringToFile(string fileName, string contents) {
               StreamWriter sWriter = null;
               try {
                  FileStream fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
                  sWriter = new StreamWriter(fileStream);
                  sWriter.Write(contents);
               } finally {
                  if(sWriter != null) {
                     sWriter.Close();
                  }
               }
            }
      
      
    66. Defining a web service

      Defining a web service is very easy. Add a reference to "System.Web.Services" in Visual Studio, add the "using System.Web.Services;" line in your code, subclass from "System.Web.Services.WebService" and finally put the "[WebMethod]" attribute on your method.

      ...
      using System.Web.Services;
      ...
         public class QuotaProxy : System.Web.Services.WebService {
      ...
            [WebMethod]
            public ArrayList GetSurveyStatus(string group, string lang, NameValueCollection DemographicResponses) {
      ...
      }
      
    67. Web Services

      To create a WSDL file for a service, just append "?wsdl" to the service name inside IE

      http://localhost/MyProject/Service1.asmx?wsdl
      
    68. Wrapper class for a WSDL

      Use the Wsdl.exe to read the WSDL document and create a wrapper class

      c:> Wsdl.exe "http://localhost/MyProject/Service1.asmx?wsdl"
      
    69. Calling one constructor from another

      //this constructor takes a single xmlElement argument, converts it to a string,
      //and calls the constructor that takes a string
      public SurveyStatus(XmlElement xmlElement) : this(To.ToText(xmlElement)) {}
      public SurveyStatus(string xmltext)  {
      ...
      }
      
      
    70. Global.asax Hooks

      'Global Event Handlers' can be set in this file

      protected void Application_Start(Object sender, EventArgs e) {
      	LogFile.WriteLine(" ** myApp Application starting at "+DateTime.Now);
      }
      
    71. Looking at an Assembly

      Code to trip through an assembly and print all public instance methods

           public void Coverage() { 
               writeMethodStart("Coverage");
               Assembly assembly = Assembly.LoadFrom("MyApplication.dll");
      		  foreach(Module module in assembly.GetModules()) {
      			  write("loading module "+module);
      			  Type[] types = module.FindTypes(null,null);
      			  foreach(Type type in types) {
      				  write(" ** "+type);
      				  MemberInfo[] memberInfoArray = type.GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly);
      				  foreach(MemberInfo memberInfo in memberInfoArray) {
      					  write("     "+memberInfo.Name+"()");
      				  }
      			  }
      		  }
      
    72. How to use Dev Studio Debugger with NUnit GUI tests

      From xprogramming.com: Mark your breakpoint in DevStudio and start the NUnit GUI. Inside DevStudio select "Debug/Process/nuit-gui.exe" then "Attach". A new window pops up, select "Common Language Runtime". Run the test inside the GUI and DevStudio will stop at the breakpoint (ok, well, it should stop there).

    73. Temporarily disabling an NUnit method

      /// <summary>
      /// test of remoting
      /// </summary>
      [Test]
      [Ignore("Service often is not started on remote machine")]
      public void GetProjectList() { 
      	writeMethodStart("GetProjectList");
      	QPManager manager = new QPManager();
      	string xml = manager.GetProjectList("Test1", "en-UK", "gender:male").ToXml();
              write("manager.GetProjectList:"+xml);
      	writeMethodEnd();
      }
      
    74. Testing for the throwing of an exception

      If this method throws an exception, it will pass the test. If it doesn't throw an exception, it will fail the test.

      [Test, ExpectedException(typeof(Exception))]
      public void Get() { 
      	writeMethodStart(MethodInfo.GetCurrentMethod().ToString());
      	DatabaseObject.Get("IDontExist");
      	writeMethodEnd();
      }
      
    75. Static Constructors

      This constructor is only called once before the first object of this type is called. (Is it guarenteed to be called if no objects of its kind are never created?) It can only reference static objects of course and it has no parameters.

      public class SDObjectRespondent : SDObject {
      	public static DatabaseProxy databaseProxy = null;
      	public SDObjectRespondent() {}
      	public SDObjectRespondent(string xmlstring) : base(xmlstring) {}
      	static SDObjectRespondent() { 
      		databaseProxy = new DatabaseProxy(Util.GetRequiredProperty("RespondentDatabase"));
      	}
      }
      
    76. How to convert a string to a byte array?

      Use the handy (if somewhat obscure) System.Text.Encoding.UTF8 class

      byte[] buffer3 =  System.Text.Encoding.UTF8.GetBytes(xmltext);
      

      Don't be tempted by the Dark Side to do the following:

      string xmltext = sb.ToString();
      len = xmltext.Length;
      buffer = new byte[len];
      buffer =  System.Text.Encoding.UTF8.GetBytes(xmltext);
      

      Since not all characters in strings map to a small friendly byte (remember our European friends?) the count of characters in strings does not equal the number of bytes.

    77. Printing the name of the currently executing method

      The following will print "Void ExistInDatabase()"

      public void ExistInDatabase() {
      System.Console.Write(System.Reflection.MethodInfo.GetCurrentMethod().ToString());
      }
      
    78. How to remove items in an ArrayList using Remove().

      It's a little trickier than just doing a foreach() loop because you will get a InvalidOperationException. Instead use a simple for loop with a decrementing counter and remove them off the end.

      public void Remove(ArrayList surveyNamesToRemove) {
      if(surveyNamesToRemove == null || surveyNamesToRemove.Count == 0) { return; }
      for(int i=(surveyStatuses.Count-1); i>=0; i--) {
      	if(surveyNamesToRemove.Contains(((SurveyStatus)surveyStatuses[i]).GetName())) {
      		surveyStatuses.RemoveAt(i);
      	}
      }
      }
      
    79. switch statement

      int respondentSource = 1;
      ...
      switch(respondentSource) {
      	case 1:
      		respondent = new DynamicRespondent(group,lang);
      		break;
      	case 2:
      		respondent = Respondent.Get(iteration+1);
      		break;
      	case 3:
                      string xmlString = "<Respondent userID='2' />";
      		respondent = new Respondent(xmlString);
      		break;
      	default:
      		throw new Exception("Invalid switch option \""+respondentSource+"\"");
      }
      ...
      
    80. Environment.StackTrace

      This method recursively dumps the information from an exception.

      /// <summary>
      /// Formats an exception to be human readable.  If the exception has
      /// an inner exception, it recurses and prints that too.
      /// The Environment.StackTrace is also printed, since the usual stacktrace is
      /// truncated at times.
      /// </summary>
      /// <param name="e">thrown exception</param>
      /// <returns>string containing human readable exception</returns>
      public static string FormatException(Exception e){
      	StringBuilder sb = new StringBuilder();
      	sb.Append("\r\n *************** Exception ***************");
      	sb.Append("\r\ne.Message:\""+e.Message+"\"");
      	sb.Append("\r\ne.StackTrace:\""+e.StackTrace+"\"");
      	sb.Append("\r\ne.Source:\""+e.Source+"\"");
      	sb.Append("\r\ne.TargetSite:\""+e.TargetSite+"\"");
      	sb.Append("\r\nEnvironment.StackTrace:\""+Environment.StackTrace+"\"");
      	//recurse into inner exceptions
      	if(e.InnerException != null) {
      		sb.Append("\r\n ***************   Inner   ***************");
      		sb.Append(FormatException(e.InnerException));
      	}
      	return sb.ToString();
      }
      
    81. Validate an xml file to a schema programatically

      See also O'Reilly's Indroduction to Schemas, Microsoft's Roadmap for XML Schemas in the .NET Framework and IBM's Basics of using XML Schema.

      /// <summary>
      /// validate an xml file to a schema
      /// </summary>
      /// <param name="xmlString">string representation of xml file</param>
      /// <param name="schemaString">string representation of schema</param>
      /// <returns>null if its happy, otherwise a string containing error messages</returns>
      public static string ValidateXML(string xmlString, string schemaString) {
      	XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xmlString));
      	XmlValidatingReader xmlValidatingReader = new XmlValidatingReader(xmlTextReader);
      	xmlValidatingReader.ValidationType = ValidationType.Schema;
      	XmlSchema xmlSchema = new XmlSchema();
      	xmlSchema = XmlSchema.Read(new StringReader(schemaString),null);
      	xmlValidatingReader.Schemas.Add(xmlSchema);
      	Validate validate = new Validate();
      	ValidationEventHandler validationEventHandler = new ValidationEventHandler(validate.Validator);
      	xmlValidatingReader.ValidationEventHandler += validationEventHandler;
      	while (xmlValidatingReader.Read());
      	return validate.errors;
      }
      /// <summary>
      /// tiny class so we can have a ValidationEventHandler and collect the errors
      /// </summary>
      private class Validate {
      	public string errors = null;
      	public  void Validator(object sender, ValidationEventArgs args) {
                 errors += args.Message + "\r\n";
      	}
      }
      
    82. Interface definition for Properties

      Properties may appear in an interace as the following example demonstrates:

      /// <summary>
      /// the inventory count for this item
      /// </summary>
      int inventory { get; set; }
      
    83. Dynamically invoking Static Methods

      How to invoke a static method on a dynamic object. This invokes the static method "Get(string name)" on a "myType" class object and returns an instance of a MyObjectType.

      using System.Reflection;            
      ...
      string objectType = "myType";
      //create an instance object
      MyObjectType objectTypeInstance =  (MyObjectType)Activator.CreateInstance(Type.GetType(objectType), null);
      //invoke static method and return an object of MyObjectType
      MyObjectType myObjectType = 
      	(MyObjectType)objectTypeInstance.GetType().InvokeMember ("Get",BindingFlags.Default | BindingFlags.InvokeMethod,null,null,new object [] {name});
      
    84. Dynamically invoking Instance Methods
    85. This example shows invoking an instance method on the "this" object, although any other object would work as well as long as you get the methodInfo object from its class.

      MethodInfo methodInfo = this.GetType().GetMethod("MyMethod");
      if(methodInfo != null) {	//invoke if method is really there
      		methodInfo.Invoke(this,param);
      }			
      ...
      
    86. Case-Insensitive Hashtable

      These are very handy when case doesn't matter.

       Hashtable hashTable = System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
      
    87. With C#2.0 you should really use a type-safe Dictionary collection instead of hashtable most of the time.

      Here is an example of using a Dictionary with a Guid key and a Survey object as a value.

      using System.Collections.Generic;
      ...
      private static Dictionary<Guid,Survey> surveyByIdDictionary = null;
      private static readonly object surveyByIdDictionaryLock = new object();
      /// <summary>
      /// return Survey object based on id.
      /// If the id requested does not exist, a null is returned.
      /// </summary>
      /// <param name="id">guid of the survey of interest.</param>
      /// <returns>survey or null</returns>
      public static Survey GetById(Guid id) {
         if (surveyByIdDictionary == null) {
             lock (surveyByIdDictionaryLock) {
                  if (surveyByIdDictionary == null) {
                      surveyByIdDictionary = new Dictionary<Guid, Survey>();
                      foreach (string surveyName in Survey.Default.GetNames()) {
                          Survey survey = Survey.Get(surveyName);
                          Survey.surveyByIdDictionary.Add(survey.id, survey);
                      }
                  }
              }
          }
          return surveyByIdDictionary.ContainsKey(id) ? surveyByIdDictionary[id] : null;
      }
              
      
    88. How to get the directory of an executing web app

      string baseDir = AppDomain.CurrentDomain.BaseDirectory.Replace("bin", "");
      
    89. Case insensitive string compares

      Can you image a more verbose way to do it?

      if(CaseInsensitiveComparer.Default.Compare(name1,name2) == 0) 
      

      Which is more preferable I think than

      if(name1.ToLower() == name2.ToLower()) 
      

      or you can use the string.Equals with an extra argument

       if ( ! string.Equals(name1,name1,StringComparison.CurrentCultureIgnoreCase))
      
    90. Using indexers

      You can override the "[]" operator to return whatever you wish

      /// <summary>
      /// indexer method to get SurveyStatus object by name
      /// </summary>
      public SurveyStatus this[ string surveyName] {
      	get {
      		foreach(SurveyStatus ss in surveyStatuses) {
      			if(CaseInsensitiveComparer.Default.Compare(surveyName, ss.GetName()) == 0) {
      				return ss;
      			}
      		}
      		return null;
      	}
      }
      
    91. IEnumerable Interface

      The IEnumerable interface (.Net 2.0) implements only one method, "GetEnumerator()". This is an easy way to iterate over collections using foreach. The yield statement returns control to the calling routine and then picks up exactly where it left off. This can be advantageous if creating the elements is expensive since you don't have to create them until called.

      using System;
      using System.Collections;
      class DaysOfWeek {
          public class Days : IEnumerable {
              readonly string[] days = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
              public IEnumerator GetEnumerator() {
                  for(int i=0;i<days.Length;i++) {
                      yield return days[i];
                  }
              }
          }
          static void Main() {
              foreach (string day in new Days()) {
                  Console.Write(day + " ");
              }
              Console.In.Read();
          }
      }
      
    92. Database Profiling Tip

      If you include the 'Application Name' in the connection string, the SQL profiler can show that to you. This makes db tuning easier.

      <add key="DB1ConnectionString" 
      
      value="Application Name=myAppName; Data Source=venus1; Trusted_Connection=yes; database=employees" />
    93. Show all the methods on an object

      using System.Reflection;
      ...
      MyObject myObject;
      foreach(MethodInfo meth in myObject.GetType().GetMethods()) {
      	Console.WriteLine(meth.ToString());
      }
      
    94. Creating a DOM programmatically

      [Test]
      new public void GenerateVenues() { 
      	writeMethodStart(MethodInfo.GetCurrentMethod().ToString());
      	
      	XmlDocument xdoc = new XmlDocument();
      	XmlElement root = xdoc.CreateElement("Schedule");
      	xdoc.AppendChild(root);
      	XmlElement day = xdoc.CreateElement("Day");
      	XmlAttribute date = xdoc.CreateAttribute("date");
      	date.Value = "2004/01/01";
             
      	day.SetAttributeNode(date);
      		XmlAttribute num = xdoc.CreateAttribute("number");
      	num.Value = "5";
      	day.SetAttributeNode(num);
      		root.AppendChild(day);
      		
      	write(To.ToText(xdoc));
      	writeMethodEnd();
      
      }
      
      

      This produces:

      <Schedule>
        <Day date="2004/01/01" number="5" />
      </Schedule> 
      
    95. Delegates

      Delegates are a refinement of method pointers in C, but with safty built in. The delegate object is bound to an method that takes the exact number and type of variables are arguments and returns the correct type.

      using System;
      
      public class DelegateTest
      {
      
      public static void PrintHello(string name) {
         Console.Write("Hello {0}!",name);
      }
          //define the MyPrinter type
          public delegate void MyPrinter(string s);
      
          public static void Main(string[] args) {
             //create an instance of MyPrinter delegate type
             MyPrinter myPrinter = new MyPrinter(PrintHello);
             myPrinter("Bill"); //invoke the delegate
          }
      }
      
    96. Asynchronous Delegate calls

      using System;
      //example of using Asynchronous Delegate calls
      public class DelegateTest
      {
      private static void Tick(int count) {
         for(int i=0;i<count;i++) {
           System.Threading.Thread.Sleep(1000); 
           Console.Out.WriteLine(".");
           Console.Out.Flush();
         }
      }
      public static string PrintHello(string name) {
         Tick(5);
         Console.Write("Hello {0}!",name);
         Tick(5);
         return name;
      }
      //define the MyPrinter type
      public delegate string MyPrinter(string s);
      
      public static void Main(string[] args) {
         //create an instance of MyPrinter delegate type
         MyPrinter myPrinter = new MyPrinter(PrintHello);
         IAsyncResult result = myPrinter.BeginInvoke("Bill",null,null);
         myPrinter("Uma");
         string tmp = myPrinter.EndInvoke(result);
         Console.Write("End of Program.  Returned value was "+tmp);
      }
      
      }
      
      
    97. Asynchronous Delegate calls with callback

      using System;
      using System.Runtime.Remoting.Messaging;
      
      //example of using Asynchronous Delegate calls with callback
      public class DelegateTest
      {
      public static void MyCallback(IAsyncResult iaresult) {
         AsyncResult result = (AsyncResult)iaresult;
         MyPrinter myPrinter = (MyPrinter)result.AsyncDelegate;
         Console.WriteLine("End of Program.  Returned value was "+myPrinter.EndInvoke(iaresult));
      }
      
      private static void Tick(int count) {
         for(int i=0;i<count;i++) {
           System.Threading.Thread.Sleep(1000); 
           Console.Out.WriteLine(".");
           Console.Out.Flush();
         }
      }
      public static string PrintHello(string name) {
         Tick(5);
         Console.Write("Hello {0}!",name);
         Tick(5);
         return name;
      }
      //define the MyPrinter type
      public delegate string MyPrinter(string s);
      
      public static void Main(string[] args) {
         //create an instance of MyPrinter delegate type
         MyPrinter myPrinter = new MyPrinter(PrintHello);
         IAsyncResult result = myPrinter.BeginInvoke("Bill",new AsyncCallback(MyCallback),null);
         myPrinter("Uma");
         //string tmp = myPrinter.EndInvoke(result);
         //Console.Write("End of Program.  Returned value was "+tmp);
      }
      
      }
      
      
    98. Sorted keys from a hashtable

      /// <summary>
      /// returns the keys of a hashtable in sorted order
      /// </summary>
      /// <param name="hashtable">unsorted type</param>
      /// <returns>sorted keys</returns>
      public static ArrayList GetSortedKeys(Hashtable hashtable) {
      	ArrayList arrayList = new ArrayList(hashtable.Keys);
      	arrayList.Sort(); //why couldn't Sort() return 'this' pointer?
      	return arrayList;
      }
      		
      
    99. "checked" keyword

      Oddly enough, by default, C# does not throw an exception for numerical overflows or underflows. To have C# check, you must use the "check" keyword, or configure your project to check all arithmetic.

      using System;
      //Example of using the "checked" keyword to catch over/under flows
      public class CheckedExample
      {
          public static void Main(string[] args) {
              int big = int.MaxValue - 1;
              int tooBig = big + 2; //overflow, but no error generated
              Console.WriteLine("big = {0}",big); 
              Console.WriteLine("tooBig = {0}",tooBig);
      
              try { 
                 checked {
                    tooBig = big + 2; //exception generated
                 }
              } catch (OverflowException e) {
                  Console.WriteLine(e.ToString());
              }
          }
      }
      
      

      The output is:

       big = 2147483646
       tooBig = -2147483648
       System.OverflowException: Arithmetic operation resulted in an overflow.
          at CheckedExample.Main(String[] args) in C:\home\mfincher\csharp\CheckedExample.cs:line 13
      
      
    100. How to convert one type of object to another using a cast

      using System;
      //hokey example of using explicit conversion
      public class Conversion
      {
      public class Circle {
         public double x,y,r;
         public Circle(double x, double y, double r) {
            this.x = x; this.y = y; this.r = r;
         }
      }
      
      public class Square {
         public double x,y,width;
         public Square(double x, double y, double width) {
            this.x = x; this.y = y; this.width = width;
         }
         public override string ToString() {
          return String.Format("Square x={0} y={1} width={2}",x,y,width);
         }
      //show the object how to cast a circle to be a square
         public static explicit operator Square(Circle circle) {
             return new Square(circle.x,circle.y,circle.r);
         }
      }
      
          public static void Main(string[] args) {
              Circle c = new Circle(1.0,1.0,2.0);
              Square s = (Square)c;
      	Console.Write("Converted circle to square!  "+s.ToString());
          }
      }
      
      
    101. How to return more than one object from a method call.

      Using the "out" or the "ref" parameter modifier will allow values to be returned.

      using System;
      //Example showing use of ref and out method parameter modifiers
      public class RefOut {
          public void test(out string text) {
      	text = "inside";
          }
          public static void Main(string[] args) {
      	RefOut refOut = new RefOut();
      	string text = "outside";
      	refOut.test(out text);
      	Console.WriteLine("text="+text);
          }
      }
      

      The results:

      text=inside
      

      What's the difference between "ref" and "out"? "ref" requires that an object is assigned before passing it to the method. "out" requires the method being called to assign a value the the variable.

      Example of using "ref"

      using System;
      class RefMagic {
      
       private void Renamer(ref string name) {
           name = "Joe";
       }
          static void Main() {
              string name = "Mike";
              Console.Out.WriteLine("name = " + name);
              RefMagic refMagic = new RefMagic();
              refMagic.Renamer(ref name);
              Console.Out.WriteLine("name = " + name);
              Console.In.Read();
          }
      }
      

      Produces:

      name = Mike
      name = Joe
      
    102. How to pass a variable number of arguments to a file

      Use the "params" modifier, which must be modifying the last argument.

      using System;
      class MyDoodle {
          //example of passing a variable number of arguments to a method
          private static int Addem(params int[] myarray) {
              int sum = 0;
              foreach (int i in myarray) {
                  sum = sum + i;
              }
              return sum;
          }
      
          static void Main() {
              Console.Out.WriteLine("sum = " + Addem());
              Console.Out.WriteLine("sum = " + Addem(1, 2));
              Console.Out.WriteLine("sum = " + Addem(1, 2, 3, 4, 5, 6));
              Console.In.Read();
          }
      }
      
    103. How to loop through a list of files in a directory

      This looks at all files ending in ".cs"

      using System;
      using System.IO;
      
      public class Temp
      {
          public static void Main(string[] args) {
          DirectoryInfo di = new DirectoryInfo(".");
      	foreach(FileInfo fi in di.GetFiles("*.cs")) {
      		Console.WriteLine("Looking at file \""+fi.FullName+"\"");
              }
         }
      }
      
      

      The results:

         Looking at file "C:\home\mfincher\csharp\Animals.cs"
         Looking at file "C:\home\mfincher\csharp\AsyncDelegateTest.cs"
         Looking at file "C:\home\mfincher\csharp\CheckedExample.cs"
         Looking at file "C:\home\mfincher\csharp\Conversion.cs"
      
    104. How to spawn a separate process and kill it.

      This launches an instance of the browser, waits 15 seconds and then closes it.

      using System;
      using System.IO;
      using System.Diagnostics;
      using System.Threading;
      
      public class Temp
      {
      	/// <summary>
      	/// Example of creating an external process and killing it
      	/// </summary>
      	public static void Main() {
          
          Process process = Process.Start("IExplore.exe","www.cnn.com");
          Thread.Sleep(15000);
          	try {
          		process.Kill();
          	} catch {}
         }
      }
      
    105. How to execute a background process repeatedly

      Using a Timer with a TimerCallback you can tell .Net to repeatedly invoke a method on a schedule. The code is a little verbose for instructional purposes.

      using System;
      using System.Threading;
      
      public class RegistrarProxy {
          private static Timer _timer;
          private static readonly TimerCallback _timerCallback = timerDelegate;
          
          public void Init() {
              _timer = new Timer(_timerCallback, null, 0, 2000); //repeat every 2000 milliseconds
          }
      
          private static void timerDelegate(object state) {
              Console.WriteLine("timerDeletegate: "+DateTime.Now);
          }
      
          public static void Main() {
              RegistrarProxy rp = new RegistrarProxy();
              rp.Init();
              Console.In.Read(); //let's wait until the "return" key pressed
          }
      }
      
    106. Example of Serialization using the Xml Formatter

      The binary and SOAP formatters are more useful in most situations.

      using System;
      using System.Xml;
      using System.Xml.Serialization;
      using System.IO;
      
      public class SerializeExample
      {
      	[Serializable]
      	public class Employee {
      		public string name;
      		public int yearOfBirth;
      		public Employee(string name, int yearOfBirth) {
      			this.name = name; this.yearOfBirth = yearOfBirth;
      		}
      		public Employee() {} //needed for serialization
      	}
          public static void Main(string[] args) {
      	Console.Write("starting serialization...");
          FileStream fileStream = File.Create("SerializeExample.xml");
          XmlSerializer xmlSerializer = 
                        new XmlSerializer(typeof(Employee),"Employee");
          xmlSerializer.Serialize(fileStream,new Employee("Achilles",1972));
          fileStream.Close();
          Console.Write("done.");
          }
      }
      
      

      Contents of the file:

      <?xml version="1.0"?>
      <Employee xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="Employee">
        <name>Achilles</name>
        <yearOfBirth>1972</yearOfBirth>
      </Employee>
      
    107. How to inject your company name etc. into the assembly

      By default dev studio creates a small file for you called "AssemblyInfo.cs". Inside are various assembly-level attributes. If you fill these in, then when the .dll is queried via a right mouse click and "Properties" selection, the information will appear in the dialog box.

      [assembly: AssemblyCompany("Acme Enterprises")]
      
    108. How to create an Enum value from the string representation

      public enum Action { run, walk, skip };
      
      string action = "Run";
      Action myaction = (Action)Enum.Parse(typeof(Action),action);
      
      if(myaction == Action.run) 
      ...
      
    109. Null Coalescing Operator, aka the double question mark operator

      The tertiary operator '?' has a friend, the '??' operator. If the value before the '??' is non-null, the value is returned. If the value is null, the value after the '??' is returned. The two statements below work identically.

             s = name != null ? name:"";
             s = name ?? ""; //returns "" if name is null, otherwise returns name
      
    110. To catch all the unhandled exceptions in a Page

      This will allow you to make sure all the errors encountered at the top level get logged.

      private void Page_Error(object sender, System.EventArgs e) {
      	Exception ep = Server.GetLastError();
      	LogFile.LogFatal(Util.FormatExceptionError("Page_Error","top level error", ep,4));
      	//Server.ClearError(); //we don't clear, but let the system produce message
      }
      
      

      To have the above run, it must be registered as a callback

      private void InitializeComponent() {    
      	this.Load += new System.EventHandler(this.Page_Load);
      	this.Error += new System.EventHandler(this.Page_Error);
      }
      		
      
    111. To store data in a respondent's session

      Session["favAnimal"] = "zebra";
      //and retrieve it later...
      string animal = (string) Session["favAnimal"];
      
    112. How an application can be notified of changes to a file

      You can set a FileWatcher to invoke a callback whenever a file is changed by an external force.

      using System;
      using System.IO;
      
      namespace DefaultNamespace
      {
      	/// <summary>
      	/// Description of Class1.	
      	/// </summary>
      	public class FileWatcher
      	{
      		public FileWatcher()
      		{
      		}
      		public static void Main() {
      			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
      			fileSystemWatcher.Path = "C:\\spy";
      			fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite;
      			
      			fileSystemWatcher.Filter = "*.txt";
      			fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
      			fileSystemWatcher.EnableRaisingEvents = true;
      			Console.Write("Listening for changes in 'C:\\spy' directory...press any key to exit");
      			Console.Read();
      			
      		}
      		
      		private static void OnChanged(object source, FileSystemEventArgs e) {
      			Console.Write("\r\nFile: {0} {1} {2}", e.FullPath, e.ChangeType, DateTime.Now);
      		}
      	}
      }
      
      
    113. How to write the name of a calling function.

      Use the handy StackTrace object as shown below. Note: the write() method is defined elsewhere.

      ...
       using System.Diagnostics;
      ...
      /// <summary>
       /// writes the name of the method that called it
       /// </summary>
       public void writeMethodStart() {
      	   StackTrace stackTrace = new StackTrace();
      	   StackFrame stackFrame = stackTrace.GetFrame(1);
      	   MethodBase methodBase = stackFrame.GetMethod();
      	   write("Method who called me was \""+methodBase.Name+"\"");
       }
            
      
    114. Get the contents of a web page as a string

      /// <summary>
      /// returns the contents of the webpage whose url is passed in
      /// No error handling is done.  If something goes wrong an exception is thrown even
      /// something as simple as not being able to close the connection.
      /// </summary>
      /// <param name="link">url to get</param>
      /// <returns>string of web contents</returns>
      private static string GetWebPage(string link) {
          HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(link);
          myRequest.Method = "GET";
          WebResponse webResponse = myRequest.GetResponse();
          StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
          string contents = streamReader.ReadToEnd();
          streamReader.Close();
          webResponse.Close();
          return contents;
      }
      
      
    115. To force .Net to use a proxy connection for web calls

      Add this to your web.config (inside the configuration element)

      <system.net>
         <defaultProxy>
            <proxy
               proxyaddress = "10.33.19.14:80"
               bypassonlocal = "true"
            />
         </defaultProxy>
      </system.net>
      
    116. How to bypass System.Web.UI.Page and write directly to requestor

      This is very useful in returning raw xml for AJAX invocations.

      using System;
      using System.Web;
       
      namespace RestDB {
      /// <summary>
      /// Example of using HttpHandler
      /// </summary>
      public class Rest : IHttpHandler {
      	public void ProcessRequest(HttpContext context) {
      		context.Response.Write("<h1>Houston we have contact!</h1>");
      	}
      	public bool IsReusable {
      		get { return true; }
      	}
      }
      }
      

      Add this snippet to your web.config

      <httpHandlers>
         <add verb="*" path="RestDB/*.aspx" type="RestDB.Rest,RestDB" />
      </httpHandlers> 
      
    117. How to write a gif to a browser request for an img tag

      This is useful when you need to know if a particular page has been viewed. Logic for recording the event is done elsewhere and then calls this routine.

      /// <summary>
      /// writes a gif image to the browser and closes the response object
      /// </summary>
      /// <param name="response">where to write the gif</param>
      /// <param name="absolutePath">where to read the gif</param>
      public static void WriteGif(System.Web.HttpResponse response,
      	string absolutePath) {
      	//TODO: cache images in hashmap with filename the key
      	FileStream fileStream;
      	long length = 0;
      
      	fileStream = new FileStream(absolutePath, FileMode.Open, FileAccess.Read);
      	length = fileStream.Length;
      
      	byte[] bBuffer = new byte[(int)length];
      	fileStream.Read(bBuffer, 0, (int)length);
      	fileStream.Close();
      
      	response.ClearContent();
      	response.ContentType = "image/gif";
      	response.BinaryWrite(bBuffer);
      	response.End();
      }
      
      
    118. Quick 'web service' call without the overhead

      If you only have a string to transmit between your server and client, you can cheat and use the "Response.StatusDescription" to pass a string message. In the Page_Load method of the server set the StatusDescription field of the Response object.

      private void Page_Load(object sender, System.EventArgs e) {
      ....
      Response.StatusDescription = "my tiny bit of information to transmit";
      ...
      }
      

      In the client, invoke a url on the server and look at the "StatusDescription" field for your tiny bit of info.

      string url = "http://...(your url goes here).......";
      HttpWebResponse resp = (HttpWebResponse)WebRequest.Create(url).GetResponse();
          
      string secretMessage = resp.StatusDescription; 
      
      
    119. How to add a javascript callback to an asp:checkbox.

      Unfortunately you can't simply add it in the HTML code. You have to go to the code behind page.

      private void Page_Load(object sender, System.EventArgs e)
      {
        if(!this.IsPostBack) {
          this.myCheckBox.Attributes.Add("onclick","javascript:myFunction()");
        }
      }
      
    120. Using cookies to set widget values

      private void Page_Load(object sender, System.EventArgs e)
      {
      	if(!this.IsPostBack) {
      		if(Request.Cookies["ExtraUrlParamsTextBox"] != null) {
      			ExtraUrlParamsTextBox.Text = Request.Cookies["ExtraUrlParamsTextBox"].Value;
      		}
      
      	}
      	if(this.IsPostBack) {
      		Response.Cookies["ExtraUrlParamsTextBox"].Value = ExtraUrlParamsTextBox.Text;
      	}
      }
      
    121. Setting a Cookie

      HttpCookie myCookie = new HttpCookie("myName");
      myCookie.Value = groupDropDown.SelectedItem.Text;
      myCookie.Expires = DateTime.Now.AddMonths(6);
      Response.Cookies.Add(myCookie);
      
    122. Getting a Cookie

      if (Request.Cookies["myName"] != null)
      {
      	itemSelected = Request.Cookies["myName"].Value;
      }
      
      
      
  2. Misc Notes:
    1. To view an assembly in gui using a tree structure use the handy Intermediate Language Disassembler (ildasm):
      c:\...\bin>ildasm myassemblyname.dll
    2. Dotnetfx.exe

      If your target machine may not have .Net installed, you can install Dotnetfx.exe during your program's installation and Dotnetfx will install the .Net framework.

    3. machine.config

      'machine.config' control's the settings for ASP.Net. It is found in a directory like "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG".

    4. To allow remote testing of web services

      For security reasons, only clients on the local host can access the web page version of a web service. To allow any client to access the service, put the following in the web.config inside the "system.web" element. This gets rid of the "The test form is only available for requests from the local machine." message.

      <!-- to allow remote access to web services -->
           <webServices> 
              <protocols>
                  <add name="HttpSoap1.2"/>
                  <add name="HttpSoap"/>
                  <add name="HttpGet"/> 
                  <add name="HttpPost"/> 
              </protocols> 
          </webServices> 
      
      
    5. The Main method can take 3 forms: "static void Main()","static int Main()",or "static int Main(string[] args)"
    6. Typical output: "System.Console.WriteLine("Howdy World!");"
    7. In VS.NET, to get the docs on an object, highlight it and press 'F1'
    8. To launch the Object Browser: View/Other Windows/Object Browser or Ctl-Alt-J
    9. To add namespaces to the object browser, in the Solution Explorer, right click on the "References" tag and select "Add..."
    10. Using an "@" in front of a string turns off escape substitutions, e.g.,, @"C:\" == "C:\\"
    11. Three ways to initialize an array

      int [] a = new int[10]; a[0] = 1; a[1] = 2;
      int [] b = new int[] { 1, 2 };
      int [] c = { 1, 2 };
    12. Our old friends, 'Preprocessor' commands, are available

      #if (DEBUG)
      ....
      #endif
      
      #warning remove next debug line from the code before release
      Console.Error.WriteLine("userID:"+userID+" : "+To.ToText(someObject));
      
    13. The 'checked' and 'unchecked' operators are used to turn on and off arithmetic exceptions, e.g.,, int x = unchecked(a * b);
    14. Enumerations
      enum Sizes {Tall, Grande, Venti};  //by default assigned to 0,1,2
      enum Sizes {Tall=1, Grande=2, Venti=4}; // can be overridden
      enum Sizes : byte {Tall, Grande, Venti}; //specify the size of the enum
      

      Enums in C# are well developed and have many interesting methods. Enums derive from System.Enum which contain methods like Format() and GetName(). My favorite is ToString(). GetValues() will return all the possible values of an enum.

    15. Struct

      Structures are similar to classes but do not have inheritance and, although created with the 'new' operator, they live on the stack.

    16. "using" keyword

      Ambiguity with class names may be resolved by the "using" keyword.

      using Set = MyUtil.Set;
      

      This tells the compiler that all instances of 'Set' in the rest of the file are references to 'MyUtil.Set'. This would be helpful if 'Set' becomes a real collection class in a future release of .Net and you have coded your own.

    17. "readonly" and "const" keywords
      public const string myValue = "abc"; //myValue cannot be changed.  Set at compile time.
      public readonly string myFutureValue; //this can be set only once at declaration or in the constructor
      

      const is set at compile time, and readonly at runtime.

    18. "is" keyword

      tests to determine if an object is of a particular type

      if(myShape is Circle) {
      ...
      }
      
    19. "as" keyword

      similar to a type cast, but if the object is not what is expected, "as" returns a null

      Circle c = myShape as Circle;
      if(c != null) {
      ...
      }
      
    20. "base" is similiar, but not identical to, Java's "super" to access a parent's members.
    21. To read a double from a string: Console.Out.WriteLine("d = {0}",Double.Parse("1.02"));
    22. Use "sealed" as a method modify so no subclass can extend the class ( like java's "final")
    23. The Object class has four methods: ToString(), Equals(), GetHashCode(), and GetType(). The first two should be overridden. Example,
      public override string ToString() { return "I'm a Jet"; }
      
    24. Member Accessibility
      1. public - available to all code
      2. protected - accessible only from derived classes
      3. private - accessible only from within the immediate class
      4. internal - accessible only from within the same assembly
      5. protected internal - accessible only from within the same assembly or from classes extending classes from this assembly
    25. Instead of using Java's "instanceof", C# uses the "is" operator. The "as" operator in C# is somewhat similar, but does more work.
  3. Installing a Service via Nant

    Hate typing in username and passwords? Let Nant do the work for you

    <target name="uninstall">
      <echo message="uninstalling..." />
      <exec program="installUtil.exe"
            basedir="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" 
            workingdir="C:\workfiles\throttler\src\Harvester\bin\debug"
            commandline="/u Harvester.exe"
            failonerror="false"
            />
    </target>
    
    <target name="install" depends="uninstall"  >
      <echo message="installing..." />
      <exec program="installUtil.exe"
            basedir="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" 
            workingdir="C:\workfiles\throttler\src\Harvester\bin\debug"
            commandline="/user=mydomain\myuser /password=mypassword Harvester.exe"
            />
    </target>
    

    Inside the installer program, read the values

    /// <summary>
    /// Sets the username and password for the service
    /// </summary>
    /// <param name="savedState"></param>
    protected override void OnBeforeInstall(IDictionary savedState)
    {
        base.OnBeforeInstall(savedState);
        this.serviceProcessInstaller1.Username =
            this.Context.Parameters["user"].ToString();
        this.serviceProcessInstaller1.Password =
            this.Context.Parameters["password"].ToString();
    
        this.serviceProcessInstaller1.Account =
            System.ServiceProcess.ServiceAccount.User;
    }
    
    
  4. Using Nullable Types

    In C# 2.0 we can use nullable types which are like regular objects but have a "HasValue()"

    using System;
    class Nullable {
        static void Main() {
            int? i = null;
            Console.Out.WriteLine("i = " + i);
            Console.Out.WriteLine("i.HasValue=" + i.HasValue);
            i = 6;
            Console.Out.WriteLine("i = " + i);
            Console.Out.WriteLine("i.HasValue=" + i.HasValue);
            Console.In.Read();
        }
    }
    
  5. How to write a message to the Event Log

    This tiny helper function creates the entry and closes it. The "source" argument is the name of your application

    ...
    WriteMessage("MyProgram",e.ToString(),System.Diagnostics.EventLogEntryType.Error);
    ...            
    private static void WriteMessage(string source, string message, System.Diagnostics.EventLogEntryType type) {
        System.Diagnostics.EventLog oEV = new System.Diagnostics.EventLog();
        oEV.Source = source;
        oEV.WriteEntry(message, type);
        oEV.Close();
    }
    
    
  6. Using generics in a list.

    Our old friendly collection, ArrayList, is alas not in Generics. Instead we use the List collection.

    using System.Collections.Generic;
    ...
    public List<XmlObject> GetChildren(string typeName) {
         List<XmlObject> list = new List<XmlObject>();
         foreach (XmlObject xmlObject in Children) {
             if (xmlObject.GetType().ToString()
                 == (NameSpace + typeName)) {
                 list.Add(xmlObject);
             }
         }
         return list;
     }
    
  7. Get the current directory of an executing program if running as a service

    System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase.ToString()
    
    or
    new System.IO.FileInfo(Assembly.GetCallingAssembly().Location).Directory.ToString()
    
  8. Example of using Regular Expressions

    Testing if each line in a data file conforms to a regular expression

    private bool TestPanelistFile(TextWriter textWriter, string fileName) {
    	textWriter.WriteLine("Testing "+fileName);
    	StreamReader sr = new StreamReader(fileName);
    	//example line:
    	//"LUK09","g9002827491","DJH4W","Stopped By Signal","01/06/2006"
    	System.Text.RegularExpressions.Regex exp = 
    		new System.Text.RegularExpressions.Regex(
    		"\"[a-zA-Z0-9]+\",\"[a-zA-Z0-9]+\",\"[a-zA-Z0-9]+\",\"(Completed Successfully|Stopped By Signal)\",\"\\d\\d/\\d\\d/\\d\\d\\d\\d\""
    		);
    	int i=0;
    	string line = "";
    	while((line = sr.ReadLine()) != null) {
    		i++;
    		if( ! exp.IsMatch(line)) {
    			textWriter.WriteLine("\r\nError in input file on line "+i);
    			textWriter.WriteLine("  bad line: "+line);
    		} else {
    			if(i % 500 == 0) { textWriter.Write("."); }
    		}
    	}
    	return false;
    }
    
    
  9. Using Regular Expression to loop over matches

    /// <summary>
    /// takes a sql string with @parameters 
    /// ( SELECT * FROM table WHERE name = @name and lang = @lang) 
    /// and returns a string array with the names of all the parameters 
    /// e.g.,  {"name","lang"}
    /// </summary>
    /// <param name="cmd">sql string with '@' prefacing parameters</param>
    /// <returns>array like, {"name","lang"}</returns>
    private static string[] GetVariables(string cmd)
    {
        Regex rexp =new Regex("@[a-zA-Z0-9]+");
        MatchCollection matches = rexp.Matches(cmd);
        string[] strings = new string[matches.Count];
        for(int i=0;i<matches.Count;i++) {
        strings[i] = matches[i].ToString().Remove(0,1);
        }
    return strings;
    }
    
  10. Regular Expression to replace substring matches

    /// <summary>
    /// converts between the old style sql commands and parameterized.
    /// changes '$(xyz)' to @xyz.  e.g., "'$(name)'" returns "@name"
    /// 
    /// </summary>
    /// <param name="cmd">string to translate</param>
    /// <returns>string with updated params</returns>
    public static string ReplaceWithParameterizedArgs(string cmd) {
      Regex rexp = new Regex("'\\$\\(([a-zA-Z0-9]+)\\)'");
    # this replaces the entire match with the inner match only
      string result = rexp.Replace(cmd, "@$1");
      return result;
    }
    
    ...
    
    [Test]
    public void ReplaceWithParameterizedArgs() {
      writeMethodStart(MethodBase.GetCurrentMethod().ToString());
      Assert.AreEqual("@name   @test", 
        Util.ReplaceWithParameterizedArgs("'$(name)'   '$(test)'"));
      Assert.AreEqual("SELECT * FROM mytable where name = @name",
        Util.ReplaceWithParameterizedArgs("SELECT * FROM mytable where name = '$(name)'"));
      Assert.AreEqual("", Util.ReplaceWithParameterizedArgs(""));
    }
    
  11. Visual Studio Regular Expression Editing tips

    VS provides regular expressions in replacing string which can be a lifesaver. Here's a few examples of operations to be performed on many files:

    1. Removing an xml attribute

      What the RE means: Find the string "<Survey " followed by a bunch of characters, followed by the string "cluster=" followed by a bunch of non-space characters. Replace with just the "<Survey " and the characters before "cluster".

      regex:  to delete the attribute "cluster" from the "Survey" element:
      Find What: \<Survey {.*} cluster=[^ ]*
      Replace With: \<Survey \1
      
    2. Rename an attribute

      In this case I want to rename the "Survey" element's 'id' attribute to 'registrarId', but not the other elements' 'id' attribute. The element name and the attribute to change must be on the same line for this to work. A tiny sliver of regular expression in the "Find and Replace" dialog did the trick: The "Find What" says find "<Survey " followed by any characters followed by " id=". The "\1" takes the value of all the characters skipped with the {.*}.
      Find What:  \<Survey {.*} id=
      Replace with: \<Survey \1 registrarId=
      
  12. How to get the version number of your assembly?

    This will print the version set in Properties/AssemblyInfo.cs.

    Console.WriteLine("version:"+Assembly.GetExecutingAssembly().GetName().Version.ToString());
    
  13. Finalize

    C# provides a way to release resources when an object dies. Like in C++, the destructor has the same name as the class with a "~" prefix.

    using System;
    public class Destructo {
    	~Destructo() {
    		Console.WriteLine("Help, I'm being destroye.#@@!@##");
    	}
    	public static void Main(string[] args) {
    		new Destructo();
    		new Destructo();
        }
    }
    

    This produces the following, but not reliably since the Console.Out may have been closed by then.

                Help, I'm being destroye.#@@!@##
                Help, I'm being destroye.#@@!@##
    
  14. CLSCompliant

    Using the CLSCompliant(true) attribute marks the assembly as being Common Language Specification compliant, so VB and other .Net languages can use your assembly. When compiling with this attribute, the compiler warns you with the error message CS3008 of non-compliant issues like exposed variable names differing only in case.

    ...
    using System.Xml;
    
    [assembly: CLSCompliant(true)]
    namespace MyComponents {
    
  15. Using Regular Expressions in Visual Studio for Replacing text

    If you have lots of test xml files for creating objects and you need to add a new attribute, it's easy with regular expressions. For example, if you need to add "newattribute='1'" to all "Survey" elements scattered over many files like this one:

    <Survey name='MoonManA' groupName='Baseline' priority='1' status='1' cellLimiter='100' surveyLimiter='100' dateStart='2004-01-10T08:00:00' dateEnd='2007-10-30T16:30:00' exclusions='0' cluster='Cluster1' >
    

    Enter "control-h" to bring up the Replace dialogue box and select the "Use:" check box in the lower left corner and make sure it displays "Regular expressions". Then enter these:

    "Find what:" \<Survey {[^\>]*}\>
    "Replace with:" <Survey  \1newattribute='0'>
    

    This will match all characters between "<Survey" and the ">". Putting the expression in braces allows you to use the "\1" syntax to place in the matched characters. The final result is

    <Survey name='MoonManA' groupName='Baseline' priority='1' status='1' cellLimiter='100' surveyLimiter='100' dateStart='2004-01-10T08:00:00' dateEnd='2007-10-30T16:30:00' exclusions='0' cluster='Cluster1' newattribute='0' >
    
    
  16. Delegates

    Delegates are type-safe function pointers.

    // CalculateTax is a delegate that takes a double and returns a double
    public delegate double CalculateTax(double x);
    static public double StateTax(double x) { return x * 0.05; }
    static public double FederalTax(double x) { if (x > 1000.0) return x * 0.02; else return 0.0; }
    static void Main(string[] args) {
        CalculateTax stateDelegate = new CalculateTax(StateTax);
        CalculateTax federalDelegate = new CalculateTax(FederalTax);
        double amountOfPurchase = 12.99;
        Console.WriteLine("{0}", stateDelegate(amountOfPurchase));
        Console.WriteLine("{0}", federalDelegate(amountOfPurchase));
    
        Console.In.ReadLine();
    
  17. Anonymous methods

    You can do the same as above with a cleaner look by using anonymous methods:

    // CalculateTax is a delegate that takes a double and returns a double
            public delegate double CalculateTax(double x);
            static void Main(string[] args) {
                CalculateTax stateDelegate = delegate(double x) { return x * 0.05; };
                CalculateTax federalDelegate = delegate(double x) { if (x > 1000.0) return x * 0.02; else return 0.0; };
                double amountOfPurchase = 12.99;
               Console.WriteLine("{0}", stateDelegate(amountOfPurchase));
                Console.WriteLine("{0}", federalDelegate(amountOfPurchase));
    
                Console.In.ReadLine();
            }
    
  18. Lambda Expressions

    We can make this even shorter by using a lambda expression:

     // CalculateTax is a delegate that takes a double and returns a double
            public delegate double CalculateTax(double x);
            static void Main(string[] args) {
                CalculateTax stateDelegate = x => x * 0.05;
                CalculateTax federalDelegate = x => { if (x > 1000.0) return x * 0.02; else return 0.0; };
                double amountOfPurchase = 12.99;
    
                Console.WriteLine("{0}", stateDelegate(amountOfPurchase));
                Console.WriteLine("{0}", federalDelegate(amountOfPurchase));
    
                Console.In.ReadLine();
            }
    
  19. Extension Methods

    In C#3.0 one of the very cool concepts is "Open Classes" where you can add methods to existing classes. In C# parlance this is an extension method. Below is an example of adding a new method to our old friend "string".

    using System;
    namespace PlayingAround {
        public static class MyStringExtensionClass {
            //wraps an xml tag around a string
            public static string Wrap(this string s, string tag) {
                return "<" + tag + ">" + s + "</" + tag + ">";
            }
        }
        class TestMe {
            static void Main(string[] args) {
                Console.WriteLine("Warning".Wrap("h1"));   // <h1>Warning</h1>
                Console.In.ReadLine();
            }
        }
    }
    
  20. Local Variable Type Inference

    The compiler can infer the type of a variable from the expression on the right side.

    var i = 6;
    Console.Out.WriteLine("i=" + i);
    
  21. Object Initialization in C# 3.0

    Objects can now be initialized in a more concise manner as shown below:

    ...
    public class House {
        public double price;
        public int stories;
        public string exterior;
    }
    
    class TestMe {
        static void Main(string[] args) {
            //old style
            House myOldHouse = new House();
            myOldHouse.price = 200000.00;
            myOldHouse.stories = 1;
            myOldHouse.exterior = "wood";
            //new style
            House myNewHouse = new House { price = 250000.00, stories = 2, exterior = "brick" };
            Console.In.ReadLine();
        }
    }
    
  22. Anonymous Types

    We can create anonymous type. The compiler will give our creation a name for us.

    var animal = new
    {
        IsMammal = true,
        Name = "lion"
    };
    Console.Out.WriteLine("Name=" + animal.Name);
    Console.Out.WriteLine("is mammal? " + animal.IsMammal);
    
  23. Aggregation

    Aggregators are extension methods that acto on IEnumerable<T>

    int[] ints = { 1, 3, 5, 7 };
    Console.WriteLine(ints.Sum());  // 16
    
    Console.WriteLine(ints.Min());  // 1
    Console.WriteLine(ints.Max());  // 7
    Console.WriteLine(ints.Average());  // 4
    
  24. Recommended Books:
    Click to read reviews or buy Programming C# Programming C# Click to read reviews or buy C# and the .NET Platform, Second Edition C# and the .NET Platform, Second Edition
  25. My favorite C# links:
    1. OpenSource C# projects.
    2. web security (not directly a C# issue, but important).
    3. ORMapper.com a sneak peak at ObjectSpaces, except this one works now.
    4. Microsoft's list of dotnet and csharp tools.
    5. weblogs.asp.net the heavy weights of .Net.
    6. msdn c# site.
    7. codeproject's list of code snippets and discussions .
    8. dotnetforums.
    9. Testing with NUnit.
    10. builder.com.com notes on strong naming and microsoft's note on how to fix "Assembly Generation Failed" Error Message When You Try to Build a Managed DLL Without a Strong Name
    11. zip library
    12. a logging library
    13. http://www.developer.com/net/net/article.php/1756211
    14. CodeDOM a language independent code writer.
    15. http://nunit.org for version 2.0
    16. mantrotech
    17. Sisyphus Persistence Framework
    18. http://groups.msn.com/dotnetpersistence
    19. list of UML Modeling Tools
    20. www.gotdotnet.com/
    21. Austin .Net Users Group (2nd Monday of the month) and the Austin special interest which meets the following Wednesday at Catapult.
    22. Nunit overview for Junit users
    23. How to create a "servlet" in csharp
    24. Wonderful conversion document from java syntax to C#
    25. http://www.csharp-station.com/Tutorials/Lesson01.aspx
    26. nunit a JUnit clone, a must for testing.
    27. net-language csharp code examples
    28. Comparison with Java
    29. Oreillynet.com on C#
    30. Download 131 Meg SDK for .Net.
    31. http://msdn.microsoft.com intro with c#
    32. http://www.csharp-station.com/
    33. http://www.learn-c-sharp.com
    34. ecma specification for C# and the 5 components of CLI including the C# language itself
    35. c-sharpcorner.com
    36. Comparison with Java
    37. http://www.csharphelp.com/
    38. XML and C Sharp
    39. www.sqlxml.org
  26. ASP.NET notes

    Types of files

    1. .aspx.cs - web forms, like jsp pages
    2. .ascx.cs - c# code objects
    3. .asmx - web services
    4. .asax - global objects
    5. .ashx - http modules

    Three types of controls

    1. HTML server controls
    2. Web server controls
    3. Validation
  27. Notes on .NET. The Common Language Infrastructure (CLI) consists of 5 parts
    1. Partition I - Architecture
      1. Common Lanugage Specification (CLS)

        rules that guarantee one language can interoperate with others if it follows the specification

      2. Common Type System (CTS)
        Type
        1. Value Types
          1. Built-in Value Types
            1. Integer Types
            2. Floating Point Types
            3. Typed References
          2. User Defined
            1. Enums
      3. Virtual Execution System (VES)
    2. Partition II - Metadata
    3. Partition III - Common Intermediate Language (CIL) bytecode
    4. Partition IV - Library
    5. Partition V - Annexes
<<<Prev   1   2   3   Next > > >