Saturday, October 8, 2011

C Sharp By Examples 1

Here's an arrangement of code samples for learning C#.
Code Samples:

< Prev  1 2 3 4  Next > 
  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
      C:>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. Reading Stuff
      1. Read an entire file into a string
        using System;
        namespace PlayingAround {
            class ReadAll {
                public static void Main(string[] args) {
                    string contents = System.IO.File.ReadAllText(@"C:\t1");
                    Console.Out.WriteLine("contents = " + contents);
                }
            }
        }
      2. Read a file with a single call to sReader.ReadToEnd() using streams
        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;
        }
      3. Read all the lines from a file into an array
        using System;
        namespace PlayingAround {
            class ReadAll {
                public static void Main(string[] args) {
                    string[] lines = System.IO.File.ReadAllLines(@"C:\t1");
                    Console.Out.WriteLine("contents = " + lines.Length);
                    Console.In.ReadLine();
                }
            }
        }
      4. Read a file line by line with no error checkingUseful if the file may be really large.
        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 a "finally" or "using" block
    4. Writing Stuff
      1. Easy writing all text to a fileWriteAllText will create the file if it doesn't exist, otherwise overwrites it. It will also close the file.
        using System;
        namespace PlayingAround {
            class ReadAll {
                public static void Main(string[] args) {
                    string myText = "Line1" + Environment.NewLine + "Line2" + Environment.NewLine;
                    System.IO.File.WriteAllText(@"C:\t2", myText);
                }
            }
        }
        Top rated books on CSharp Programming:
      2. Write a line to a file using streams
        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(); }
         }
        }
        }
        
      3. 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 cause problems.
        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();
            }
        }
        
      4. "using" as "typedef" (a la "C")"C" allows you to alias one type as another with typedef. In C# you can do this with "using" (can we create another overload for "using" just to make it more confusing?) Everywhere the type "RowCollection" is used, C# will understand it to be of type "List<Node>"
        using RowCollection = List<Node>;
      5. 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);
        }
      6. Write a very simple XML fragment the easier 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());
      7. To write any object or some collections to xmlObject must have a default constructor.
        public static string SerializeToXmlString(object objectToSerialize) {
            MemoryStream memoryStream = new MemoryStream();
            System.Xml.Serialization.XmlSerializer xmlSerializer = 
                new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
            xmlSerializer.Serialize(memoryStream, objectToSerialize);
            ASCIIEncoding ascii = new ASCIIEncoding();
            return ascii.GetString(memoryStream.ToArray());
        }
      8. And this should turn the xml back into an object
        public static object DeSerializeFromXmlString(System.Type typeToDeserialize, string xmlString) {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString);
            MemoryStream memoryStream = new MemoryStream(bytes);
            System.Xml.Serialization.XmlSerializer xmlSerializer = 
                new System.Xml.Serialization.XmlSerializer(typeToDeserialize);
            return xmlSerializer.Deserialize(memoryStream);
        }
        
        Example
        [Test]
        public void GetBigList() {
            var textRepository = ObjectFactory.GetInstance<ITextRepository>();
            List<BrandAndCode> brandAndCodeList = textRepository.GetList(...);
            string xml = SerializeToXmlString(brandAndCodeList);
            Console.Out.WriteLine("xml = {0}", xml);
             var brandAndCodeList2 = DeSerializeFromXmlString(typeof (BrandAndCode[]), xml);
        }
        
        
          
      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'
        Console.WriteLine( 1234567.ToString("#,##0")); // writes with commas:   1,234,567
        
      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'
    5. Example of Constructors, static Constructor and Destructor:
      using System;
      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");
            }
            
            static void Main(string[] args)
            {
               Console.Out.WriteLine("Test2");
               new Test2();
               new Test2();
            }
         }
      Produces:
      inside static construtor...
      Test2
      inside regular construtor... i=4
      inside regular construtor... i=4
      inside destructor
      inside destructor
    6. Example of Virtual Functions:
      using System;
      namespace Test2 {
         class Plane {
            public double TopSpeed() {
               return 300.0D;
            }
         }
         class Jet : Plane {
            public double TopSpeed() {
               return 900.0D;
            }
         }
         class Airport {
            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
    7. 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();
            }
         }
      
    8. 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();
            }
         }
    9. 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'"
    10. 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();
           }
      }
      
    11. 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;ilt;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();
         }
      }
      }
      Or you can use a static method to download a web page into a string:
      public static string GetWebPageAsString(string url) {
          HttpWebRequest httpWebRequest =(HttpWebRequest)WebRequest.Create(url);
          // you may need these next two lines to prevent a .net bug
          // System.IO.IOException : Unable to read data from the transport connection: The connection was closed.
          // see http://support.microsoft.com/default.aspx?scid=kb;EN-US;915599
          httpWebRequest.KeepAlive = false; 
          httpWebRequest.ProtocolVersion = HttpVersion.Version10; 
                  
          HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
          Stream stream = httpWebResponse.GetResponseStream();
          StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);
          return streamReader.ReadToEnd();
      }
      This is also rumored to work, but not for me.
      string xml;
      using(WebClient client = new WebClient()) {
          xml = client.DownloadString(url);
       }
      
    12. Download response with errorsHow to get the content of the page even with errors like 500 or 404 is shown below:
      public static string GetWebPageAsString(string url)
      {
          HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
          HttpWebResponse httpWebResponse = null;
          string xml = "";
          try
          {
              httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
          }
          catch (WebException exception)
          {
              if (exception.Status == WebExceptionStatus.ProtocolError)
              { //get the response object from the WebException
                  httpWebResponse = exception.Response as HttpWebResponse;
                  if (httpWebResponse == null){ return "<Error />";}
              }
          }
          Stream stream = httpWebResponse.GetResponseStream();
          StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);
          xml = streamReader.ReadToEnd();
          //streamReader.Close();
          if (httpWebResponse.StatusCode != System.Net.HttpStatusCode.OK)
          {
              throw new Exception(xml);
          }
      
          return xml;
      }
    13. Use System.Web.HttpUtility.HtmlEncode() to encode strings for display in the browser. Converts "<" to &lt;, a good first step against hacking on your site.
      this.Response.Write("<br />xml returned: \"" + HttpUtility.HtmlEncode(xml)  + "\"");
    14. Calculate Elapsed Time
      DateTime startTime = DateTime.Now;
       // do stuff
       TimeSpan elapsed = DateTime.Now - startTime;
       Console.WriteLine("response time: {0}",elapsed.TotalSeconds);
      Or you can you the handy Stopwatch class from System.Diagnostics
      using System;
      using System.Threading;
      using System.Diagnostics;
      namespace PlayingAround {
          class MyStopwatch {
              private static void Main() {
                  var stopwatch = Stopwatch.StartNew();
                  Thread.Sleep(50); //do something interesting here...
                  stopwatch.Stop();
                  long elapsedTimeInMilliSeconds = stopwatch.ElapsedMilliseconds;
                  Console.Out.WriteLine("elapsedTimeInMilliSeconds = {0}", elapsedTimeInMilliSeconds);
                  Console.Out.Write("press return to exit."); Console.In.ReadLine();
              }
          }
      }
      What's the units for the argument to Sleep? You can make it more implicit by using TimeSpan.From* format:
      Thread.Sleep(TimeSpan.FromMilliseconds(50));
    15. How to convert a string to an integer, a string to a double, a string 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();
      }
      }
    16. How to convert a double to an integerSystem.Convert contains many nifty little conversion routines.
      Convert.ToInt32(mydouble);
    17. Tiny Browser
      Source Code.
    18. 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);
          }
      }
      
    19. Xml and Xslt
      1. 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)
            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());
            }
        }
        
        
      2. 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)
            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());
            }
        }
      3. Another example reading xml and xslt info from two files and transforming with the more modern XslCompiledTransform
        [Test]
        public void Transform() {
            const string xmlFileNameWithPath = @"C:\workfiles\SwitchBoard\SwitchBoardHandler\Tests\Incidence1.xml";
            const string xslFileNameWithPath = @"C:\workfiles\SwitchBoard\SwitchBoardHandler\xslt\Incidence.xslt";
            XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
            xslCompiledTransform.Load(xslFileNameWithPath);
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter stringWriter = new StringWriter(stringBuilder);
            xslCompiledTransform.Transform(xmlFileNameWithPath, null, stringWriter);
            stringWriter.Close();
            Console.Out.WriteLine("sb.ToString() = {0}", stringBuilder.ToString());
        }
      4. Transforming an xml string with an xslt file
        [Test]
        public void Transform() {
            const string xmlFileNameWithPath = @"C:\workfiles\SwitchBoard\SwitchBoardHandler\Tests\Incidence1.xml";
            const string xslFileNameWithPath = @"C:\workfiles\SwitchBoard\SwitchBoardHandler\xslt\Incidence.xslt";
            string xmlString = GetFileAsString(xmlFileNameWithPath);
            XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xmlString));
            XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
            xslCompiledTransform.Load(xslFileNameWithPath);
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter stringWriter = new StringWriter(stringBuilder);
            xslCompiledTransform.Transform(xmlTextReader, null, stringWriter);
            stringWriter.Close();
            Console.Out.WriteLine("sb.ToString() = {0}", stringBuilder.ToString());
        }
      5. How to transform an xml string with an xsl string
        // <summary>
        /// transforms an xml string with an xsl string
        /// </summary>
        /// <param name="xmlString">xml to transform</param>
        /// <param name="XSLStylesheet">stylesheet</param>
        /// <returns>xml transformed</returns>
        public static string TransformXmlStringWithXslString(string xmlString, string XSLStylesheet)
        {
            //process our xml
            XmlTextReader xmlTextReader =
                new XmlTextReader(new StringReader(xmlString));
            XPathDocument xPathDocument = new XPathDocument(xmlTextReader);
        
            //process the xsl
            XmlTextReader xmlTextReaderXslt = new XmlTextReader(new StringReader(XSLStylesheet));
            XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
            xslCompiledTransform.Load(xmlTextReaderXslt);
        
            //handle the output stream
            StringBuilder stringBuilder = new StringBuilder();
            TextWriter textWriter = new StringWriter(stringBuilder);
            
            //do the transform
            xslCompiledTransform.Transform(xPathDocument, null, textWriter);
            return stringBuilder.ToString();
        }
        ...
        [Test]
        public void TransformXmlStringWithXsltString() {
            KoEndPoint koEndPoint = new KoEndPoint("test",null);
            string result = koEndPoint.TransformXmlStringWithXslString("<person name='Francis Bacon' />", "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:template match='/'>Person:<xsl:apply-templates select='*' /></xsl:template><xsl:template match='/person'><xsl:value-of select='@name' /></xsl:template></xsl:stylesheet>");
            Console.Out.WriteLine("result = " + result);
            result.ShouldEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>Person:Francis Bacon");
        }
        
      6. 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);
            }
        }
      7. Convert XML to an HTML tableC# has another set of libraries
        using System.Linq;
        using System.Text;
        using System.Xml.Linq;
        
        namespace SwitchBoard.Views.Handler {
            public class HandlerView {
                /// <summary>
                /// takes in well structured xml from something like 
                /// SELECT * FROM mytable AS XML AUTO
                /// where all the elements have identical attribues
                /// and creates an HTML table
                /// </summary>
                /// <param name="xml">collection of xml elements all with the same attributes</param>
                /// <returns>HTML table with class of 'xmlTable'</returns>
                public string ConvertXmlToHtmlTable(string xml) {
                    XDocument xDocument = XDocument.Parse("<outer>" + xml + "</outer>");
                    XElement root = xDocument.Root;
                    if(root == null || root.Elements().Count() == 0) return "Empty";
                    var xmlAttributeCollection = root.Elements().First().Attributes();
                    StringBuilder html = new StringBuilder("<table class='xmlTable'>\r\n<tr>");
                    foreach (var attribute in xmlAttributeCollection)
                    {
                        html.Append("<th>"+attribute.Name+"</th>");
                    }
                    html.Append("</tr>");
                    foreach (XElement element in root.Descendants())
                    {
                        html.Append("\r\n<tr>");
                        foreach (XAttribute attrib in element.Attributes()) {
                            html.Append("<td>"+attrib.Value+"</td>");
                        }
                        html.Append("</tr>");
                    }
                    html.Append("</table>");
                    return html.ToString();
                }
            }
        }
    20. To get a value from a form page
      private void Page_Load(object sender, System.EventArgs e) {
         string survey = Request.Params.Get("survey"));
         ...
      }
    21. 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();
               }
            }
          }
      }
    22. 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 + "\" ");
          }
       }
    23. 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();
      }
    24. 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
    25. 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;
       }
    26. 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);
            }
          }
      
    27. 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();
            }
    28. Returning an attribute from an XmlDocument
      string total = xmlDocument.SelectSingleNode("Surveys/Survey[@name='Beer']/cellName[@name='MatureBlueCollarMen']").Attributes.GetNamedItem("total").Value; 
      
    29. 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);
    30. Tokenize stringcode to tokenize string into ArrayList
      string[] tokens = surveyName.Split(new char[] {':'});
         foreach (string item in tokens) {
            arrayList.Add(item);
         }
    31. 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();
          }
      }
    32. Adding elements to an ArrayList with AddRangeInstead 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
    33. ArraysArrays 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};
    34. 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");
        }
      
    35. Working with our friend the database
      1. Accessing a databaseLet's return a single string from a database
        static public string GetSqlAsString(string sqlText,
                               SqlParameter[] sqlParameters,
                               string databaseConnectionString) {
            string result = "";
            SqlDataReader reader;
            SqlConnection connection = new SqlConnection(databaseConnectionString);
            using (connection) {
                SqlCommand sqlcommand = connection.CreateCommand();
                sqlcommand.CommandText = sqlText;
                if (sqlParameters != null) {
                    sqlcommand.Parameters.AddRange(sqlParameters);
                }
                connection.Open();
                reader = sqlcommand.ExecuteReader();
                if (reader != null)
                    if (reader.Read()) {
                        result = reader.GetString(0);
                    }
            }
            return result;
        }
        
      2. Timeout expired exceptionIf you get the following exception:
        System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) Your command may really taking too long in the database and has been killed. You can increase the default time of 30 seconds by using the "CommandTimeout" field on the "Command" object as shown below:
        using (connection) {
            SqlCommand sqlcommand = connection.CreateCommand();
            sqlcommand.CommandTimeout = 60; //default is 30 seconds
            sqlcommand.CommandText = sqlText;
            ... 
        Don't be misled by the database connection string option, "Connection Timeout", e.g., "Data Source=myMachine; Integrated Security=SSPI; database=Northwind;Connection Timeout=60". That timeout is for getting the connection, not for how long it queries the database.
      3. Register a delegateExample of adding an InforMessage handler to a connection object.
        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;
              }
        
        
      4. ExecuteScalarExample of a utility function that uses ExecuteScalar, and a utility function to free resources (which is now obsolete - you should use the "using" construct).
        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
        
              }
      5. Example of Parameterized SQLTo 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 {
        /// <summary>
        /// example of using parameterized sql to avoid SQL injection attacks
        
        /// </summary>
           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.
      6. 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"); 
        
    36. Array sorting
    37. Example of using "using" to avoid the finally block messa "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();
          }
      }
      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);
    38. Using XPathThe 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)");
    39. using blockC# 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.
    40. 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;
          }
      
      
    41. Use Reflection to print all the fields and their values in an object, kinda like "inspect" in Ruby.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();
        }
    42. Call a parent's constructorTo call the parent's constructor:
      public Group(string xmlstring) : base (xmlstring) {
            
      }
    43. 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);
    44. 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;
            }
         }
    45. 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);
      ...
            }
       
    46. Sort an ArrayList of non-trivial objectsThe 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
    47. Example of using InterfacesAs 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());
          }
      }
      
    48. Randomize C# ArrayListUtility 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);
          }
       }
    49. Print out objects in Assmebly
      Assembly assembly = Assembly.GetAssembly(this.GetType());
               Type[] types = assembly.GetTypes();
               foreach(Type type in types) {
                  write("type="+type);
               }
    50. 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());
      ...
    51. 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[]{});
    52. Using attributes on classesExample 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
             ....
    53. 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();
                  }
               }
            }
      
      
    54. Defining a web serviceDefining 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) {
      ...
      }
    55. Web ServicesTo create a WSDL file for a service, just append "?wsdl" to the service name inside IE
      http://localhost/MyProject/Service1.asmx?wsdl
    56. Wrapper class for a WSDLUse the Wsdl.exe to read the WSDL document and create a wrapper class
      c:> Wsdl.exe "http://localhost/MyProject/Service1.asmx?wsdl"
    57. 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)  {
      ...
      }
      
    58. 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);
      }
    59. Looking at an AssemblyCode 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+"()");
            }
           }
          }
    60. 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).
    61. 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();
      }
    62. Testing for the throwing of an exceptionIf 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();
      }
      In later versions of NUnit you can use this syntax which is better
      Assert.Throws<Exception>(() => new MyObject(badargument));
    63. Static ConstructorsThis 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"));
       }
      }
    64. 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.
    65. Printing the name of the currently executing methodThe following will print "Void ExistInDatabase()"
      public void ExistInDatabase() {
      System.Console.Write(System.Reflection.MethodInfo.GetCurrentMethod().ToString());
      }
    66. 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);
       }
      }
      }
    67. 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+"\"");
      }
      ...
    68. Environment.StackTraceThis 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();
      }
    69. 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";
       }
      }
    70. Interface definition for PropertiesProperties may appear in an interace as the following example demonstrates:
      /// <summary>
      /// the inventory count for this item
      /// </summary>
      
      int inventory { get; set; }
    71. 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});
    72. Dynamically invoking Instance Methods 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);
      }   
      ...
    73. Case-Insensitive HashtableThese are very handy when case doesn't matter.
      Hashtable hashTable = System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
    74. 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;
      }
              
    75. How to get the directory of an executing web app
      string baseDir = AppDomain.CurrentDomain.BaseDirectory.Replace("bin", "");
    76. 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))
    77. How to do case-insensitive substrings searchs
      0 <= mystring.IndexOf(mysubstring, StringComparison.InvariantCultureIgnoreCase)
    78. Using indexersYou 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;
       }
      }
    79. IEnumerable InterfaceThe 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();
          }
      }
    80. 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" />
    81. Show all the methods on an object
      using System.Reflection;
      ...
      MyObject myObject;
      foreach(MethodInfo meth in myObject.GetType().GetMethods()) {
       Console.WriteLine(meth.ToString());
      }
    82. 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> 
    83. DelegatesDelegates 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
          }
      }
    84. 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);
      }
      
      }
      
    85. 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);
      }
      
      }
      
    86. 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;
      }
        
    87. "checked" keywordOddly 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
      
    88. 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());
          }
      }
      
    89. 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
    90. How to pass a variable number of arguments to a fileUse 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();
          }
      }
    91. How to loop through a list of files in a directoryThis 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"
      A caveat: DirectoryInfo.GetFiles will sometimes return more than you want. It will also return files whose extension has extra characters. Looking for "*.xml" will also yield "*.xmlabc" which can be, at the least, annoying.
      foreach (var fileInfo in dirInfo.GetFiles("*.xml"))
      {
          if(fileInfo.Extension != ".xml") continue; //gets rid of "SDUS.xml~"
          using (var reader = new XmlTextReader(fileInfo.FullName))
          ...
      }
    92. How to walk up a directory tree looking for a fileFor example, you may want to find a "config" directory which is a few levels above your executing directory. Use something like "Assmebly.GetAssembly" to find a startingDirectory and "\\Config\\settings.xml" for a target file.
      private static string WalkDirTreeUpwardsAndSearchForFile(string startingDirectory, string targetFilename) {
                  string path = startingDirectory;
                  string fullFilename = path + targetFilename;
                  while (!File.Exists(fullFilename) && path != null) {
                      path = Path.GetDirectoryName(path);//walk up a directory
                      fullFilename = path + targetFilename;
                  }
                  if (!File.Exists(fullFilename)) {
                      throw new Exception(string.Format("Could not find file '{0}' starting in directory '{1}'", targetFilename, startingDirectory));
                  }
                  return fullFilename;
              }
    93. How to convert a relative path to an absolute path
      string directoryName = Path.GetFullPath(@"..\..\..\..\..\Data\xsd\Surveys.xsd");
      Console.Out.WriteLine("directoryName = {0}", directoryName); //C:\workfiles\SurveyDirector\src\Data\xsd\Surveys.xsd
    94. 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 {}
         }
      }
    95. How to execute a background process repeatedlyUsing 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
          }
      }
    96. Example of Serialization using the Xml FormatterThe 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>
    97. How to inject your company name etc. into the assemblyBy 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")]
    98. 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) 
      ...
    99. Null Coalescing Operator, aka the double question mark operatorThe 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
    100. ASP.NET Example code
      1. 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>
      2. How to create a cookie in asp.net
        <%
            HttpCookie aCookie = new HttpCookie("MyCookieName");
            aCookie.Value = "MyCookieValue";
            aCookie.Expires = DateTime.Now.AddDays(100);
            Response.Cookies.Add(aCookie);
        %>                                                             
      3. Get the IP address of the browser On the aspx page:
        protected void Page_Load(object sender, EventArgs e) {
               string ip = Request.UserHostAddress;
               ...
      4. Show a result set in a broswer window. On the aspx page:
        <asp:GridView ID="GridViewResults" runat="server" />
        In the code behind:
        DataSet ds = databaseProxy.GetSqlAsDataSet("SELECT * FROM candidate_data ORDER BY dtime DESC","Poll");
        GridViewResults.DataSource = ds;
        GridViewResults.DataBind();
      5. 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;
      6. To catch all the unhandled exceptions in a PageThis 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);
        }
          
      7. To store data in a respondent's session
        Session["favAnimal"] = "zebra";
        //and retrieve it later...
        string animal = (string) Session["favAnimal"];
      8. How an application can be notified of changes to a fileYou 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);
          }
         }
        }
        
      9. 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+"\"");
         }
              
      10. 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;
        }
        
      11. 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>
      12. 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> 
      13. 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();
        }
        
      14. Quick 'web service' call without the overheadIf 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; 
        
      15. 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()");
          }
        }
      16. 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;
         }
        }
      17. Setting a Cookie
        HttpCookie myCookie = new HttpCookie("myName");
        myCookie.Value = groupDropDown.SelectedItem.Text;
        myCookie.Expires = DateTime.Now.AddMonths(6);
        Response.Cookies.Add(myCookie);
      18. Getting a Cookie
        if (Request.Cookies["myName"] != null)
        {
         itemSelected = Request.Cookies["myName"].Value;
        }
        
        
      19. Using standalone C# in an aspx page When a respondent is forwarded to this page, they are redirected to another page based on the value of "x" All their GET parameters are passed on as well. If x=ABCDE, then they are forwarded to ABCDE.html
        <%@ Page Language="C#" %>
        <script runat="server">
            protected void Page_Load(object sender, EventArgs e) {
                string source = Page.Request.QueryString["x"];
                if (string.IsNullOrEmpty(source)) {
                    source = "XYZ"; //this is the default source if nothing is passed in as "x" param
                }
                Page.Response.Redirect(source + ".html?" + Page.Request.QueryString);
            }
        </script>
        <html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server">
            <title>Redirect Page</title>
        </head>
        <body>
        </body>
        </html>
  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. Which data type should we use for money?The "decimal" struct gives 28 significant digits and may be used for most currency applications. Use the "m" suffix for constants.
      const decimal interestRate = 0.02m;
      decimal interestEarned = customer.Amount*interestRate/365.25m;
    3. 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.
    4. 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".
    5. 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> 
      
    6. Use stringBuilder.AppendFormat() instead of .Append() when doing multiple Appends.
      StringBuilder sb = new StringBuilder();
      const string first = "Odysseus";
      const string second = "Hector";
      //instead of this
      sb.Append(first).Append(" said, '").Append(second).Append(", it was his cousin.'");
      Console.Out.WriteLine(sb.ToString());
      sb = new StringBuilder();
      //use AppendFormat()
      sb.AppendFormat("{0} said, '{1}, it was his cousin.'",first,second);
      Console.Out.WriteLine(sb.ToString());
      Produces:
      Odysseus said, 'Hector, it was his cousin.'
      Odysseus said, 'Hector, it was his cousin.'
    7. The Main method can take 3 forms: "static void Main()","static int Main()",or "static int Main(string[] args)"
    8. Typical output: "System.Console.WriteLine("Howdy World!");"
    9. In VS.NET, to get the docs on an object, highlight it and press 'F1'
    10. To launch the Object Browser: View/Other Windows/Object Browser or Ctl-Alt-J
    11. To add namespaces to the object browser, in the Solution Explorer, right click on the "References" tag and select "Add..."
    12. Using an "@" in front of a string turns off escape substitutions, e.g.,, @"C:\" == "C:\\"
    13. 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 };
    14. 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));
      
    15. The 'checked' and 'unchecked' operators are used to turn on and off arithmetic exceptions, e.g.,, int x = unchecked(a * b);
    16. 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.
    17. StructStructures are similar to classes but do not have inheritance and, although created with the 'new' operator, they live on the stack.
    18. "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.
    19. "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.
    20. "is" keywordtests to determine if an object is of a particular type
      if(myShape is Circle) {
      ...
      }
    21. "as" keywordsimilar to a type cast, but if the object is not what is expected, "as" returns a null while a type cast throws an exception.
      Circle c = myShape as Circle;
      if(c != null) {
      ...
      }
    22. "base" is similiar, but not identical to, Java's "super" to access a parent's members.
    23. To read a double from a string: Console.Out.WriteLine("d = {0}",Double.Parse("1.02"));
    24. Use "sealed" as a method modify so no subclass can extend the class ( like java's "final")
    25. 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"; }
    26. 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
    27. 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 TypesIn 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 surpress warning with MSBuildWith csc.exe it's easy to surpress warning with the "nowarn" option. With MSBuild it's a little trickier. Use the "property" switch and encluse your warning numbers with "&quot;", which is a little awkward.
    <target name="compile">
        <exec program="MSBuild.exe" basedir="${framework::get-framework-directory(framework::get-target-framework())}" workingdir="${project::get-base-directory()}" commandline="MyProject.sln /verbosity:diag /p:Configuration=${string::to-upper(project.config)} /t:Clean;Rebuild /property:nowarn=&quot;1591,0618&quot;" output="MyProjectMSBuild.txt" />
      </target>
  6. 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();
    }
    
  7. 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;
     }
    
  8. Create your own generic class By adding "lt;T>" after the class you can create a Templated, or generic, version of your object, in this case a wrapper for cached items. We don't have to create a CachedItemString and a CachedItemInt.
    using System;
    
    namespace PlayingAround {
        class Cacher<T> {
                    public T CachedItem;
                    public DateTime ExpirationDate;
        }
        class Runner {
            private static void Main() {
                Cacher<string> myString = new Cacher<string>();
                myString.CachedItem = "old string";
                Console.Out.WriteLine("myString.CachedItem = {0}", myString.CachedItem);
                Cacher<int> myInt = new Cacher<int>();
                myInt.CachedItem = 6;
                Console.Out.WriteLine("myInt = {0}", myInt.CachedItem);
                Console.Out.Write("press return to exit."); Console.In.ReadLine();
            }
        }
    }
  9. 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()
  10. Examples of using Regular Expressions
    1. 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;
      }
      
    2. 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;
      }
    3. Replace all characters that are not letters or numbers with "_".
      using System.Text.RegularExpressions;
      ...
      string filename = "file(1)";
      //find all characters that are not letters or numbers
      Regex regex = new Regex("[^a-zA-Z0-9]");
      filename = regex.Replace(filename, "_");
    4. 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(""));
      }
    5. Select a stringThis lifts the database name from a connection string.
      string result="No Database found.";
      Regex pattern = new Regex(@"Database=(?<databaseName>\w+)", RegexOptions.IgnoreCase);
      Match match = pattern.Match("Server=.; Integrated Security=SSPI; Database=T800; Application Name=Cyberdyne");
      if (match.Success) {
          result = match.Groups["databaseName"].Value;
      }
    6. Visual Studio Regular Expression Editing tipsVS 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=
        
  11. 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());
  12. 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.#@@!@##
  13. 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 {
  14. 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' >
    
  15. DelegatesDelegates are type-safe function pointers. In the old C# 1.0 days a delegate method had to have it's own declaration as a method like this:
    // 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();
    }
    
  16. Anonymous methods (C# 2.0)You can do the same as above with a cleaner look by using anonymous methods. We don't have to declare a real method, we can just inline it:
    // 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();
    }
    
  17. 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
  18. 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 4  Next >

No comments:

Post a Comment