October 11, 2005

Singleton Implementation in c#

At http://csharpindepth.com/Articles/General/Singleton.aspx can be found a full description of the different c# singletons and their advantages and disadvantages
Here is the fast thread safe one:
#region Fast Thread Safe Singleton Implementation

static $ClassName$()
{}

private $ClassName$()
{}

private static readonly $ClassName$ instance= new $ClassName$();

public static $ClassName$ Instance
{
  get { return instance; }
}

#endregion
as a snippet:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Keywords>
        <Keyword>SimpleSingleton</Keyword>
      </Keywords>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>SimpleSingleton</Title>
      <Author>R Bovill</Author>
      <Description>Make a threadsafe singleton class</Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>SimpleSingleton</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="false">
          <ID>ClassName</ID>
          <ToolTip>
          </ToolTip>
          <Default>
          </Default>
          <Function>ClassName()</Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[
        #region Fast Thread Safe Singleton Implementation
        
        static $ClassName$()
        {}

        private $ClassName$()
        {}

        private static readonly $ClassName$ instance = new $ClassName$();

        public static $ClassName$ Instance
        {
            get
            {
                return instance;
            }
        }

        #endregion Fast Thread Safe Singleton Implementation
        ]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
Full lazy implementation as a snippet:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Keywords>
        <Keyword>Full Lazy Singleton</Keyword>
      </Keywords>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>FullLazySingleton</Title>
      <Author>Microsoft</Author>
      <Description>Make a threadsafe singleton class</Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>FullLazySingleton</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="false">
          <ID>ClassName</ID>
          <ToolTip>
          </ToolTip>
          <Default>
          </Default>
          <Function>ClassName()</Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[
    #region Thread Safe Lazy Singleton Implementation
    
    private $ClassName$()
    {
    }

    public static $ClassName$ Instance
    {
        get
        {
            return Nested.instance;
        }
    }
    
    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly $ClassName$ instance = new $ClassName$();
    }


    #endregion Thread Safe Lazy Singleton Implementation
]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

October 5, 2005

Pattern/Sample To Parse Xml Using XmlReader

Heres some sample text that shows how to parse some Xml with XmlTextReader I am trying to demonstrate parsing of attributes, empty nodes and layered nodes all in one go that’s why its quite complex

   #region ReadIBVDescriptor Method

  private const string ELEMENT_NAME = "IBVDescriptor";

  // Parse some xml fragment 
  // <IBVDescriptor>...</IBVDescriptor>
  // On exit the XmlReader is pointing to the 
  // node immediately following
  // the end element node ('</IBVDescriptor>')
  public static IBVDescriptor ReadIBVDescriptor(
    XmlReader xmlReader)
  {
    // Move to the next start element
    // ('<IBVDescriptor>') if not already there
    MoveTo(xmlReader, XmlNodeType.Element);
    _Assert((xmlReader.Name == IBVDescriptor_ELEMENT_NAME)
      &&amp; (xmlReader.NodeType == XmlNodeType.Element));
    int startDepth = xmlReader.Depth;
    bool elementIsEmpty = xmlReader.IsEmptyElement;
    // PARSE ATTRIBUTES of the descriptor root node
    string name = xmlReader.GetAttribute("Name");
    string provider = xmlReader.GetAttribute("Provider");
    string tmp = xmlReader.GetAttribute("RunningStatus");
    // To parse an attribute directly into an 'enum' value
    // use the following code pattern
    Service.RunningStatuses runningStatus =
      (Service.RunningStatuses)Enum.Parse(
      typeof(Service.RunningStatuses), tmp);
    byte type = byte.Parse(xmlReader.GetAttribute("Type"));
  
    IBVDescriptor descriptor = new IBVDescriptor(
      name, provider, runningStatus, type);
     if (!elementIsEmpty)
    {
      xmlReader.Read();
       bool endOfDesc = false;
      DataService ds = null;
      string val;
      while (true)
      {
        // look for the end of the main parent element node
        endOfDesc = (xmlReader.Name == ELEMENT_NAME) &&
          (xmlReader.NodeType == XmlNodeType.EndElement);
        if (endOfDesc)
          break;

        // PARSE ELEMENT NODES
        // Begin Element Processing ''
        if (xmlReader.NodeType == XmlNodeType.Element)
        {
          // Do something with the node
          switch (xmlReader.Name)
          {
            case "DataService":
              _Assert(ReferenceEquals(ds, null));
              string id = xmlReader.
                GetAttribute("DataServiceId");
              ds = new DataService(id);
              xmlReader.Read();
              break;

            case "Reserved":
              // Interpret an element node. In this
              // case we assume it cannot be empty
              _Assert(!xmlReader.IsEmptyElement);
              val = xmlReader.ReadElementString();
              ds.Reserved = val;
              break;
            case "FieldParity":
              // Can read in an entire Xml
              // fragment as a string if required
              val = xmlReader.ReadOuterXml();
              descriptor.FieldParity = val;
              break;
            case "Authorisation":
              // Can devolve complex xml fragments to
other routines
              Authorisation val =
XmlHelper.ReadAuthorisation(xmlReader);
                descriptor.Authorisation = val;
                break;
            default: // Whitespace etc.
              //TODO_NODE(xmlReader);
              // Can use Skip() to ignore unhandled XML
              XmlHelper.Skip(xmlReader);
                break ;
          }
        }
        else
        {
          // End Element Processing '</xxx>'
          if (xmlReader.NodeType == XmlNodeType.EndElement)
          {
            if (xmlReader.Name == "DataService")
            {
              _Assert(!ReferenceEquals(ds, null));
              descriptor.AddDataService(ds);
              ds = null;
            }
          }
          xmlReader.Read();
        }
      }
  
      // Use xmlReader.Depth to ensure we are still
      _Assert(xmlReader.Depth == startDepth);
      _Assert((xmlReader.Name == IELEMENT_NAME) &&amp;
        (xmlReader.NodeType == XmlNodeType.EndElement));
      xmlReader.Read();
    }
    return descriptor;
  }

  #endregion ReadIBVDescriptor Method

  // Helper method to skip the next node.
  // 'XmlTextReader.Skip()' does not handle
  // empty element nodes, ie.
  // those of format '<xxx />'
  public static void Skip(XmlReader xmlReader)
  {
    if (xmlReader.IsEmptyElement)
      xmlReader.Read();
    else
      xmlReader.Skip();    
  }

  public static void MoveTo(
          XmlReader xmlReader, XmlNodeType nodeType)
  {
     while (!xmlReader.EOF && 
            (xmlReader.NodeType != nodeType) )
     {
        xmlReader.Read() ;
     }
  }

Using XmlTextReader With a String

Pattern for Using XmlTextReader with a string. This is useful for testing your Xml Parsing

//Create the XML fragment to be parsed.
string xmlFrag =
  "<Transport Label=\"TS1\" TransportId=\"1\" 
OrigNetworkId=\"1\" >" + " <Metadata>" + " <Id>c98dced0-1efc-48c3-aa37-cae5141c6615</Id>" + " <ProfileDescription>Test TS</ProfileDescription>" + " </Metadata>" + "</Transport>"; // Create a XmlTextReader that will read from an Xml string XmlTextReader xmlReader = new XmlTextReader( xmlFrag, XmlNodeType.Element, new XmlParserContext(null, new XmlNamespaceManager(
new NameTable()), null, XmlSpace.Default)); // <= XXX // Can set how to handle whitespace here! //xmlReader.WhitespaceHandling = WhitespaceHandling.All; Transport transport = XmlProcessor.ReadTransport(xmlReader) ; //Close the reader. xmlReader.Close();

A longer version for the creating the XmlTextReader. Replace the line XXX with this

//Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(
null, nsmgr, null, XmlSpace.Default); //Create the reader, tell it the fragment represents
an Xml Element type of node XmlTextReader xmlReader = new XmlTextReader(
xmlFrag, XmlNodeType.Element, context);