November 23, 2005
Using C# Xml Documentation
November 21, 2005
Modifying Config File for a Log4Net 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
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#
- 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#
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() ; } }
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
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.
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.'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"
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")); } }
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
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
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
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
Rectangle rect = this.ClientRectangle; graphics.Clear(Color.Black); rect.Inflate(-1,-1); graphics.DrawString(string.Concat("Onpaint error: \'", exception.Message, "\'") , theFont, Brushes.Red, rect);
Code to write to the App.Config file.
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
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
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
/// <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)
May 11, 2005
System.Uri Class.
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 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 > filenameTo APPEND output to a file (great for log files):
command >> filenameTo use output from one command as input for another:
command1 | command2Want a certain batch file to clear the screen after running?:
echo @cls >> batfile.batWant to view a text file, a page at a time?:
type filename.txt moreUse 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 ========== PAUSEHere 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.
Winkey Shortcuts
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
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",To use the method
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; } }
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
#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
<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 28, 2005
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
xsl:sort
xsl:import
Compiling an ASP.NET dll by hand
EnableViewState="false"
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
April 13, 2005
Interesting Links
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
April 6, 2005
Browser Redirection
April 5, 2005
Codebehind To Inline In Visual Studio
April 4, 2005
Inserting C# into XSL
April 3, 2005
Useful CSS Links
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.