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.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,
    // 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

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


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 =
 private static string ArchiveIconResouceName =

 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 =
  // 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 = null;
- Could not load the Animated Printing Icon!");

  imgStream = ass.GetManifestResourceStream(ArchiveIconResouceName);
  if(!ReferenceEquals(null, imgStream))
   AnimatedArchivingImage  = Image.FromStream(imgStream);
   imgStream = null;
   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");
AnimatedPrintingImage = new Bitmap( ass.GetManifestResourceStream
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, 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)
  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 ==========
Here is an example build script:
ECHO ========== Started ==========
CALL "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
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 ==========

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'
#include "windows.h"

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

  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 )
       // Initialize once for each new process.
       // Return FALSE to fail DLL load.

       // Do thread-specific initialization.

       // Do thread-specific cleanup.

       // Perform any necessary cleanup.
  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);

The trick here is to save the bitmap to the 'OutputStream'.