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:

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);

August 30, 2005

c# Array Append Pattern

Pattern to append one array to the end of another in c#
public static class ArrayAppender
{
  public static TYPE[] Append(this TYPE[] b1, TYPE[] b2)
  {
    TYPE[] newArray = new TYPE[b1.Length + b2.Length];
    Array.Copy(b1, 0, newArray, 0, b1.Length);
    Array.Copy(b2, 0, newArray, b1.Length, b2.Length);
    return newArray;
  }
}

internal class ArrayAppendTester
{
  public void Test()
  {
    int[] intArray1 = new int[4] { 42, 7, 6, 3 };
    int[] intArray2 = new int[7] { 1, 2, 3, 4, 5, 6, 7};

    int[] newArray = ArrayAppender.Append(intArray1, intArray2);
    int[] newArray2 = intArray1.Append(intArray2);
  }
}

Format of an c# Indexer

Indexer format:

class XXX 
{
// RETURN_TYPE is type that is returned by the indexer
// INDEX_TYPE is the indexer look up type
public RETURN_TYPE this[INDEX_TYPE index] 
{
  get{return ...;}
  set{... = value;}
}
Note that their can be multiple indexers
public RETURN_TYPE this[INDEX_TYPE_1 index1, ..., INDEX_TYPE_N indexN] 
{
  get{ ... }
  set{ ... }
}

Equals Operator Pattern

Equality in C#

Pattern for implementing required operators to support '==', '!=', 'Equals()' and 'GetHashCode()' for a new reference or value type. Need to implement these methods together.

For REFERENCE types
public override bool Equals(object rhs)
{
    if (rhs == null) // this cannot be null
        return false;

    if (object.ReferenceEquals(this, rhs)
        return true;

    // Check for null values and compare run-time types.
    if (this.GetType() != rhs.GetType())
         return false;

    return CompareFields(rhs as XXX);
}

private bool CompareFields(XXX p)
{ // Field by field comparison
  return (this.field1 == this.field2) && ...; 
}


public override int GetHashCode()
{   // Aim to get a unique number from the objects state 
    int tmp = ((int)(field1 << 16) + field2) ... ;
    return tmp;
}

In general it is not recommended to override the '==' and '!=' operators for reference types. They should only be overriden for immutable types. However here is a suitable implementation:
public static bool operator ==(XXX obj1, XXX obj2)
{
// IF obj1 is null
//  so obj2 must be for equality
// ELSE obj1 is not null,  
//  compare it with obj2 using above Equals() operator
    if (ReferenceEquals(obj1, null))        
        return ReferenceEquals(obj2, null); 
    else                                    
        return obj1.Equals(obj2);           
}

public static bool operator !=(XXX obj1, XXX obj2)
{
    return !(obj1 == obj2);
}
For VALUE types
public override bool Equals(object rhs)
{
    if (rhs == null) // this cannot be null
        return false;

    return Equals(rhs as XXX);
}

public override bool Equals(XXX rhs)
{
    return CompareFields(rhs);
}


private bool CompareFields(XXX p)
{ // Field by field comparison
  return (this.field1 == this.field2) && ...; 
}

public override int GetHashCode()
{   // Aim to get a unique number from the objects state 
    int tmp = ((int)(field1 << 16) + field2) ... ;

    return tmp;
}

// For VALUE types
public static bool operator ==(XXX lhs, XXX rhs)
{
    bool res = lhs.Equals(rhs);
    return res;
}

public static bool operator !=(XXX lhs, XXX rhs)
{ 
    return !(lhs==rhs); 
}

Here is a Unit Test To Test the Equals operator Create 'x', 'y' and 'z' that are the same and an object 'a' that is not

TestEqualsOperator()
{
  // Ensure all the XXX objects have the same constructor 
  // except the one called 'different'
  XXX a = new XXX(...);
  XXX x = new XXX(...);
  XXX y = new XXX(...);
  XXX z = new XXX(...);
  XXX different = new XXX(...); 

  Debug.Assert(x.Equals(x) == true);
  Debug.Assert(x.Equals(y) == y.Equals(x));
  Debug.Assert((x.Equals(y) && y.Equals(z)) && x.Equals(z));
  Debug.Assert(x.Equals(null) == false);

  Debug.Assert(a.Equals(different) == false);
  Debug.Assert(different.Equals(a) == false);
  Debug.Assert(x.Equals(different) == false);
  Debug.Assert(different.Equals(x) == false);
  Debug.Assert(y.Equals(different) == false);
  Debug.Assert(different.Equals(y) == false);
  Debug.Assert(z.Equals(different) == false);
  Debug.Assert(different.Equals(z) == false);

}

August 18, 2005

My Testing Of DateTime Parsing Capabilities

  
  public static void TestDateTime()
  {
    TestDateParsing(DateTime.Today.ToString());
    TestDateParsing("16/08/2005");
    TestDateParsing("01-08-2005");
    TestDateParsing("25 December 2005");
    TestDateParsing("");
    TestDateParsing("YES");
    /*
Test with: '18/08/2005 00:00:00'
  '18/08/2005'
  Difference in days from today: 0
Test with: '16/08/2005'
  '16/08/2005'
  Difference in days from today: 2
  Date is WITHIN the last '21' days
Test with: '01-08-2005'
  '01/08/2005'
  Difference in days from today: 17
  Date is WITHIN the last '21' days
Test with: '25 December 2005'
  '25/12/2005'
  Difference in days from today: -128
Test with: ''
  Exception caught: 'String was not recognized as a valid DateTime.'
setting dat e to Minimum Value '01/01/0001' Difference in days from today: 732175 Test with: 'YES' Exception caught: 'The string was not recognized as a valid
DateTime. There i s a unknown word starting at index 0.' setting date to Minimum
Value '01/01/0001' Difference in days from today: 732175 */ } public static void TestDateParsing(string str) { DateTime date; try { WL(string.Concat("Test with: \'", str, "\'")); date = DateTime.Parse(str); } catch (Exception ex) { WL(string.Concat(" Exception caught: \'",ex.Message, "\'
setting date to Minimum Value")); date = DateTime.MinValue; } WL(string.Concat(" \'", date.ToString("dd/MM/yyyy"), "\'")); TimeSpan time = DateTime.Now.Subtract(date); WL(string.Concat(" Difference in days from today: ",time.Days)); const int DAYLIMIT = 21; if ((time.Days <= DAYLIMIT) && (time.Days > 0)) { WL(string.Concat(" Date is WITHIN the last \'", DAYLIMIT,
"\' days")); } }
To parse the string "Mon, 08 Apr 2013 09:56:56 +0100" had to use the parse format "ddd, dd MMM yyyy HH':'mm':'ss K"
Like so:
string form = @"ddd, dd MMM yyyy HH':'mm':'ss K";
DateTime.TryParseExact(pubDateNode.Value, form, 
  System.Globalization.CultureInfo.CurrentCulture,
  System.Globalization.DateTimeStyles.AssumeLocal, 
  out when);

July 15, 2005

Generic Dispose

Use this generic class to dispose of any reference object, whether it is IDisposable or not. I havent tried this class yet so I do not know if it will work. It is using c# Generics. I am assuming a C# generic class can have a static method.
public class Disposer<T>
{
  static public void DisposeOf(ref T obj)
  {
    if (!ReferenceEquals(obj, null))
    {
      if (obj is IDisposable)
        ((IDisposable)obj).Dispose();
      obj = null;
    }
  }
}
...
// To use
Disposer<MyClass>.DisposeOf(ref myObject);

.Net Deep Copy or Cloning Using Serialization

Heres some code I developed to make a deep copy of an object using serialisation.
public class Cloner
{
      
  static public object _GenericDeepCopy(object target)
  {
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    // Serialize the object into the stream.
    bf.Serialize(ms, target);
    //Position streem pointer back to first byte.
    ms.Seek(0, SeekOrigin.Begin);
    // Deserialize into another object.
    object clone = bf.Deserialize(ms);
    // Release memory.
    ms.Close();
    return clone;
  }

  static public XXX _XXXDeepCopy(XXX dcLookUpTable)
  {
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    // Serialize the object into the stream.
    bf.Serialize(ms, dcLookUpTable);
    //Position streem pointer back to first byte.
    ms.Seek(0, SeekOrigin.Begin);
    // Deserialize into another object.
    XXX cloneObject = (XXX)bf.Deserialize(ms);
    // Release memory.
    ms.Close();
    return cloneObject;
  }
}

July 14, 2005

Using Flag based Enumerated Types


class EnumSample
{
#region ControlData

/// <summary>
/// Flag based enumerated type
/// </summary>
[Flags]
private enum ControlData
{
 /// <summary>
 /// No data of any kind available
 /// </summary>
 None = 0,
 /// <summary>
 /// Hist graph data is available
 /// </summary>
 Hist = 1,
 /// <summary>
 /// Curve graph data is available
 /// </summary>
 Curve = 2,
 /// <summary>
 /// XXX data is available
 /// </summary>
 XXX = 4
}


/// <summary>
/// Record what data is available for the viewer
/// </summary>
private ControlData m_ControlData = ControlData.None;

/// <summary>
/// Is the given Data Available
/// </summary>
/// <param name="datatype">Type of data required</param>
/// <returns></returns>
public bool IsDataAvailable(ControlData datatype)
{
  return ((m_ControlData & datatype) != ControlData.None);
}

/// <summary>
/// Add the given Data Available
/// </summary>
/// <param name="datatype">Type of data now available</param>
public void AddDataAvailable(ControlData value)
{
  m_ControlData |= value;
}

#endregion ControlData
}

Drawing Rounded Rectangles

Based on some code from here I tidied it up a bit.
using System.Drawing;
using System.Drawing.Drawing2D;

class GraphicsHelper
{
 #region Drawing Rounded Rectangles

 /// <summary>
 /// Draw a rounded rectangle with the specified radius of the
 ///  rounded corners
 /// </summary>
 /// <param name="pen"></param>
 /// <param name="left"></param>
 /// <param name="top"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="radius">radius of the rounded corners</param>
 public static void _DrawRoundedRectangle(Graphics graphics, Pen pen,
  int left, int top, int width, int height, int radius)
 {
  using (GraphicsPath gp = new GraphicsPath())
  {
   _AddRoundedRectPath(gp, left, top, width, height, radius);
   gp.CloseFigure();
   graphics.DrawPath(pen, gp);
  }
 }

 /// <summary>
 /// Draw a filled rounded rectangle with the specified radius
 /// of the rounded corners
 /// </summary>
 /// <param name="brush"></param>
 /// <param name="left"></param>
 /// <param name="top"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="radius">radius of the rounded corners</param>
 public static void FillRoundedRectangle(Graphics graphics,
  Brush brush, int left, int top, int width, int height,
  int radius)

 {
  using (GraphicsPath gp = new GraphicsPath())
  {
   _AddRoundedRectPath(gp, left, top, width, height, radius);
   gp.CloseFigure();
   graphics.FillPath(brush, gp);
  }
 }

 /// <summary>
 /// Add a rounded rectangle to the given graphics path with
 /// the specified radius of the rounded corners
 /// </summary>
 /// <param name="gp"></param>
 /// <param name="left"></param>
 /// <param name="top"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="radius">radius of the rounded corners</param>
 private static void _AddRoundedRectPath(GraphicsPath gp,
  int left, int top, int width, int height, int radius)
 {
  // Top line
  gp.AddLine(left+radius, top,  left+width-radius, top);
  // Top right arc
  gp.AddArc(left+width-radius, top, radius, radius, 270, 90);

  // Right hand side line
  gp.AddLine(left+width, top+radius, left+ width, top+height-radius);
  // Bottom right arc
  gp.AddArc(left+width-radius, top+height-radius,
   radius, radius, 0, 90);

  //  Bottom line
  gp.AddLine(left+width-radius, top+height, left+radius, top+height);
  //  Bottom left arc
  gp.AddArc(left, top+height-radius, radius, radius, 90, 90);

  // Left hand side line
  gp.AddLine(left, top+height-radius, left, top+radius);
  // Top left arc
  gp.AddArc(left, top, radius, radius, 180, 90);
 }

 #endregion Drawing Rounded Rectangles
}

May 25, 2005

Useful Drawstring function

This version of Drawstring is useful it will fit the string to the given rectangle, automatically wrapping it as appropriate.
 Rectangle rect = this.ClientRectangle;
 graphics.Clear(Color.Black);
 rect.Inflate(-1,-1);
 graphics.DrawString(string.Concat("Onpaint error: \'", exception.Message, "\'")
  , theFont, Brushes.Red, rect);

Free Online HTML editor

Uses apsx HTML editor specified below. Free apsx HTML editor

Code to write to the App.Config file.

.Net provides something to read configuration file settings but nothing to write them back.

Draw Image To Fit A Rectangular Area

Following code draws an image scaled to a given rectangle, keeping the aspect ratio and centering the scaled image inside the rectangle using GDI+

 
  Graphics.DrawImage(image, FitToRect(this.ClientRectangle, image.Size));
 
 /// <summary>
 /// Fit the given src Size to the target Rectangle keeping the aspect
 /// ratio and centering the src inside the rectangle
 /// </summary>
 /// <param name="target"></param>
 /// <param name="src"></param>
 /// <returns></returns>
 static public Rectangle FitToRect(Rectangle target, Size src)
 {
    // Find the scale to fit the Src to the Target height
    float   sfh = (float)target.Height/(float)src.Height;
    // Find the scale to fit the Src to the Target width
    float   sfw = (float)target.Width/(float)src.Width;
    // Smaller of the 2 is the fit to view scale factor
    float   sf = Math.Min(sfh, sfw);
    // Find the size of the Src scaled to fit the target rectangle
    Size sizeToFit = new Size((int)Math.Round((double)src.Width*sf),
     (int)Math.Round((double)src.Height*sf) );
    Poiny loc = new Point((target.Width-sizeToFit.Width)/2,
                                    (target.Height-sizeToFit.Height)/2);
    // Now centre the scaled src size in the rectangle
    Rectangle rect = new Rectangle(loc, sizeToFit);
    return rect;
  }

May 20, 2005

ASP.NET and HTTP Protocol

Explains how HTTP protocol works. Very thorough run down of the workings of ASP.NET.

A Bunch of On line books. - These books are very basic but very detailed. They are from the same guys as above.

Difference between Invalidate, Update and Refresh

Whats the difference between Control.Invalidate, Control.Update and Control.Refresh? See here for a detailed explanantion

Summary:
Control.Invalidate() => Mark region/rectangle for painting in when next WM_PAINT is received. Asynchonouse
Control.Update() => Immediately send WM_PAINT to the WNDPROC() if update region is not empty. Synchonous
Control.Refresh() => Control.Invalidate() followed by Control.Update(). Synchonous

System.Buffer and System.BitConverter Classes

Discovered System.Buffer class that can directly manipulate the bytes of an array class objects. All its members are static.

 
 int[] myarr1 = newint[5] {1,2,3,4,5};
 int[] myarr2=newint[10] {0,0,0,0,0,6,7,8,9,10};
               
 //here we are copying offset to offet as bytes
 Buffer.BlockCopy(myarr1,0,myarr2,0,20);
It has 4 members:
  • BlockCopy - Copies a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset.
  • ByteLength - Returns the number of bytes in the specified array.
  • GetByte - Retrieves the byte at a specified location in a specified array.
  • SetByte - Assigns a specified value to a byte at a particular location in a specified

System.BitConverter class - Converts base data types to an array of bytes, and an array of bytes to base data types. See 'SelfMarshalledStruct' in OpenNETCF.Net for a sample usage. Works with the System.Buffer class for serialising/deserialising data types to byte arrays.

May 19, 2005

GetBitmapFromResources

Code to get a bitmap resource from the current Assembly
 /// <summary>
 /// Retrieves a bitmap out of the application's resources.
 /// </summary>
 /// <param name="path">Path of the resource</param>
 /// <returns>An image.</returns>
 public static Image GetBitmapFromResources( string path )
 {
  // Assembly containing the resources
  Assembly source = Assembly.GetExecutingAssembly();
 
  // Create and return image
  if ( source.GetManifestResourceStream( path ) != null)
   return new Bitmap( source.GetManifestResourceStream( path ) );
  return null;
 }
Loading animated icons from an Assembly
 private static string PrintIconResouceName =
"Controls.Common.PrintAnimated.gif";
 private static string ArchiveIconResouceName =
"Controls.Common.ArchiveAnimated.gif";

 public static Image AnimatedPrintingImage;
 public static Image AnimatedArchivingImage;

 /// <summary>
 /// // Load the animated icons from the Current Assembly
 /// </summary>
 private static void LoadAnimatedIcons()
 {

  System.IO.Stream imgStream = null;
  // get a reference to the current assembly
  System.Reflection.Assembly ass =
System.Reflection.Assembly.GetExecutingAssembly();
      
  // get a list of resource names from the manifest
  //string [] resNames = ass.GetManifestResourceNames();

  imgStream = ass.GetManifestResourceStream(PrintIconResouceName);
  if(!ReferenceEquals(null, imgStream))
  {                   
   AnimatedPrintingImage  = Image.FromStream(imgStream);
   imgStream.Close();
   imgStream = null;
  }
  else
  {
   System.Diagnostics.Debug.WriteLine("FormsHelpers.LoadAnimatedIcons,
- Could not load the Animated Printing Icon!");
  }

  imgStream = ass.GetManifestResourceStream(ArchiveIconResouceName);
  if(!ReferenceEquals(null, imgStream))
  {                   
   AnimatedArchivingImage  = Image.FromStream(imgStream);
   imgStream.Close();
   imgStream = null;
  }
  else
  {
   System.Diagnostics.Debug.WriteLine("FormsHelpers.LoadAnimatedIcons -
Could not load the Animated Printing Icon!");
  }
 }
This can be easily shortened with something like:
AnimatedPrintingImage = new Bitmap( typeof(someclass) , "print.gif");
OR
AnimatedPrintingImage = new Bitmap( ass.GetManifestResourceStream
(ArchiveIconResouceName));
I think.

Resource Constructor (Type, String)

Had a problem loading a resource using the (Type, string) constructor of a graphic type, Bitmap in this case. Had the correct syntax and could not work out why it would not load. Finally I noticed that the graphic had been added to the project file but it must be set as a 'Embedded Resource' in the 'Build Action' property of the resource in Solution Explorer. MSDN does not explain how the 'Type' parameter is used for loading the resource. However the latest version of MSDN, msdn2.microsoft.com gives a better description. Simply search on '

May 11, 2005

System.Uri Class.

Using System.Uri with a local file
Uri uri = new Uri(@"c:\somefile.dat");
uri.LocalPath  => returns 'c:\somefile.dat'
uri.ToString() => returns 'file:///c:/somefile.dat'
C# Uri Class - With lots of samples using console output to show their effects.

Always use IsWellFormedUriString before constructing an instance to ensure that the string being used is valid:
string GetUriContents(string uriString)
{
 string contents = "";
 if (!string.IsNullOrWhiteSpace(uriString) &&
         Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
 {
  Uri uri = new Uri(uriString);
  if (uri.IsAbsoluteUri || uri.IsUnc)
  {
   UrlLoader urlLoader = new UrlLoader();
   contents = urlLoader.TryGetUrlContents(uri.AbsoluteUri);
   if (contents.Length > 0)
    DoSomething();
  } 
  else if (uri.IsFile)
  {
   contents = File.ReadAllText(uri.LocalPath);
  }
 }
 return contents;
}

Batch Files

Batch file help
Batch file Command Line Parameters
Run Batch File in C#
Batch File To Clean A Build
To put all output from a command in a file (erases existing file):
command > filename  
To APPEND output to a file (great for log files):
command >> filename  
To use output from one command as input for another:
command1 | command2 
Want a certain batch file to clear the screen after running?:
echo @cls >> batfile.bat
Want to view a text file, a page at a time?:
type filename.txt  more
Use call to invoke another batch file:
CALL "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
Echo to just display a line of text in the output:
ECHO ========== Started ==========
PAUSE to make the batchfile pause until a key is pressed:
ECHO ========== Finished ==========
PAUSE
Here is an example build script:
ECHO ========== Started ==========
CALL "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
F:
cd F:\SourceControl\XXX
ECHO ========== CLEAN ==========
del /F /S /Q win32_vs90
del /F /S /Q win32_vs100
del /F /S /Q obj\d32
del /F /S /Q obj\r32
del /F /S /Q *.suo
del /F /S /Q *.ncb
del /F /S /Q *.user
msbuild /t:clean
ECHO ========== Syncing to change list 285519 ==========
p4 sync //depot/Main/XXX/...@285519
p4 -s -c RBovillTestRelated sync //depot/Main/UnitTestData/...@285519
ECHO ========== Building XXX ==========
CALL bin\VSXXX.bat -rebuild -debug -nopause
ECHO ========== Finished ==========
PAUSE

ASP.NET: Tips, Tutorials, and Code.

Quite a good book. p90 - Use DNS.Resolve to validate an email address. Tried this but it did not work with my e-mail adddresses p87 - WebClient.DownloadData to read a web page.

Winkey Shortcuts

WinKey + R - Open the Run dialog
WinKey + L - Locks a workstation
WinKey + E - Open an Explorer window
WinKey + D - Show/Hide Desktop
WinKey + Tab - Cycle through taskbar program buttons (in 3D on Windows 7/Vista)
WinKey + Pause - Open the System Properties dialog
WinKey + F - Find All Files
WinKey + Ctrl+F - Find: Computer
WinKey + M - Minimize all open windows
WinKey + Shift+M - Undo minimize all open windows
WinKey + F1 - Open Windows Help
WinKey + Up Maximize
WinKey + Down Restore / Minimize
WinKey + Left Snap to left
WinKey + Right Snap to right
WinKey + Shift+Left Jump to left monitor
WinKey + Shift+Right Jump to right monitor
WinKey + Home Minimize / Restore all other windows
WinKey + T Focus the first taskbar entry
Pressing again will cycle through them, you can can arrow around.
WinKey + Shift+T cycles backwards.
WinKey + Space Peek at the desktop
WinKey + G Bring gadgets to the top of the Z-order
WinKey + P External display options (mirror, extend desktop, etc)
WinKey + X Mobility Center (same as Vista, but still handy!)
WinKey + # where (# = number key) Launches a new instance of the application in the Nth slot on the taskbar.
Shake window title bar => Grab the window by the title bar and shake it and all the other windows will minimise

Loading Cursor From Win32 Resource File In .NET

See the my blog 'Creating a Win 32 Resource DLL' on how to create a C++ resource DLL Using Colored and Animated Cursors
Using legacy plug-ins with .NET - Using LoadLibrary,FreeLibrary and GetProcAdress within .NET to load and use legacy DLLs dynamically. Building Managed Resources from Win32 Resources Using Win32 and Other Libraries - Interop stuff Create Simple Load time DLLs
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class Win32
{
 [DllImport("user32.dll", EntryPoint = "LoadCursorFromFileW", 
CharSet = CharSet.Unicode)] public static extern IntPtr LoadCursorFromFile(String str); [DllImport("user32.dll", EntryPoint = "LoadImageW",
CharSet = CharSet.Unicode)] public static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad); public const uint LR_LOADFROMFILE = 16; public const uint IMAGE_CURSOR = 2; } class CursorLoader { /// <summary> /// Load Coloured Cursor from a file. Do not scale the cursor to
the default size /// </summary> /// <param name="filename"></param> /// <returns></returns> public static Cursor LoadCursorFromFileUnscaled(string filename) { IntPtr hCursor; Cursor result = null; hCursor = Win32.LoadImage(IntPtr.Zero, filename, Win32.IMAGE_CURSOR,
0, 0, Win32.LR_LOADFROMFILE); if (!IntPtr.Zero.Equals(hCursor)) { result = new Cursor(hCursor); } else { throw new Exception("Could not create cursor from file "
+ filename); } return result; } }
To use the method
Cursor XxxCursor = CursorLoader.LoadCursorFromFileUnscaled("Xxx.cur");
This method can be adapted to load other resource types. Just play around with the Win32 'LoadImage' API call.

Creating a Win 32 Resource DLL

Use a 'Win32 Project' template from the 'Visual C++ Projects' list of project types. In the Wizard, select 'Application Settings'. In this tab sheet set the 'Application Type' to 'DLL' and 'Additional Options' to 'Empty Project'. Add the following as a source file called 'DllMain.cpp'
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

//LPTSTR FileName = _T("AWin32Resources.dll");


BOOL WINAPI DllMain(
  HINSTANCE hinstDLL,  // handle to DLL module
  DWORD fdwReason,     // reason for calling function
  LPVOID lpReserved )  // reserved
{

  // Perform actions based on the reason for calling.
  switch( fdwReason )
  {
      case DLL_PROCESS_ATTACH:
   
   
       // Initialize once for each new process.
       // Return FALSE to fail DLL load.
          break;

      case DLL_THREAD_ATTACH:
       // Do thread-specific initialization.
          break;

      case DLL_THREAD_DETACH:
       // Do thread-specific cleanup.
          break;

      case DLL_PROCESS_DETACH:
  
       // Perform any necessary cleanup.
          break;
  }
  return TRUE;  // Successful DLL_PROCESS_ATTACH.
}
Add the resources as required.

Dynamics Graphics In ASP.Net

Use this to create a Dynamic graphics object
<img src="DynamicImage.aspx" border="1" alt="Dynamically Graphics Object">
where DynamicImage.aspx is:
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script language="C#" runat="server">

void Page_Load(Object sender, EventArgs e)
{
  Bitmap bitmap = new Bitmap(200, 200);
  Graphics gfx = Graphics.FromImage(objBitmap);

  // use 'gfx' object to create graphics
  SolidBrush objBlackBrush = new SolidBrush(Color.Black),
             objYellowBrush = new SolidBrush(Color.Yellow);
  Font font = new Font("Arial Black", 9);


  gfx.FillRectangle(new SolidBrush(Color.Ivory),
                            0, 0, 200, 200);
  gfx.DrawString("Blah, blah, blah", font, objBlackBrush, 5, 8);
  gfx.FillEllipse(objYellowBrush, 375, 5, 50, 50);
  ...

  Response.ContentType = "image/jpeg";
  bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

  gfx.Dispose();
  bitmap.Dispose();
}
</script>
The trick here is to save the bitmap to the 'OutputStream'.

April 21, 2005

Using Enumerated Types in C# as Bit Flags

example

[Flags]
  public enum Layout : byte //<= specify UNDERLYING type here
  {
    CentreColumn = 1,
    LeftColumn = 2,
    RightColumn = 4
  }
  
  private Layout m_Layout = Layout.CentreColumn | Layout.LeftColumn
| Layout.RightColumn; ... // USAGE m_Layout.ToString(); // => Gives "'CentreColumn, LeftColumn, RightColumn'" // Going the other way Layout m_Layout = (Layout)Enum.Parse(typeof(Layout), "CentreColumn, LeftColumn"); Layout m_Layout = (Layout)4; // => m_Layout = RightColumn

April 14, 2005

Weblog Sample

Took a closer look at http://www.codeproject.com/soap/weblog.asp. Tested it on my PC and it worked. Had to copy the Weblog project to my Inetpub directory and set it as an web application using the ComputerManager=>Services and Applications=>InternetInformatioServices tool.There are some useful techniques to learn from this sample. The way it uses passwords to access a webservice. I also like the fact that it persists the data direct to an XML file rather than some database. Managed to get editdvdcollection.aspx to write the updated dvdcollection.xml file correctly. I had to remove the TITLE, DESCRIPTION and LASTUPDATED elements from the COLLECTION node and then just regenerate the xsd. Makes me wonder how the DataSets handle complex XML. What if I kept these elements but put all the ENTRY nodes under a single ENTRIES node could I get the code to work then. I havent got time to investigate this I just want something that works. Next I need to work out how an aspx web page can accessed using only secured (via a password) users. I want access to a web page for everyone but the editing facilities only available to those who are logged on. When I started writing the Freelancer XSL I got used to the two different forms ways of processing nodes. I like the idea of writing a rule to match a node no matter where it is in the sequence and processing it. However sometimes you want to choose a particular node and ignore all the rest. This is why I had got used to the named template style. When writing xsl decied if all the nodes of a certain type will be output. If so use a rule to match against it, if not the parent node will have to select the interseting node or nodes and invoke a named template on them.

xsl:sort

Learned about using 'xsl:sort'. Its very easy just put it after the for statement. Specify what of part of each node processed by the 'for' dtatement is to provide the basis of the sort.

xsl:import

Got 'xsl:import' to work. Found that unlike the 'xsl:include' it has to be straight after the xsl:stylesheet' definition

Compiling an ASP.NET dll by hand

>csc /t:library /out:bin\dvdcollection.dll /r:System.dll /r:System.Web.dll dvdcollection.aspx.cs

EnableViewState="false"

<%@ Page EnableViewState="false" %> Use this to turn off ViewState in an aspx page. Its not needed unless there are controls in the page.

TechInterviews -
What does the "EnableViewState" property do? Why would I want it on or off?

Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip (as in the datagrid example in tip #4), then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.

RSS Feed Using Asp.Net

http://www.uberasp.net/getarticle.aspx?id=17 - Simple sample Using aspx to write RSS as XML to the client

April 13, 2005

Interesting Links

Discovered some useful links: This one goes over the nuances of Xml Serialization
Code Behind for Web Services. - JIT Compilation is Possible, eg '<%@ WebService language="C#" class="SomeClass" %>' just do not use the Codebehind attribute. In this case the class must exist in the same file
HTML to XML webservice

April 7, 2005

'Assembly src=' Directive

Discovered that can use 'Assembly src=' directive to compile other C# files into a single source file type aspx file. In the main source file you can use classes and types mentioned in the Assembly source file. http://www.jenitennison.com/cv.xml - CV in XML form, do View Source http://www.snapfiles.com/opinions/for_abilon.html - A freeware blogging tool Did some work on the 'EMailMe' project. I put all the code to output the stylesheet partions into a separate class. From the '.apsx' file I use type statements to output the stylesheet html statements. This means that the main block of statements for outputting the page has to be copied to each new web page. This is not perfectly satisfactory but at least the process of setting up the page is semi-automatic. Really should used the 'editdvdcollection' project to test this new code as it uses my standard web-page layout. Found the location of the IIS compiled web applications. They are at: 'C:\Documents and Settings\\VSWebCache'. Only the Web applications go here.

April 6, 2005

Browser Redirection

Skidoo_too: Use #innerColumnContainer, #outerColumnContainer { border-left-width: 0; border-right-width: 0;} to make both left and right hand menus dissappear The following line cause the browser to redirect to the specified page after 3 seconds: <meta http-equiv="refresh" content="3;URL=index.html">

April 5, 2005

Codebehind To Inline In Visual Studio

Tried a simple trick. Used Visual Studio to create a dummy web application. Changed the 'Codebehind' directive in the 'Global.asax' and 'WebForm1.aspx' files to 'Src' and the web page would load from IE without any compiling or anything. First off I just copied the 'aspx' and 'aspx.cs' file to another directory and then changed the 'Codebehind' to 'Src' and that worked as well. A simply deploy could just be to copy the files to a target directory and change the 'Codebehind'. http://www.google.com/search?q=Web+Forms+Code+Model - Web Forms Code Model. Explains COdebehind and the Single file asp.net model http://www.dotnetjunkies.com/Tutorial/3623050C-B046-4E7B-A2C7-0934F1105312.dcik - The @ Page Directive - Inherits vs.Src vs. Codebehind Codebehind is a Visual Studio attribute not a .NET attribute, it is used to track the class file associated with the form http://www.wilsondotnet.com/Demos/Generator.aspx - Generates code for a web page

April 4, 2005

Inserting C# into XSL

http://www.aspfree.com/c/a/ASP.NET/Advanced-XSL-Transformations-With-ASP-NET/ - Interesting Article on Performing XSLT tranformations in ASP.NET, in particular how to insert c# code into a XSLT stylesheet

April 3, 2005

Useful CSS Links

http://www.uoguelph.ca/~stuartr/articles/beginnercss.shtml - Good Basic Stylesheet, Try it out
http://webmonkey.wired.com/webmonkey/98/15/index0a.html - Intro to Stylesheets
http://www.mako4css.com/TMat.htm - Good stylesheets intro
http://www.bluerobot.com/web/layouts/ - Basic 2 columnn layout style sheets
http://www.alistapart.com/articles/journey/ - Found the above link here
http://glish.com/css/home.asp - More css layouts without tables
http://www.thenoodleincident.com/tutorials/box_lesson/boxes.html - More layouts horrible colours
http://www.brainjar.com/css/tabs/default3.asp - Excellent use of css to create tabs
http://cssvault.com/2005/02/index.php - Lots of sample css
http://cssvault.com/cat_layouts.phphttp://webhost.bridgew.edu/etribou/layouts/ - More layouts including Skidoo
http://webhost.bridgew.edu/etribou/layouts/2col_footer/index.html - Try this other skidoolayout, on the skidoo site it is 'Two Columns With Footer - v5'
http://www.redmelon.net/tstme/box_model/ - A Graphical Explanation of the CSS Terms (margin, padding, ...). Brilliant!
http://www.brainjar.com/css/positioning/default.asp - Links to the above web page. Another explanation of the CSS model
http://www.colorschemer.com/online.html - Another color scheme generator
http://www.wellstyled.com/css-photo-cards.html - More CSS for a nice photo placement style
http://wellstyled.com/tools/colorscheme2/index-en.html - Tool for web site colour generation
http://interglacial.com/~sburke/stuff/pretty_rss.html - Using both XSL and CSS to style a webpage.
http://www.xml.com/pub/a/2005/01/19/print.html - Why CSS is better for styling documents than XSL
http://www.javascript-page.com/css/step1.shtml - Basic CSS.
CSS Zen Garden - 1000s of CSS Samples based on a specific html page form
CSS PageMaker Template - A website that generates a web page template in CSS format from a set of options. Try the home page as well, theres alot of CSS advice

April 1, 2005

Interlocked.Exchange Hazard

object box = (object)m_StitchState;
System.Threading.Interlocked.Exchange(ref box, (int)StitchState.ImageProcessing); // WILL NOT work. 
The box copes the value type object into the box, it does not create a reference that points/refers to the location of the original value or at least we cant assume it does.