November 23, 2005
Using C# Xml Documentation
Heres some links:
MSDN Article on Using Xml Within C#
Xml Documentation Tutorial
Recommended Tags for Documentation Comments
November 21, 2005
Modifying Config File for a Log4Net TraceAppender
Modifying an App.Config file for Log4Net
Adding a TraceAppender:
<appender name="TraceAppender" type="log4net.Appender.TraceAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date{HH:mm:ss,fff}[%thread] %-5level %logger{2}: %message%newline%exception" /> </layout> </appender>Setting a module to use the log to the TraceAppender and the ConsoleAppender
<logger name="mymodule.comms"> <level value="ALL" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="TraceAppender" /> </logger>
Helper Class To Converts Strings To Ascii and Back
using System.Text; ... // Helper methods for converting strings to ascii and back public class Ascii { // Converts a standard c# unicode string to an array of ASCII characters public static byte[] FromString(string str) { Encoding ascii = Encoding.ASCII; byte[] asciiBytes = ascii.GetBytes(str); return asciiBytes; } // Converts an array of ASCII characters to a standard c# unicode string public static string ToString(byte[] asciiString) { // Create two different encodings. Encoding ascii = Encoding.ASCII; string str = ascii.GetString(asciiString); return str; } }
Using Streams To Serialize Something to A Byte Array
Writing To A Stream Using A BinaryWriter
byte[] data; MemoryStream stream = new MemoryStream(); BitWriter writer = new BitWriter(stream, System.Text.Encoding.ASCII); writer.UseNetworkByteOrder = true; bat.Serialize(writer); stream.Flush(); stream.Close(); data = stream.ToArray(); return data;
TCP/IP Socket Programming in C#
Here is some links I discovered during my research:
- Using Sockets in C#
- Portscanning in C# Using Sockets
- Good intro to TcpClient and TcpListener
- MSDN C++ to c# article - Has some basic Tcp and use of Socket type code
- MSDN article on sockets
- Handling Socket Exceptions
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:
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; } } #endregionas 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) && (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) && (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() ; } }
Subscribe to:
Posts (Atom)