<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:snippet="http://codexchange.org/schemas/snippet/1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
  <channel>
    <title>CodeXchange: User Contributed Snippets</title>
    <link>http://www.codexchange.org</link>
    <description>Summary of the snippets published by a codexchange user</description>
    <language>en-us</language>
    <copyright>Copyright © CodeXchange, 2004-2006</copyright>
    <generator>CodeXchange RSS Feed Generator v1.0</generator>
    <webMaster>webmaster@codexchange.org</webMaster>
    <lastBuildDate>Fri, 07 Aug 2026 04:03:27 GMT</lastBuildDate>
    <ttl>20</ttl>
    <dc:language>en-us</dc:language>
    <dc:rights>Copyright © CodeXchange, 2004-2006</dc:rights>
    <dc:date>8/7/2026 4:03:27 AM</dc:date>
    <dc:publisher />
    <dc:creator>CodeXchange RSS Feed Generator v1.0</dc:creator>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=35588062-0416-46bc-bba8-0895eebb19ad</guid>
      <title>Returns a description of a number of bytes, in appropriate units</title>
      <link>/PreviewSnippet.aspx?SnippetID=35588062-0416-46bc-bba8-0895eebb19ad</link>
      <description>Returns a description of a number of bytes, in appropriate units [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 29 Dec 2005 14:25:49 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=35588062-0416-46bc-bba8-0895eebb19ad#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Returns a description of a number of bytes, in appropriate units</dc:title>
      <dc:date>12/29/2005 2:25:49 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        /// <summary>
        /// Returns a description of a number of bytes, in appropriate units.
        /// e.g. 
        ///		passing in 1024 will return a string "1 Kb"
        ///		passing in 1230000 will return "1.23 Mb"
        /// Megabytes and Gigabytes are formatted to 2 decimal places.
        /// Kilobytes are rounded to whole numbers.
        /// If the rounding results in 0 Kb, "1 Kb" is returned, because Windows behaves like this also.
        /// </summary>
        public static string GetFileSize(long numBytes)
        {
            string fileSize = "";

            if (numBytes > 1073741824)
                fileSize = String.Format("{0:#.00} Gb", (double)numBytes / 1073741824);
            else if (numBytes > 1048576)
                fileSize = String.Format("{0:#.00} Mb", (double)numBytes / 1048576);
            else
                fileSize = String.Format("{0:#} Kb", (double)numBytes / 1024);

            if (fileSize == "0 Kb") fileSize = "1 Kb";	// min.							
            return fileSize;
        }</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=d5c3d264-3514-4c2b-ab7b-0afea4905d7d</guid>
      <title>Windows event log helper based on IssueVision Smart Client sample</title>
      <link>/PreviewSnippet.aspx?SnippetID=d5c3d264-3514-4c2b-ab7b-0afea4905d7d</link>
      <description>Windows event log helper based on IssueVision Smart Client sample [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 02 Jun 2005 05:01:57 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=d5c3d264-3514-4c2b-ab7b-0afea4905d7d#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Windows event log helper based on IssueVision Smart Client sample</dc:title>
      <dc:date>6/2/2005 5:01:57 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Diagnostics;

namespace IssueVision
{
	// Windows event log helper.
	public class EventLogHelper
	{
		private const string m_eventLogSource = "IssueVision Smart Client 1.0";

		private EventLogHelper()
		{
		}

		// Checks for the existing of an event source. Returns true if the event 
		// source exists; otherwise false is returned.
		public static bool Exists(string eventSourceName)
		{
			return EventLog.Exists(eventSourceName);
		}

		// Creates an event source name for the windows application event log.
		public static void CreateSource(string eventSourceName)
		{
			if (!EventLog.Exists(eventSourceName))
			{
				EventLog.CreateEventSource(eventSourceName, "Application");
			}
		}

		// Removes an event source name from the windows application event log.
		public static void RemoveSource(string eventSourceName)
		{
			if (EventLog.Exists(eventSourceName))
			{
				EventLog.DeleteEventSource(eventSourceName, "Application");
			}
		}

		// Logs an error to the application log.
		public static void LogError(string message)
		{
			LogEvent(m_eventLogSource, message, EventLogEntryType.Error);
		}

		// Logs a failure audit message to the application event log.
		public static void LogFailureAudit(string message)
		{
			LogEvent(m_eventLogSource, message, EventLogEntryType.FailureAudit);
		}

		// Logs a sucess audit message to the application event log.
		public static void LogSuccessAudit(string message)
		{
			LogEvent(m_eventLogSource, message, EventLogEntryType.SuccessAudit);
		}

		// Logs a warning message to the application event log.
		public static void LogWarning(string message)
		{
			LogEvent(m_eventLogSource, message, EventLogEntryType.Warning);
		}

		// Logs an information message to the application event log.
		public static void LogInformation(string message)
		{
			LogEvent(m_eventLogSource, message, EventLogEntryType.Information);
		}

		// Log an message to the Windows Application Event Log with a specified type.
		private static void LogEvent(string eventLogSource, string message, EventLogEntryType eventLogEntryType)
		{
			EventLog.WriteEntry(eventLogSource, message, eventLogEntryType);
		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=9ba028c0-c59e-4f9b-b053-0b3e21d7bd3a</guid>
      <title>This function returns the apth of the application. Normally where your exe files reside.</title>
      <link>/PreviewSnippet.aspx?SnippetID=9ba028c0-c59e-4f9b-b053-0b3e21d7bd3a</link>
      <description>This function returns the apth of the application. Normally where your exe files reside. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:25:16 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=9ba028c0-c59e-4f9b-b053-0b3e21d7bd3a#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>This function returns the apth of the application. Normally where your exe files reside.</dc:title>
      <dc:date>4/15/2005 6:25:16 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>private string GetAppPath() 
{
	System.Reflection.Module[] modules = System.Reflection.Assembly.GetExecutingAssembly().GetModules();
	string aPath = System.IO.Path.GetDirectoryName (modules[0].FullyQualifiedName);
	if ((aPath != "") && (aPath[aPath.Length-1] != '\\'))
	{
		aPath += '\\';
	}
	return aPath;
}</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=aa5cd983-eee1-460e-b332-0c3a2c56ec01</guid>
      <title>Binary search tree</title>
      <link>/PreviewSnippet.aspx?SnippetID=aa5cd983-eee1-460e-b332-0c3a2c56ec01</link>
      <description>Binary search tree [C++]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 17 Apr 2005 10:29:53 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=aa5cd983-eee1-460e-b332-0c3a2c56ec01#comments</comments>
      <category>0f7510dd-92d6-4892-9539-4866adb651a3</category>
      <dc:title>Binary search tree</dc:title>
      <dc:date>4/17/2005 10:29:53 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>#ifndef BSTTREE
#define BSTTREE
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

template <class Type>
class Node:CObject
{
public:
Type tData;
Node* lpLeft;
Node* lpRight;
Node();
Node(Type data);
Node(Type data,Node<Type>*left,Node<Type>*right);
Node(Node<Type>& node);
Node<Type>& operator=(Node<Type>& node);
virtual ~Node();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
};


template <class Type>
Node<Type>::Node()
{
lpLeft=NULL;
lpRight=NULL;
}
template <class Type>
Node<Type>::Node(Type data)
{
tData=data;
lpLeft=NULL;
lpRight=NULL;
}
template <class Type>
Node<Type>::Node(Type data,Node<Type>*left,Node<Type>*right)
{
tData=data;
lpLeft=left;
lpRight=right;
}
template <class Type>
Node<Type>::Node(Node<Type>& node)
{
tData=node.tData;
lpLeft=NULL;
lpRight=NULL;
}
template <class Type>
Node<Type>& Node<Type>::operator =(Node<Type>& node)
{
if (this!=&node)
{
tData=node.tData;
lpLeft=NULL;
lpRight=NULL;
}
return *this;
}
template <class Type>
Node<Type>::~Node()
{
}
#ifdef _DEBUG
template <class Type>
void Node<Type>::AssertValid() const
{
}
template <class Type>
void Node<Type>::Dump(CDumpContext& dc)
{
	CObject::Dump(dc);
	dc<<"Data:"<<tData<<"\n";
	dc<<"Left:"<<lpLeft<<"\n";
	dc<<"Right:"<<lpRight<<"\n";
}
#endif
template <class Type>
class BSTTree:public CObject
{
protected:
Node<Type>*lpRoot;
public:
BSTTree();
BSTTree(Node<Type>*root);
BSTTree(BSTTree<Type>& bst);
BSTTree<Type>& operator=(BSTTree<Type>& bst);
virtual ~BSTTree();
private:
void DeleteTree(Node<Type>*root);
Node<Type>* Clone(Node<Type>*root);
public:
BSTTree<Type> Clone();
void Insert(Type data);
void InsertDuplicate(Type data);
void Delete(Type data);
void DeleteFirst(Type data);
private:
bool Delete(Node<Type>*&node,Type data);
void Insert(Node<Type>*&node,Type data);
void InsertDuplicate(Node<Type>*&node,Type data);
public:
void RotateLeft();
void RotateRight();
void RotateLeft(Type data);
void RotateRight(Type data);
private:
void RotateLeft(Node<Type>*&node);
void RotateRight(Node<Type>*&node);
void RotateLeft(Node<Type>*&node,Type data);
void RotateRight(Node<Type>*&node,Type data);
public:
bool Find(Type data);
Type Max();
Type Min();
int Count();
int Height();
Node<Type>* Node(Type data);
Node<Type>* Root();
private:
	int Count(Node<Type>*node);
	int Height(Node<Type>*node);
public:
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif
};

template <class Type>
BSTTree<Type>::BSTTree()
{
lpRoot=NULL;
}
template <class Type>
BSTTree<Type>::BSTTree(Node<Type>*root)
{
if (lpRoot!=root)
{
DeleteTree(lpRoot);
lpRoot=Clone(root);
}
}
template <class Type>
BSTTree<Type>::BSTTree(BSTTree<Type>& bst)
{
*this=bst;
}
template <class Type>
BSTTree<Type>& BSTTree<Type>::operator =(BSTTree<Type>& bst)
{
if (this!=&bst)
{
lpRoot=NULL;
lpRoot=Clone(bst.lpRoot);
}
return *this;
}

template <class Type>
BSTTree<Type>::~BSTTree()
{
DeleteTree(lpRoot);
}

template <class Type>
void BSTTree<Type>::DeleteTree(Node<Type>*root)
{
if (root==NULL)
return;
if (root->lpLeft!=NULL)
DeleteTree(root->lpLeft);
if (root->lpRight!=NULL)
DeleteTree(root->lpRight);

delete root;
root=NULL;
}

template <class Type>
Node<Type>* BSTTree<Type>::Clone(Node<Type>*root)
{
if (root==NULL)
 return NULL;
 
return (new Node<Type>(root->tData,Clone(root->lpLeft),Clone(root->lpRight)));
}
template <class Type>
void BSTTree<Type>::Insert(Node<Type>*&node,Type data)
{
if (node==NULL)
node=new Node<Type>(data);
else
if (data<node->tData)
Insert(node->lpLeft,data);
else
if (data>node->tData)
Insert(node->lpRight,data);
}

template <class Type>
void BSTTree<Type>::Insert(Type data)
{
Insert(lpRoot,data);
}
template <class Type>
void BSTTree<Type>::InsertDuplicate(Node<Type>*&node,Type data)
{
if (node==NULL)
node=new Node<Type>(data);
else
if (data<node->tData)
Insert(node->lpLeft,data);
else
Insert(node->lpRight,data);
}
template <class Type>
void BSTTree<Type>::InsertDuplicate(Type data)
{
InsertDuplicate(lpRoot,data);
}

template <class Type>
bool BSTTree<Type>::Delete(Node<Type>*&node,Type data)
{
Node<Type>**q,*p;
if (node==NULL)
return false;
if (data<node->tData)
Delete(node->lpLeft,data);
else
if (data>node->tData)
Delete(node->lpRight,data);
else
{
if (node->lpRight==NULL)
{
p=node;
node=node->lpLeft;
delete p;
return true;
}
else
if (node->lpLeft==NULL)
{
p=node;
node=node->lpRight;
delete p;
return true;
}
else
{
q=&node->lpLeft;
while ((*q)->lpRight != NULL)
q=&(*q)->lpRight;
node->tData=(*q)->tData;
(*q)->tData=data;
Delete(node->lpLeft,data);
}
}
}

template <class Type>
void BSTTree<Type>::Delete(Type data)
{
while (Delete(lpRoot,data));
}
template <class Type>
void BSTTree<Type>::DeleteFirst(Type data)
{
Delete(lpRoot,data);
}
template <class Type>
BSTTree<Type> BSTTree<Type>::Clone()
{
return BSTTree<Type>(*this);
}
template <class Type>
void BSTTree<Type>::RotateLeft(Node<Type>*&p)
{
Node<Type>*q=p;
p=p->lpRight;
q->lpRight=p->lpLeft;
p->lpLeft=q;
}
template <class Type>
void BSTTree<Type>::RotateLeft()
{
RotateLeft(lpRoot);
}
template <class Type>
void BSTTree<Type>::RotateRight(Node<Type>*&p)
{
Node<Type>*q=p;
p=p->lpLeft;
q->lpLeft=p->lpRight;
p->lpRight=q;
}
template <class Type>
void BSTTree<Type>::RotateRight()
{
RotateRight(lpRoot);
}

template <class Type>
void BSTTree<Type>::RotateLeft(Node<Type>*&p,Type data)
{
 if (p->tData==data)
 RotateLeft(p);
 else
 if (data<p->tData)
 RotateLeft(p->lpLeft,data);
 else
 RotateLeft(p->lpRight,data);
}
template <class Type>
void BSTTree<Type>::RotateLeft(Type data)
{
RotateLeft(lpRoot,data);
}

template <class Type>
void BSTTree<Type>::RotateRight(Node<Type>*&p,Type data)
{
 if (p->tData==data)
 RotateRight(p);
 else
 if (data<p->tData)
 RotateRight(p->lpLeft,data);
 else
 RotateRight(p->lpRight,data);
}
template <class Type>
void BSTTree<Type>::RotateRight(Type data)
{
RotateRight(lpRoot,data);
}
template <class Type>
bool BSTTree<Type>::Find(Type data)
{
Node<Type>*cur=lpRoot;
while (cur)
{
if (cur->tData==data)
return true;
else
if (data<cur->tData)
cur=cur->lpLeft;
else
cur=cur->lpRight;
}
return false;
}

template <class Type>
Type BSTTree<Type>::Max(Type data)
{
Node<Type>*cur=lpRoot;
if (!cur)return NULL;
while(cur->lpRight)
cur=cur->lpRight;
return cur->tData;
}
template <class Type>
Type BSTTree<Type>::Min()
{
Node<Type>*cur=lpRoot;
if (!cur)return NULL;
while(cur->lpLeft)
cur=cur->lpLeft;
return cur->tData;
}
template <class Type>
int Count(Node<Type>*node)
{
	if (node==NULL)
		return 0;
	return Count(node->lpLeft)+Count(node->lpRight)+1;
}
template <class Type>
int Count()
{
	return Count(lpRoot);
}
template <class Type>
int Height(Node<Type>*node)
{
	if (node==NULL) return -1;
	int u=Height(node->lpLeft),v=Height(node->lpRight);
	if (u>v)return u+1;else return v+1;
}
template <class Type>
int Height()
{
	return Height(lpRoot);
}

template <class Type>
Node<Type>* BSTTree<Type>::Node(Type data)
{
Node<Type>*cur=lpRoot;
while (cur)
{
if (cur->tData==data)
return cur;
else
if (data<cur->tData)
cur=cur->lpLeft;
else
cur=cur->lpRight;
}
return NULL;
}
template <class Type>
Node<Type>* BSTTree<Type>::Root()
{
	return lpRoot;	
}
#ifdef _DEBUG
template <class Type>
void BSTTree<Type>::AssertValid()
{
}
template <class Type>
void BSTTree<Type>::Dump(CDumpContext& dc)
{
}

#endif</pre>]]></content:encoded>
      <snippet:downloads>17</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C++</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=de34be62-40f7-4df1-a38f-0c9eadd1b9f5</guid>
      <title>The folder for the framework is located under </title>
      <link>/PreviewSnippet.aspx?SnippetID=de34be62-40f7-4df1-a38f-0c9eadd1b9f5</link>
      <description>The folder for the framework is located under  [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 15 Jan 2006 12:40:51 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=de34be62-40f7-4df1-a38f-0c9eadd1b9f5#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>The folder for the framework is located under </dc:title>
      <dc:date>1/15/2006 12:40:51 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>    ''' <summary>
    ''' Assumption: The folder for the framework is located under 
    ''' [System Drive]\Windows\Microsoft.Net\Framework\v[Major.Minor.Build]
    ''' 
    ''' The Major, Minor and Build number are obtained using the .NET Framework
    ''' class System.Environment. This yields the version number of the CLR it 
    ''' was built with. In this case it will be .NET Framework 2.0 with specific
    ''' minor and build numbers.
    ''' </summary>
    ''' <returns></returns>
    Private Function GetFrameworkFolder() As String

        Dim frameworkFolder As String = Path.Combine(Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.System)).FullName, "Microsoft.NET")
        frameworkFolder = Path.Combine(frameworkFolder, "Framework")

        Dim version As String = "v" + Environment.Version.Major.ToString() + "." + Environment.Version.Minor.ToString() + "." + Environment.Version.Build.ToString()
        frameworkFolder = Path.Combine(frameworkFolder, version)

        Return frameworkFolder

    End Function</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=508f1ed1-b33f-418d-b6d2-0d168368eef9</guid>
      <title>File System image selector (BMP , GIF , etc..) type editor</title>
      <link>/PreviewSnippet.aspx?SnippetID=508f1ed1-b33f-418d-b6d2-0d168368eef9</link>
      <description>File System image selector (BMP , GIF , etc..) type editor [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 12 Jun 2005 13:02:29 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=508f1ed1-b33f-418d-b6d2-0d168368eef9#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>File System image selector (BMP , GIF , etc..) type editor</dc:title>
      <dc:date>6/12/2005 1:02:29 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>	public class ImageFileNameEditor : System.Windows.Forms.Design.FileNameEditor 
	{ 
		protected override void InitializeDialog(OpenFileDialog ofd) 
		{ 
			ofd.Filter = "Image file (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All (*.*)|*.*"; 
		}
	}
</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=5f100682-bdc3-4965-952c-0d42f2466485</guid>
      <title>Opening the CD-ROM Drive with Win32 Interop</title>
      <link>/PreviewSnippet.aspx?SnippetID=5f100682-bdc3-4965-952c-0d42f2466485</link>
      <description>Opening the CD-ROM Drive with Win32 Interop [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 17 Apr 2005 10:44:51 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=5f100682-bdc3-4965-952c-0d42f2466485#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Opening the CD-ROM Drive with Win32 Interop</dc:title>
      <dc:date>4/17/2005 10:44:51 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>private void btnEject_Click( object sender, System.EventArgs e )
{
  int ret = mciSendString( "set cdaudio door open", null, 0, IntPtr.Zero );
}

private void btnClose_Click( object sender, System.EventArgs e )
{
  int ret = mciSendString( "set cdaudio door closed", null, 0, IntPtr.Zero );
}

[DllImport( "winmm.dll", EntryPoint="mciSendStringA", CharSet=CharSet.Ansi )]
protected static extern int mciSendString( string lpstrCommand,
                                           StringBuilder lpstrReturnString,
                                           int uReturnLength,
                                           IntPtr hwndCallback );</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ed522082-3ddb-4d01-926e-0e623e962d7d</guid>
      <title>Symmetric key encryption and decryption using Rijndael algorithm.</title>
      <link>/PreviewSnippet.aspx?SnippetID=ed522082-3ddb-4d01-926e-0e623e962d7d</link>
      <description>Symmetric key encryption and decryption using Rijndael algorithm. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 16 Aug 2005 13:06:25 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ed522082-3ddb-4d01-926e-0e623e962d7d#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Symmetric key encryption and decryption using Rijndael algorithm.</dc:title>
      <dc:date>8/16/2005 1:06:25 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
// 
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// Copyright (C) Obviex(TM). All rights reserved.
// 
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and 
/// decrypt data. As long as encryption and decryption routines use the same
/// parameters to generate the keys, the keys are guaranteed to be the same.
/// The class uses static functions with duplicate code to make it easier to
/// demonstrate encryption and decryption logic. In a real-life application, 
/// this may not be the most efficient way of handling encryption, so - as
/// soon as you feel comfortable with it - you may want to redesign this class.
/// </summary>
public class RijndaelSimple
{
    /// <summary>
    /// Encrypts specified plaintext using Rijndael symmetric key algorithm
    /// and returns a base64-encoded result.
    /// </summary>
    /// <param name="plainText">
    /// Plaintext value to be encrypted.
    /// </param>
    /// <param name="passPhrase">
    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.
    /// </param>
    /// <param name="saltValue">
    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    /// </param>
    /// <param name="passwordIterations">
    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    /// </param>
    /// <param name="initVector">
    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be 
    /// exactly 16 ASCII characters long.
    /// </param>
    /// <param name="keySize">
    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
    /// Longer keys are more secure than shorter keys.
    /// </param>
    /// <returns>
    /// Encrypted value formatted as a base64-encoded string.
    /// </returns>
    public static string Encrypt(string   plainText,
                                 string   passPhrase,
                                 string   saltValue,
                                 string   hashAlgorithm,
                                 int      passwordIterations,
                                 string   initVector,
                                 int      keySize)
    {
        // Convert strings into byte arrays.
        // Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);
        
        // Convert our plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes  = Encoding.UTF8.GetBytes(plainText);
        
        // First, we must create a password, from which the key will be derived.
        // This password will be generated from the specified passphrase and 
        // salt value. The password will be created using the specified hash 
        // algorithm. Password creation can be done in several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase, 
                                                        saltValueBytes, 
                                                        hashAlgorithm, 
                                                        passwordIterations);
        
        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);
        
        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();
        
        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;        
        
        // Generate encryptor from the existing key bytes and initialization 
        // vector. Key size will be defined based on the number of the key 
        // bytes.
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                         keyBytes, 
                                                         initVectorBytes);
        
        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream();        
                
        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream, 
                                                     encryptor,
                                                     CryptoStreamMode.Write);
        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                
        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();
                
        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();
        
        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);
        
        // Return encrypted string.
        return cipherText;
    }
    
    /// <summary>
    /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
    /// </summary>
    /// <param name="cipherText">
    /// Base64-formatted ciphertext value.
    /// </param>
    /// <param name="passPhrase">
    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.
    /// </param>
    /// <param name="saltValue">
    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    /// </param>
    /// <param name="passwordIterations">
    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    /// </param>
    /// <param name="initVector">
    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be
    /// exactly 16 ASCII characters long.
    /// </param>
    /// <param name="keySize">
    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
    /// Longer keys are more secure than shorter keys.
    /// </param>
    /// <returns>
    /// Decrypted string value.
    /// </returns>
    /// <remarks>
    /// Most of the logic in this function is similar to the Encrypt
    /// logic. In order for decryption to work, all parameters of this function
    /// - except cipherText value - must match the corresponding parameters of
    /// the Encrypt function which was called to generate the
    /// ciphertext.
    /// </remarks>
    public static string Decrypt(string   cipherText,
                                 string   passPhrase,
                                 string   saltValue,
                                 string   hashAlgorithm,
                                 int      passwordIterations,
                                 string   initVector,
                                 int      keySize)
    {
        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);
        
        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        
        // First, we must create a password, from which the key will be 
        // derived. This password will be generated from the specified 
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase, 
                                                        saltValueBytes, 
                                                        hashAlgorithm, 
                                                        passwordIterations);
        
        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);
        
        // Create uninitialized Rijndael encryption object.
        RijndaelManaged    symmetricKey = new RijndaelManaged();
        
        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;
        
        // Generate decryptor from the existing key bytes and initialization 
        // vector. Key size will be defined based on the number of the key 
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                         keyBytes, 
                                                         initVectorBytes);
        
        // Define memory stream which will be used to hold encrypted data.
        MemoryStream  memoryStream = new MemoryStream(cipherTextBytes);
                
        // Define cryptographic stream (always use Read mode for encryption).
        CryptoStream  cryptoStream = new CryptoStream(memoryStream, 
                                                      decryptor,
                                                      CryptoStreamMode.Read);

        // Since at this point we don't know what the size of decrypted data
        // will be, allocate the buffer long enough to hold ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        
        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 
                                                   0, 
                                                   plainTextBytes.Length);
                
        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();
        
        // Convert decrypted data into a string. 
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 
                                                   0, 
                                                   decryptedByteCount);
        
        // Return decrypted string.   
        return plainText;
    }
}

/// <summary>
/// Illustrates the use of RijndaelSimple class to encrypt and decrypt data.
/// </summary>
public class RijndaelSimpleTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        string   plainText          = "Hello, World!";    // original plaintext
        
        string   passPhrase         = "Pas5pr@se";        // can be any string
        string   saltValue          = "s@1tValue";        // can be any string
        string   hashAlgorithm      = "SHA1";             // can be "MD5"
        int      passwordIterations = 2;                  // can be any number
        string   initVector         = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int      keySize            = 256;                // can be 192 or 128
        
        Console.WriteLine(String.Format("Plaintext : {0}", plainText));

        string  cipherText = RijndaelSimple.Encrypt(plainText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Encrypted : {0}", cipherText));
        
        plainText          = RijndaelSimple.Decrypt(cipherText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Decrypted : {0}", plainText));
    }
}
</pre>]]></content:encoded>
      <snippet:downloads>13</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=f8227327-73a3-4a8c-8d82-11fccd3593c3</guid>
      <title>How to retrieve an icon based on the file type</title>
      <link>/PreviewSnippet.aspx?SnippetID=f8227327-73a3-4a8c-8d82-11fccd3593c3</link>
      <description>How to retrieve an icon based on the file type [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 24 Apr 2005 10:46:02 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=f8227327-73a3-4a8c-8d82-11fccd3593c3#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>How to retrieve an icon based on the file type</dc:title>
      <dc:date>4/24/2005 10:46:02 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public class ExtractIcon
{
    [DllImport("Shell32.dll")]
    private static extern int SHGetFileInfo
        (
        string pszPath,
        uint dwFileAttributes,
        out SHFILEINFO psfi,
        uint cbfileInfo,
        SHGFI uFlags
        );

    [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
    {
        public SHFILEINFO(bool b)
        {
            hIcon=IntPtr.Zero;iIcon=0;dwAttributes=0;szDisplayName="";szTypeName="";
        }
        public IntPtr hIcon;
        public int iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.LPStr, SizeConst=260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.LPStr, SizeConst=80)]
        public string szTypeName;
    };

    private ExtractIcon()
    {
    }

    private enum SHGFI
    {
        SmallIcon = 0x00000001,
        OpenIcon = 0x00000002,
        LargeIcon = 0x00000000,
        Icon = 0x00000100,
        DisplayName = 0x00000200,
        Typename = 0x00000400,
        SysIconIndex = 0x00004000,
        LinkOverlay = 0x00008000,
        UseFileAttributes = 0x00000010
    }

    /// <summary>
    /// Get the associated Icon for a file or application, this method always returns
    /// an icon. If the strPath is invalid or there is no idonc the default icon is returned
    /// </summary>
    /// <param name="strPath">full path to the file or directory</param>
    /// <param name="bSmall">if true, the 16x16 icon is returned otherwise the 32x32</param>
    /// <param name="bOpen">if true, and strPath is a folder, returns the 'open' icon rather than the 'closed'</param>
    /// <returns></returns>
    public static Icon GetIcon(string strPath, bool bSmall, bool bOpen)
    {
        SHFILEINFO info = new SHFILEINFO(true);
        int cbFileInfo = Marshal.SizeOf(info);
        SHGFI flags;
        if (bSmall)
            flags = SHGFI.Icon|SHGFI.SmallIcon;
        else
            flags = SHGFI.Icon|SHGFI.LargeIcon;
        if (bOpen) flags = flags|SHGFI.OpenIcon;

        SHGetFileInfo(strPath, 256, out info,(uint)cbFileInfo, flags);
        return Icon.FromHandle(info.hIcon);
    }
}

// Here is sample code to call the class:
Icon myicon = ExtractIcon.GetIcon (mypath, true, false);
</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=02fc4dcd-8150-4213-bfc3-1426f5f1f331</guid>
      <title>Generate Random Number</title>
      <link>/PreviewSnippet.aspx?SnippetID=02fc4dcd-8150-4213-bfc3-1426f5f1f331</link>
      <description>Generate Random Number [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:33:03 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=02fc4dcd-8150-4213-bfc3-1426f5f1f331#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Generate Random Number</dc:title>
      <dc:date>4/15/2005 6:33:03 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Dim RanNum As Random = New Random(CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
Dim Num As Integer
Num = RanNum.Next() ' Puts The Random Number In The Num Variable</pre>]]></content:encoded>
      <snippet:downloads>22</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=85e435d6-cd41-4cf0-9de2-1685818e95f0</guid>
      <title>Function to test whether the string is valid number or not Regex</title>
      <link>/PreviewSnippet.aspx?SnippetID=85e435d6-cd41-4cf0-9de2-1685818e95f0</link>
      <description>Function to test whether the string is valid number or not Regex [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 19 Apr 2005 13:14:49 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=85e435d6-cd41-4cf0-9de2-1685818e95f0#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Function to test whether the string is valid number or not Regex</dc:title>
      <dc:date>4/19/2005 1:14:49 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>///Function to test whether the string is valid number or not Regex
  public bool IsNumber(string strNumber)
  {
    Regex objNotNumberPattern=new Regex("[^0-9.-]");
    Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
    Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
    String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
    String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
    Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");

    return !objNotNumberPattern.IsMatch(strNumber) &&
           !objTwoDotPattern.IsMatch(strNumber) &&
           !objTwoMinusPattern.IsMatch(strNumber) &&
           objNumberPattern.IsMatch(strNumber);
  }
</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=0fe69f63-3e6b-4c25-92a5-177bf0c0735f</guid>
      <title>How to check if a given share exist on a server?</title>
      <link>/PreviewSnippet.aspx?SnippetID=0fe69f63-3e6b-4c25-92a5-177bf0c0735f</link>
      <description>How to check if a given share exist on a server? [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 11:45:20 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=0fe69f63-3e6b-4c25-92a5-177bf0c0735f#comments</comments>
      <category>edde3ea1-24a6-4cb0-8446-ab91e1800116</category>
      <dc:title>How to check if a given share exist on a server?</dc:title>
      <dc:date>4/16/2005 11:45:20 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Runtime.InteropServices;

namespace CodeXchangeSamples
{
	public class NetApiWin32
	{
		[DllImport("Netapi32.dll")]
		public static extern int NetShareCheck(
			[MarshalAs(UnmanagedType.LPWStr)]string ServerName,
			[MarshalAs(UnmanagedType.LPWStr)]string Device,
			out long Type);
	}

bool IsResourceShared(string strServer, string strResourceName, out ShareType nType)
{
	bool bRet = false;
	nType = ShareType.STYPE_DISKTREE;
	long lType = 0;
	int nRet = NetApiWin32.NetShareCheck(strServer, strResourceName, out lType);
	bRet = (0 == nRet);
	if (!bRet)
	{
		if (nRet == 2311)
		{
			Console.WriteLine("Device not shared");
		}
		else if (nRet == 2310)
		{
			Console.WriteLine("The device does not exist");
		}
		else
		{
			Console.WriteLine("Unknown win32 error");
		}
	}
	else
	{
		nType = (ShareType)lType;
	}
	return bRet;
      }
}</pre>]]></content:encoded>
      <snippet:downloads>7</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=f679eb1c-a472-4f1b-bd24-1843a9fcbfa9</guid>
      <title>Using regular expressions . Simple C# Regex Sample.</title>
      <link>/PreviewSnippet.aspx?SnippetID=f679eb1c-a472-4f1b-bd24-1843a9fcbfa9</link>
      <description>Using regular expressions . Simple C# Regex Sample. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 19 Apr 2005 09:41:32 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=f679eb1c-a472-4f1b-bd24-1843a9fcbfa9#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Using regular expressions . Simple C# Regex Sample.</dc:title>
      <dc:date>4/19/2005 9:41:32 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System.Text.RegularExpressions;
class RegExSample 
{
   static string CapText(Match m) 
   {
      // Get the matched string.
      string x = m.ToString();
      // If the first char is lower case...
      if (char.IsLower(x[0])) 
      {
         // Capitalize it.
         return char.ToUpper(x[0]) + x.Substring(1, x.Length-1);
      }
      return x;
   }
    
   static void Main() 
   {
      string text = "four score and seven years ago";
      System.Console.WriteLine("text=[" + text + "]");
      string result = Regex.Replace(text, @"\w+",
         new MatchEvaluator(RegExSample.CapText));
      System.Console.WriteLine("result=[" + result + "]");
   }
}</pre>]]></content:encoded>
      <snippet:downloads>23</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=9774a13f-d2d0-4b7b-9b00-1bf51873892d</guid>
      <title>This example shows various aspects of defining, initializing, and using arrays.</title>
      <link>/PreviewSnippet.aspx?SnippetID=9774a13f-d2d0-4b7b-9b00-1bf51873892d</link>
      <description>This example shows various aspects of defining, initializing, and using arrays. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 19 May 2005 19:33:49 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=9774a13f-d2d0-4b7b-9b00-1bf51873892d#comments</comments>
      <category>f8b47dd5-9f0a-4831-b7ad-ae8d5083baf3</category>
      <dc:title>This example shows various aspects of defining, initializing, and using arrays.</dc:title>
      <dc:date>5/19/2005 7:33:49 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>static void ArrayDemo() {
   // Declare a reference to an array
   Int32[] ia; // defaults to null
   ia = new Int32[100];
   ia = new Int32[] { 1, 2, 3, 4, 5 };
   // Display the array's contents
   foreach (Int32 x in ia) 
      Console.Write("{0} ", x);

   // Working with multi-dimensional arrays
   StringBuilder[,] sa = new StringBuilder[10][5];
   for (int x = 0; x < 10; x++) {
      for (int y = 0; y < 5; y++) {
         sa[x][y] = new StringBuilder(10);
      }
   }
   // Working with jagged arrays (arrays of arrays)
   Int32 numPolygons = 3;
   Point[][] polygons = new Point[numPolygons][];
   polygons[0] = new Point[3]  { ... };
   polygons[1] = new Point[5]  { ... };
   polygons[2] = new Point[10] { ... };
}</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=3001fbcd-7baf-4637-bfd8-1cd0d4df6f26</guid>
      <title>This snippet shows how to merge 2 datasets which are stored locally in an xml file </title>
      <link>/PreviewSnippet.aspx?SnippetID=3001fbcd-7baf-4637-bfd8-1cd0d4df6f26</link>
      <description>This snippet shows how to merge 2 datasets which are stored locally in an xml file  [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:24:31 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=3001fbcd-7baf-4637-bfd8-1cd0d4df6f26#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>This snippet shows how to merge 2 datasets which are stored locally in an xml file </dc:title>
      <dc:date>4/15/2005 6:24:31 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>// read the local xml dataset
// mark that the schema for this Dataset defines the column id as primary key
DataSet dataSet = new DataSet();
dataSet.ReadXmlSchema("..\\..\\Dataset1.xsd");
dataSet.ReadXml("..\\..\\Dataset1.xml");
// create a temporary dataset
// consider we manually set the primary key
// that is actually the most important part because the merge is done based on the key
DataSet TMPdataSet = new DataSet();
DataTable TMPdataTable = TMPdataSet.Tables.Add("Project");
DataColumn TMPdataTableID = TMPdataTable.Columns.Add("id",typeof(int));
DataColumn TMPdataTableNAME = TMPdataTable.Columns.Add("name",typeof(string));
TMPdataTable.PrimaryKey = new DataColumn [] {TMPdataTableID};
// just fill in some stupid data
DataRow TMPdataRow = TMPdataTable.NewRow();
TMPdataRow["id"] = 1;
TMPdataRow["name"] = "project1";
TMPdataTable.Rows.Add(TMPdataRow);
// merge  the datasets
dataSet.Merge(TMPdataSet);
dataSet.WriteXml("..\\..\\Dataset1.xml",XmlWriteMode.DiffGram);</pre>]]></content:encoded>
      <snippet:downloads>20</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=1f06c95b-78d4-4396-81ea-1dee7e665347</guid>
      <title>A VB.NET implementation of a DPAPI wrapper, based on the DPAPI wrapper in IssueVision</title>
      <link>/PreviewSnippet.aspx?SnippetID=1f06c95b-78d4-4396-81ea-1dee7e665347</link>
      <description>A VB.NET implementation of a DPAPI wrapper, based on the DPAPI wrapper in IssueVision [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 29 May 2005 00:11:15 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=1f06c95b-78d4-4396-81ea-1dee7e665347#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>A VB.NET implementation of a DPAPI wrapper, based on the DPAPI wrapper in IssueVision</dc:title>
      <dc:date>5/29/2005 12:11:15 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.Text
Imports System.Runtime.InteropServices
Public Module DataProtection
    Public Enum Store
        Machine
        User
    End Enum
    Private Class Consts
        Public Shared ReadOnly entropyData As Byte() = _
            ASCIIEncoding.ASCII.GetBytes("1295C82E-6D6E-4a01-96DD-
                                          1BF76B7F4CB4")
    End Class
    Private Class Win32
        Public Const CRYPTPROTECT_UI_FORBIDDEN As Integer  = &H1
        Public Const CRYPTPROTECT_LOCAL_MACHINE As Integer = &H4
        <StructLayout(LayoutKind.Sequential)> _
        Public Structure DATA_BLOB
            Public cbData As Integer
            Public pbData As IntPtr
        End Structure
        <DllImport("crypt32", CharSet:=CharSet.Auto)> _
        Public Shared Function CryptProtectData(ByRef _
            pDataIn As DATA_BLOB, _
            ByVal szDataDescr As String, _
            ByRef pOptionalEntropy As DATA_BLOB, _
            ByVal pvReserved As IntPtr, _
            ByVal pPromptStruct As IntPtr, _
            ByVal dwFlags As Integer, _
            ByRef pDataOut As DATA_BLOB) As Boolean
        End Function

        <DllImport("crypt32", CharSet:=CharSet.Auto)> _
         Public Shared Function CryptUnprotectData(ByRef _
           pDataIn As DATA_BLOB, _
           ByVal szDataDescr As StringBuilder, _
           ByRef pOptionalEntropy As DATA_BLOB, _
           ByVal pvReserved As IntPtr, _
           ByVal pPromptStruct As IntPtr, _
           ByVal dwFlags As Integer, _
           ByRef pDataOut As DATA_BLOB) As Boolean
        End Function
        <DllImport("kernel32")> _
        Public Shared Function LocalFree(ByVal hMem As IntPtr) As IntPtr
        End Function
    End Class
    Public Function Encrypt(ByVal data As String, _
        ByVal store As Store) As String
        Dim inBlob As Win32.DATA_BLOB      = New Win32.DATA_BLOB
        Dim entropyBlob As Win32.DATA_BLOB = New Win32.DATA_BLOB
        Dim outBlob As Win32.DATA_BLOB     = New Win32.DATA_BLOB
        Dim result As String = ""
        Try
            Dim flags As Integer = Win32.CRYPTPROTECT_UI_FORBIDDEN
            If (store = store.Machine) Then
                flags = flags Or Win32.CRYPTPROTECT_LOCAL_MACHINE
            End If
            SetBlobData(inBlob, UTF8Encoding.UTF8.GetBytes(data))
            SetBlobData(entropyBlob, Consts.entropyData)
            If (Win32.CryptProtectData(inBlob, "", _
                entropyBlob, IntPtr.Zero, _
                IntPtr.Zero, flags, outBlob)) Then
                Dim resultBits() As Byte = GetBlobData(outBlob)
                If (resultBits.Length <> 0) Then
                    result = Convert.ToBase64String(resultBits)
                End If
            End If

        Catch ex As Exception
            Return String.Empty
        Finally
            If (inBlob.pbData.ToInt32() <> 0) Then
                Marshal.FreeHGlobal(inBlob.pbData)
            End If
            If (entropyBlob.pbData.ToInt32() <> 0) Then
                Marshal.FreeHGlobal(entropyBlob.pbData)
            End If
        End Try
        Return result
    End Function
    Public Function Decrypt(ByVal data As String, _
                            ByVal store As Store) As String
        Dim result As String = ""
        Dim inBlob As Win32.DATA_BLOB      = New Win32.DATA_BLOB
        Dim entropyBlob As Win32.DATA_BLOB = New Win32.DATA_BLOB
        Dim outBlob As Win32.DATA_BLOB     = New Win32.DATA_BLOB
        Try
            Dim flags As Integer = Win32.CRYPTPROTECT_UI_FORBIDDEN
            If (store = store.Machine) Then
                flags = flags Or Win32.CRYPTPROTECT_LOCAL_MACHINE
            End If
            Dim bits() As Byte = Convert.FromBase64String(data)
            SetBlobData(inBlob, bits)
            SetBlobData(entropyBlob, Consts.entropyData)
            If (Win32.CryptUnprotectData(inBlob, Nothing, entropyBlob, _
                IntPtr.Zero, IntPtr.Zero, flags, outBlob)) Then
                Dim resultBits() As Byte = GetBlobData(outBlob)
                If (resultBits.Length <> 0) Then
                    result = UTF8Encoding.UTF8.GetString(resultBits)
                End If
            End If
        Catch ex As Exception
            Return String.Empty
        Finally
            If (inBlob.pbData.ToInt32() <> 0) Then
                Marshal.FreeHGlobal(inBlob.pbData)
            End If
            If (entropyBlob.pbData.ToInt32() <> 0) Then
                Marshal.FreeHGlobal(entropyBlob.pbData)
            End If
        End Try
        Return result
    End Function
    Private Sub SetBlobData(ByRef blob As Win32.DATA_BLOB, _
                            ByVal bits() As Byte)
        blob.cbData = bits.Length
        blob.pbData = Marshal.AllocHGlobal(bits.Length)
        Marshal.Copy(bits, 0, blob.pbData, bits.Length)
    End Sub
    Private Function GetBlobData(ByRef blob As Win32.DATA_BLOB) As Byte()
        If (blob.pbData.ToInt32() = 0) Then Return Nothing
        Dim data(blob.cbData) As Byte
        Marshal.Copy(blob.pbData, data, 0, blob.cbData)
        Win32.LocalFree(blob.pbData)
        Return data
    End Function
End Module</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=067bab21-b5d9-484b-a508-1e36dc357cf2</guid>
      <title>Draw Gradient on Form</title>
      <link>/PreviewSnippet.aspx?SnippetID=067bab21-b5d9-484b-a508-1e36dc357cf2</link>
      <description>Draw Gradient on Form [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:47:26 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=067bab21-b5d9-484b-a508-1e36dc357cf2#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Draw Gradient on Form</dc:title>
      <dc:date>4/6/2005 1:47:26 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        Imports System.Drawing.Drawing2D
        'In the Form_Paint event. Put the following code
        Dim rec As Rectangle = New Rectangle(0, 0, Me.Width, Me.Height) 'create a new recatangle
        'Create a new brush. Make is a Gradient style brush.
        Dim myBrush As Brush = New LinearGradientBrush(rec, Color.Aqua, Color.Yellow, LinearGradientMode.ForwardDiagonal)
        'draw the gradient onto the form.
        e.Graphics.FillRectangle(myBrush, rec)
</pre>]]></content:encoded>
      <snippet:downloads>31</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=4249566f-9d8d-415a-9f60-1f9c12223730</guid>
      <title>Code for a sitemap generation (Google Sitemap format)</title>
      <link>/PreviewSnippet.aspx?SnippetID=4249566f-9d8d-415a-9f60-1f9c12223730</link>
      <description>Code for a sitemap generation (Google Sitemap format) [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 19 Jul 2005 02:53:28 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=4249566f-9d8d-415a-9f60-1f9c12223730#comments</comments>
      <category>e5dc5661-427e-4d33-8be6-187bd2783223</category>
      <dc:title>Code for a sitemap generation (Google Sitemap format)</dc:title>
      <dc:date>7/19/2005 2:53:28 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.IO;
using System.Xml;
using System.Text;

namespace GoogleSiteMapGenerator
{
	/// <summary>
	/// Summary description for SiteMapGenerator.
	/// </summary>
	public class SiteMapFeedGenerator 
	{ 
		private XmlTextWriter writer; 

		public SiteMapFeedGenerator (Stream stream , Encoding encoding)
		{ 
			writer = new XmlTextWriter(stream, encoding); 
			writer.Formatting = Formatting.Indented; 
		} 

		public SiteMapFeedGenerator (TextWriter w ) 
		{ 
			writer = new XmlTextWriter(w); 
			writer.Formatting = Formatting.Indented; 
		} 

		/// <summary> 
		/// Writes the beginning of the SiteMap document 
		/// </summary> 
		public void WriteStartDocument() 
		{ 
			writer.WriteStartDocument(); 
			writer.WriteStartElement("urlset"); 
			writer.WriteAttributeString("xmlns","http://www.google.com/schemas/sitemap/0.84"); 
		} 
		
		/// <summary> 
		/// Writes the end of the SiteMap document 
		/// </summary> 
		public void WriteEndDocument() 
		{ 
			writer.WriteEndElement(); 
			writer.WriteEndDocument(); 
		} 

		/// <summary> 
		/// Closes this stream and the underlying stream 
		/// </summary> 
		public void Close() 
		{ 
			writer.Flush(); 
			writer.Close(); 
		} 

		public void WriteItem (string link, DateTime publishedDate) 
		{ 
			writer.WriteStartElement("url"); 
			writer.WriteElementString("loc",link); 
			writer.WriteElementString("lastmod", TimeZone.CurrentTimeZone.ToUniversalTime(publishedDate).ToString("s") + "+00:00"); 
			writer.WriteElementString("changefreq","always"); 
			writer.WriteElementString("priority","0.8"); 
			writer.WriteEndElement(); 
		} 
	} 
}</pre>]]></content:encoded>
      <snippet:downloads>9</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=91d87908-fc63-49d1-a7bf-2136e31cebd0</guid>
      <title>Formatting DateTime to friendly post time string</title>
      <link>/PreviewSnippet.aspx?SnippetID=91d87908-fc63-49d1-a7bf-2136e31cebd0</link>
      <description>Formatting DateTime to friendly post time string [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 18 Mar 2007 13:36:06 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=91d87908-fc63-49d1-a7bf-2136e31cebd0#comments</comments>
      <category>053f6cad-6b5e-4dd3-9c3d-f1b2979f7fcb</category>
      <dc:title>Formatting DateTime to friendly post time string</dc:title>
      <dc:date>3/18/2007 1:36:06 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>    public class FormattingUtility
    {
        public static string ApproxHowLongAgo(DateTime dt)
        {
            TimeSpan ts = DateTime.Now.Subtract(dt);

            if (ts.TotalDays < 1)
            {
                if (ts.TotalSeconds > 3)
                {
                    if (ts.TotalSeconds > 55)
                    {
                        if (ts.TotalSeconds >= 120)
                        {
                            if (ts.TotalHours >= 1 && ts.TotalHours < 2 && ts.Minutes < 55)
                            {
                                if (ts.Minutes < 5)
                                    return "About an hour ago";
                                else
                                    return "Over an hour ago";
                            }
                            else if (ts.TotalHours < 2 && ts.Minutes >= 55)
                                return "Nearly 2 hours ago";
                            else if (ts.TotalHours > 1 && ts.Minutes < 55)
                            {
                                if (ts.Minutes < 5)
                                    return "About " + ts.TotalHours.ToString("#") + " hours ago";
                                else
                                    return "Over " + ts.TotalHours.ToString("#") + " hours ago";
                            }
                            else if (ts.TotalHours > 1 && ts.Minutes >= 55)
                                return "Nearly " + (ts.TotalHours + 1).ToString("#") + " hours ago";
                            else
                                return "About " + ts.TotalMinutes.ToString("#") + " minutes ago";
                        }
                        else
                            return "About a minute ago";
                    }
                    else
                        return ts.Seconds.ToString() + " seconds ago";
                }
                else
                    return "Just then";
            }
            else
                if (ts.TotalDays < 30)
                {
                    return "About " + ts.TotalDays.ToString("#") + " days ago";
                }
                else
                {
                    if (ts.TotalDays > 365)
                    {
                        return "More than one year ago";
                    }
                    else
                    {
                        return "About " + (ts.TotalDays / 30) + " months ago";
                    }
                }
        }
    }
</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=67df7b9b-212e-4ed3-937f-21676423a4c7</guid>
      <title>A .NET C# class for data encryption/decrytion</title>
      <link>/PreviewSnippet.aspx?SnippetID=67df7b9b-212e-4ed3-937f-21676423a4c7</link>
      <description>A .NET C# class for data encryption/decrytion [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 02 Sep 2005 21:09:27 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=67df7b9b-212e-4ed3-937f-21676423a4c7#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>A .NET C# class for data encryption/decrytion</dc:title>
      <dc:date>9/2/2005 9:09:27 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace FangHome_Crypto
{
	/// <summary>
	/// SymmCrypto is a wrapper of System.Security.Cryptography.SymmetricAlgorithm classes
	/// and simplifies the interface. It supports customized SymmetricAlgorithm as well.
	/// </summary>
	public class SymmCrypto
	{
		/// <remarks>
		/// Supported .Net intrinsic SymmetricAlgorithm classes.
		/// </remarks>
		public enum SymmProvEnum : int
		{
			DES, RC2, Rijndael
		}
		private SymmetricAlgorithm mobjCryptoService;
		/// <remarks>
		/// Constructor for using an intrinsic .Net SymmetricAlgorithm class.
		/// </remarks>
		public SymmCrypto(SymmProvEnum NetSelected)
		{
			switch (NetSelected)
			{
				case SymmProvEnum.DES:
					mobjCryptoService = new DESCryptoServiceProvider();
					break;
				case SymmProvEnum.RC2:
					mobjCryptoService = new RC2CryptoServiceProvider();
					break;
				case SymmProvEnum.Rijndael:
					mobjCryptoService = new RijndaelManaged();
					break;
			}
		}
		/// <remarks>
		/// Constructor for using a customized SymmetricAlgorithm class.
		/// </remarks>
		public SymmCrypto(SymmetricAlgorithm ServiceProvider)
		{
			mobjCryptoService = ServiceProvider;
		}
		private byte[] GetLegalKey(string Key)
		{
			string sTemp = Key;
			mobjCryptoService.GenerateKey();
			byte[] bytTemp = mobjCryptoService.Key;
			int KeyLength = bytTemp.Length;
			if (sTemp.Length > KeyLength)
				sTemp = sTemp.Substring(0, KeyLength);
			else if (sTemp.Length < KeyLength)
				sTemp = sTemp.PadRight(KeyLength, ' ');
			return ASCIIEncoding.ASCII.GetBytes(sTemp);
		}
		private byte[] GetLegalIV()
		{
			// The initial string of IV may be modified with any data you like
			string sTemp = "Â¾ÃˆÃ’ÃœÃ¦Â§Ã¼Ã©Ã¢Â»";
			mobjCryptoService.GenerateIV();
			byte[] bytTemp = mobjCryptoService.IV;
			int IVLength = bytTemp.Length;
			if (sTemp.Length > IVLength)
				sTemp = sTemp.Substring(0, IVLength);
			else if (sTemp.Length < IVLength)
				sTemp = sTemp.PadRight(IVLength, ' ');
			return ASCIIEncoding.ASCII.GetBytes(sTemp);
		}
		public string Encrypting(string Source, string Key)
		{
			// use UTF8 unicode conversion for two byte characters
			byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
			// create a MemoryStream so that the process can be done without I/O files
			System.IO.MemoryStream ms = new System.IO.MemoryStream();
			// set the private key
			mobjCryptoService.Key = GetLegalKey(Key);
			mobjCryptoService.IV = GetLegalIV();
			// create an Encryptor from the Provider Service instance
			ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
			// create Crypto Stream that transforms a stream using the encryption
			CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
			// write out encrypted content into MemoryStream
			cs.Write(bytIn, 0, bytIn.Length);
			cs.FlushFinalBlock();
			ms.Close();
			byte[] bytOut = ms.ToArray();
			// convert into Base64 so that the result can be used in xml
			return System.Convert.ToBase64String(bytOut);
		}
		public string Decrypting(string Source, string Key)
		{
			// convert from Base64 to binary
			byte[] bytIn = System.Convert.FromBase64String(Source);
			// create a MemoryStream with the input
			System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);
			// set the private key
			mobjCryptoService.Key = GetLegalKey(Key);
			mobjCryptoService.IV = GetLegalIV();
			// create a Decryptor from the Provider Service instance
			ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
			// create Crypto Stream that transforms a stream using the decryption
			CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
			
			// read out the result from the Crypto Stream
			System.IO.StreamReader sr = new System.IO.StreamReader( cs );
			return sr.ReadToEnd();
		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=14d898ad-a0ac-453d-a3d4-25582a77f48e</guid>
      <title>Read and write settings to an XML .config file without using ConfigurationSettings.AppSettings</title>
      <link>/PreviewSnippet.aspx?SnippetID=14d898ad-a0ac-453d-a3d4-25582a77f48e</link>
      <description>Read and write settings to an XML .config file without using ConfigurationSettings.AppSettings [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 05 Jun 2005 00:22:30 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=14d898ad-a0ac-453d-a3d4-25582a77f48e#comments</comments>
      <category>e5dc5661-427e-4d33-8be6-187bd2783223</category>
      <dc:title>Read and write settings to an XML .config file without using ConfigurationSettings.AppSettings</dc:title>
      <dc:date>6/5/2005 12:22:30 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>' Read and write settings to an XML .config file. Does not use 
' ConfigurationSettings.AppSettings since it's read-only and not 
' supported on .NET Compact Framework. 
'
' Uses same schema as app.config file. Example:
'
'	<configuration>
'		<appSettings>
'			<add key="Name" value="Live Oak" />
'			<add key="LogEvents" value="True" />
'		</appSettings>
'	</configuration>	
'
' The .config file name follows the standard naming convention, 
' it appends .config to the end of the assembly name. For example:
'
'	<appname.exe>.config
Imports System.Xml
Imports System.IO
Public Class Settings
	' internal members
	Private _list As New Hashtable
	Private _filePath As String = ""
	Private _autoWrite As Boolean = True
	Private _defaultValues As String()()
	' properties
	' specifies if the settings file is updated whenever a value 
	' is set, if false, you need to call Write to update the 
	' underlying settings file
	Public Property AutoWrite() As Boolean
		Get
			Return _autoWrite
		End Get
		Set(ByVal value As Boolean)
			_autoWrite = value
		End Set
	End Property
	' full path to settings file
	Public Property FilePath() As String
		Get
			' make sure the folder exist
			Dim folderPath As String = Path.GetDirectoryName(_filePath)
			If Directory.Exists(folderPath) = False Then
				Directory.CreateDirectory(folderPath)
			End If
			Return _filePath
		End Get
		Set(ByVal value As String)
			_filePath = value
		End Set
	End Property
	' ctor
	Public Sub New()
		' get full path to the file
		InitFilePath()
		' populate list with settings from file
		Read()
	End Sub
	' ctor that takes in default values
	Public Sub New(ByVal defaultValues As String()())
		' store default values, use later when populate list
		_defaultValues = defaultValues
		' get full path to file
		InitFilePath()
		' populate list with settings from file
		Read()
	End Sub

	' public methods
	' set setting value, update underlying file if AutoUpdate is true
	Public Sub SetValue(ByVal key As SettingKey, ByVal value As Object)
		' update internal list
		_list(key.ToString()) = value
		' update settings file
		If _autoWrite Then
			Write()
		End If
	End Sub
	' return specified setting	as string
	Public Function GetString(ByVal key As SettingKey) As String
		Dim result As Object = _list(key.ToString())
		If result Is Nothing Then
			Return ""
		Else
			Return result.ToString()
		End If
	End Function
	' return specified setting as integer
	Public Function GetInt(ByVal key As SettingKey) As Integer
		Dim result As String = GetString(key)
		If result = "" Then
			Return 0
		Else
			Return CInt(result)
		End If
	End Function
	' return specified setting as boolean
	Public Function GetBool(ByVal key As SettingKey) As Boolean
		Dim result As String = GetString(key)
		If result = "" Then
			Return False
		Else
			Return CBool(result)
		End If
	End Function
	' read settings file
	Public Sub Read()
		' first remove all items from list
		_list.Clear()
		' next, populate list with default values
		For i As Integer = 0 To (_defaultValues.GetLength(0)) - 1
			_list(_defaultValues(i)(0)) = _defaultValues(i)(1)
		Next
		' last, populate list with items from the file
		If File.Exists(Me.FilePath) Then
			Dim reader As New XmlTextReader(Me.FilePath)
			' go through file and read the xml file and 
			' populate internal list with 'add' elements
			While reader.Read()
				If reader.NodeType = XmlNodeType.Element And reader.Name = "add" Then
					_list(reader.GetAttribute("key")) = reader.GetAttribute("value")
				End If
			End While
			reader.Close()
		End If
	End Sub
	' write settings to the .config file
	Public Sub Write()
		Dim xmlWriter As New XmlTextWriter(Me.FilePath, Nothing)
		' header elements
		xmlWriter.Formatting = Formatting.Indented
		xmlWriter.WriteStartElement("configuration")
		xmlWriter.WriteStartElement("appSettings")
		' go through internal list and create the 'add' element for each item
		Dim enumerator As IDictionaryEnumerator = _list.GetEnumerator()
		While enumerator.MoveNext()
			xmlWriter.WriteStartElement("add")
			' key attribute
			xmlWriter.WriteStartAttribute("key", Nothing)
			xmlWriter.WriteString(enumerator.Key.ToString())
			xmlWriter.WriteEndAttribute()
			' value attribute
			xmlWriter.WriteStartAttribute("value", Nothing)
			xmlWriter.WriteString(enumerator.Value.ToString())
			xmlWriter.WriteEndAttribute()
			xmlWriter.WriteEndElement()
		End While
		' terminate header elements
		xmlWriter.WriteEndElement()
		xmlWriter.WriteEndElement()
		xmlWriter.Flush()
		xmlWriter.Close()
	End Sub
	' overwrite settings with default values
	Public Sub RestoreDefaults()
		Try
			' easiest way is to delete the file and
			' repopulate internal list with defaults
			File.Delete(FilePath)
			Read()
		Catch ex As Exception
			' an error occurred deleting the file
		End Try
	End Sub
	' internal methods
	' return full path to settings file
	Private Sub InitFilePath()
#If COMPACT_FRAMEWORK Then
		Me.FilePath = Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase & ".config"
#Else
		' create full path to the setting file, using Application.UserAppDataPath 
		' uses the company name, app name and assembly 4-part version, instead, 
		' just use the app name and short 2-part version (1.0 for example)
		' get folder location
		Dim ver As String() = Application.ProductVersion.Split("."c)
		Dim app As String = String.Format("{0}\{1}.{2}", _
		 Application.ProductName, ver(0), ver(1))
		Dim folder As String = Path.Combine( _
		 Environment.GetFolderPath( _
		 Environment.SpecialFolder.ApplicationData), _
		 app)
		' make sure folder exists
		If Directory.Exists(folder) = False Then
			Directory.CreateDirectory(folder)
		End If
		' return full path to the settings file
		Me.FilePath = Path.Combine(folder, _
		 Path.GetFileName(Application.ExecutablePath) & _
		 ".config")
#End If
	End Sub
End Class</pre>]]></content:encoded>
      <snippet:downloads>30</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=aee490b6-10d4-4e3c-b47b-25babe4f7169</guid>
      <title>Creating SmartTags for Word and Excel using VSTO 2005</title>
      <link>/PreviewSnippet.aspx?SnippetID=aee490b6-10d4-4e3c-b47b-25babe4f7169</link>
      <description>Creating SmartTags for Word and Excel using VSTO 2005 [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 04 Oct 2005 18:47:59 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=aee490b6-10d4-4e3c-b47b-25babe4f7169#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Creating SmartTags for Word and Excel using VSTO 2005</dc:title>
      <dc:date>10/4/2005 6:47:59 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
 
namespace SmartTagToActionPaneCS
{
    public partial class ThisDocument
    {
            ActionsPaneControl1 APC = new ActionsPaneControl1();
 
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
                  //Create the SmartTag
                  SmartTag ST = new SmartTag("http://MySmartTag/ST#SmartTagToActionsPane", SmartTag to ActionsPane");
              //define the terms to recognize
                  ST.Terms.Add("Hello");
                  //create Actions
                  Action AddtoActionsPaneAction = new Action("Add text to Actions Pane");
                  //add the Actions to your SmartTag
                  ST.Actions = new Action[] { AddtoActionsPaneAction };
                  //add the event handler 
                  AddtoActionsPaneAction.Click+=new ActionClickEventHandler(AddtoActionsPaneAction_Click);
 
                  //add the SmartTag to your Document
                  this.VstoSmartTags.Add(ST);
 
                  //Add the Actions Pane
                  this.ActionsPane.Controls.Add(APC);
        }
 
            void AddtoActionsPaneAction_Click(object sender, ActionEventArgs e)
            {
                  APC.label1.Text = e.Text;
            }
 
        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
        }
 
        #region VSTO Designer generated code
        /// <summary>
/// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisDocument_Startup);
            this.Shutdown += new System.EventHandler(ThisDocument_Shutdown);
        }
        #endregion
    }
}</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=6f1fd744-c735-40a4-865e-26416f98cf71</guid>
      <title>Ip adress to hostname</title>
      <link>/PreviewSnippet.aspx?SnippetID=6f1fd744-c735-40a4-865e-26416f98cf71</link>
      <description>Ip adress to hostname [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 11:24:56 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=6f1fd744-c735-40a4-865e-26416f98cf71#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>Ip adress to hostname</dc:title>
      <dc:date>4/9/2005 11:24:56 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Net; 
namespace Snippets
{
          class ConvertIpToHostName
          {
                  static void Main()           
                  {
                         IPHostEntry iph = Dns.Resolve("127.0.0.1");
                         string hostName = iph.HostName;

                         Console.WriteLine(hostName);
                   }
           }
}
</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=c60225d9-b863-44da-8245-29e756f7b2b7</guid>
      <title>The following code demonstrates how to write amd use a link list in C#</title>
      <link>/PreviewSnippet.aspx?SnippetID=c60225d9-b863-44da-8245-29e756f7b2b7</link>
      <description>The following code demonstrates how to write amd use a link list in C# [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 11:43:36 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=c60225d9-b863-44da-8245-29e756f7b2b7#comments</comments>
      <category>f8b47dd5-9f0a-4831-b7ad-ae8d5083baf3</category>
      <dc:title>The following code demonstrates how to write amd use a link list in C#</dc:title>
      <dc:date>4/16/2005 11:43:36 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
namespace CodeXchangeSamples
{
	class LinkList
	{
		public string Val;
		public object NextItem;
		[STAThread]
		static void Main(string[] args)
		{
			LinkList obList = new LinkList();
			obList.Val = "Head";
			
			LinkList obHead = obList;
			
			// Add 10 items to the list.
			for (int i = 0; i < 10; i++)
			{
				obList.NextItem = new LinkList();
				obList = (LinkList)obList.NextItem;
				obList.Val = i.ToString();
			}
			// Print the added items.
			while (obHead != null)
			{
				Console.WriteLine("Item: {0}", obHead.Val);
				obHead = (LinkList)obHead.NextItem;
			}
		}
	}
}
</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=2912deda-96f2-4a94-a118-2b5ef187ffaa</guid>
      <title>Drawing a Rectangle with rounded corners</title>
      <link>/PreviewSnippet.aspx?SnippetID=2912deda-96f2-4a94-a118-2b5ef187ffaa</link>
      <description>Drawing a Rectangle with rounded corners [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 22 Jun 2005 09:43:01 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=2912deda-96f2-4a94-a118-2b5ef187ffaa#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Drawing a Rectangle with rounded corners</dc:title>
      <dc:date>6/22/2005 9:43:01 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public static void DrawRoundedRectangle(Graphics g, Pen p, Color backColor, Rectangle rc, Size size)
{
   Point[] points = new Point[8];
   
   //prepare points for poligon
   points[0].X = rc.Left + size.Width / 2;
   points[0].Y = rc.Top + 1;
   points[1].X = rc.Right - size.Width / 2;
   points[1].Y = rc.Top + 1; 
   points[2].X = rc.Right;
   points[2].Y = rc.Top + size.Height / 2;
   points[3].X = rc.Right;
   points[3].Y = rc.Bottom - size.Height / 2; 
   points[4].X = rc.Right - size.Width / 2;
   points[4].Y = rc.Bottom;
   points[5].X = rc.Left  + size.Width / 2;
   points[5].Y = rc.Bottom; 
   points[6].X = rc.Left + 1;
   points[6].Y = rc.Bottom - size.Height / 2;
   points[7].X = rc.Left + 1;
   points[7].Y = rc.Top + size.Height / 2; 

   //prepare brush for background
   Brush fillBrush = new SolidBrush(backColor); 

   //draw side lines and circles in the corners
   g.DrawLine(p, rc.Left  + size.Width / 2, rc.Top,
    rc.Right - size.Width / 2, rc.Top);
   g.FillEllipse(fillBrush, rc.Right - size.Width, rc.Top,
    size.Width, size.Height);
   g.DrawEllipse(p, rc.Right - size.Width, rc.Top,
    size.Width, size.Height); 
   g.DrawLine(p, rc.Right, rc.Top + size.Height / 2,
    rc.Right, rc.Bottom - size.Height / 2);
   g.FillEllipse(fillBrush, rc.Right - size.Width, rc.Bottom - size.Height,
    size.Width, size.Height);
   g.DrawEllipse(p, rc.Right - size.Width, rc.Bottom - size.Height,
    size.Width, size.Height);
   
   g.DrawLine(p, rc.Right - size.Width / 2, rc.Bottom,
    rc.Left  + size.Width / 2, rc.Bottom);
   g.FillEllipse(fillBrush, rc.Left, rc.Bottom - size.Height, 
    size.Width, size.Height);
   g.DrawEllipse(p, rc.Left, rc.Bottom - size.Height, 
    size.Width, size.Height);
   
   g.DrawLine(p, rc.Left, rc.Bottom - size.Height / 2,
    rc.Left, rc.Top + size.Height / 2);
   g.FillEllipse(fillBrush, rc.Left, rc.Top,
    size.Width, size.Height);
   g.DrawEllipse(p, rc.Left, rc.Top,
    size.Width, size.Height);
   
   //fill the background and remove the internal arcs  
      g.FillPolygon(fillBrush, points);
   //dispose the brush
   fillBrush.Dispose();
  } 

//And this is how you'd use this method: 
Rectangle rc =  new Rectangle(10, 10, 100, 30); 
DrawRoundedRectangle(e.Graphics, new Pen(Color.Black), Color.CadetBlue, rc, new Size(8, 8));</pre>]]></content:encoded>
      <snippet:downloads>7</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=55087ea1-23ff-4479-b903-2b7ff926402c</guid>
      <title>Quick Shortcut to Lock Workstation</title>
      <link>/PreviewSnippet.aspx?SnippetID=55087ea1-23ff-4479-b903-2b7ff926402c</link>
      <description>Quick Shortcut to Lock Workstation [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 24 Apr 2005 12:40:33 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=55087ea1-23ff-4479-b903-2b7ff926402c#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Quick Shortcut to Lock Workstation</dc:title>
      <dc:date>4/24/2005 12:40:33 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace QuickLock
{
       class MyComputerLock
      {
            [DllImport("user32.dll")]
            public static extern void LockWorkStation();
             static void Main(String[] args)
            {
                     try
                          {
                                 LockWorkStation();
                          }
                          catch (Exception ee)
                         {
                               MessageBox.Show(ee.Message);
                          }
              }
       }
}
</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=81ecb4f6-ba97-47e3-bc0d-2d4a0ce56f0d</guid>
      <title>Working with EXIF  (Exchangeable Image Format) data stored in images</title>
      <link>/PreviewSnippet.aspx?SnippetID=81ecb4f6-ba97-47e3-bc0d-2d4a0ce56f0d</link>
      <description>Working with EXIF  (Exchangeable Image Format) data stored in images [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 05 Jun 2005 00:18:57 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=81ecb4f6-ba97-47e3-bc0d-2d4a0ce56f0d#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Working with EXIF  (Exchangeable Image Format) data stored in images</dc:title>
      <dc:date>6/5/2005 12:18:57 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>' Works with EXIF (Exchangeable Image Format) data that is stored in photo
' images. The Copy method copies EXIF info from one image into another; the 
' thumbnail info is not copied since it's most likely incorrect. The Read method 
' reads the EXIF values in the image and exposes the info through properties.
'
' Some settings are stored in APEX (Additive System of Photographic Exposure) 
' units and need to be converted. Extra care is taken when reading the information 
' since can't ensure all cameras will store the data in the same format. The EXIF 
' format and other useful information (such as sample images) can be found at 
' www.exif.org.
Imports System.Drawing.Imaging
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Exif
	' exif tags
	Private Enum ExifTag
		Make = &H10F
		Model = &H110
		UserComment = &H9286
		ExposureTime = &H829A
		Aperture = &H829D
		ExposureTimeApex = &H9201
		ApertureApex = &H9202
		Iso = &H8827
		Flash = &H9209
		ThumbnailFormat = &H201
		ThumbnailLength = &H202
	End Enum
	' tag categories
	Private Enum ExifCategory
		Thumbnail = 1
	End Enum
	' internal members
	Private _make As String
	Private _model As String
	Private _userComment As String
	Private _exposureTime As Single
	Private _aperture As Single
	Private _iso As Integer
	Private _flash As Boolean
	' properties
	Public ReadOnly Property Make() As String
		Get
			Return _make
		End Get
	End Property
	Public ReadOnly Property Model() As String
		Get
			Return _model
		End Get
	End Property
	Public ReadOnly Property UserComment() As String
		Get
			Return _userComment
		End Get
	End Property
	Public ReadOnly Property ExposureTime() As Single
		Get
			Return _exposureTime
		End Get
	End Property
	Public ReadOnly Property Aperture() As Single
		Get
			Return _aperture
		End Get
	End Property
	Public ReadOnly Property Iso() As Integer
		Get
			Return _iso
		End Get
	End Property
	Public ReadOnly Property Flash() As Boolean
		Get
			Return _flash
		End Get
	End Property
	' ctor
	Public Sub New()
		Clear()
	End Sub
	' public methods
	' copy the exif info from the source image to the target image
	Public Shared Sub Copy(ByVal sourceImage As Bitmap, ByVal targetImage As Bitmap)
		' return right away if there are not any exif tags to copy
		If ContainsProperties(sourceImage) = False Then Return
		Try
			' loop through the list and copy to the target image
			' skip any thumbnail-related tags
			For Each item As PropertyItem In sourceImage.PropertyItems
				If item.Type <> ExifCategory.Thumbnail AndAlso _
				 item.Id <> ExifTag.ThumbnailFormat AndAlso _
				 item.Id <> ExifTag.ThumbnailLength Then
					targetImage.SetPropertyItem(item)
				End If
			Next
		Catch ex As Exception
			' a problem copying the exif info
		End Try
	End Sub
	' read the exif info for the specified image
	Public Sub Read(ByVal image As Bitmap)
		' init values
		Clear()
		' return if the image does not contain any exif tags
		If ContainsProperties(image) = False Then Return
		' loop through the list and pull out the tags we want to store, some
		' cameras store values in APEX format which neeeds to be converted
		For Each item As PropertyItem In image.PropertyItems
			Select Case item.Id
				Case ExifTag.Make
					_make = GetAscii(item.Value)
				Case ExifTag.Model
					_model = GetAscii(item.Value)
				Case ExifTag.UserComment
					_userComment = GetAscii(item.Value)
				Case ExifTag.ExposureTime
					_exposureTime = GetRational(item.Value)
				Case ExifTag.ExposureTimeApex
					Dim value As Single = GetRational(item.Value)
					_exposureTime = CSng(1 / Math.Pow(2, value))
				Case ExifTag.Aperture
					_aperture = GetRational(item.Value)
				Case ExifTag.ApertureApex
					Dim value As Single = GetRational(item.Value)
					_aperture = CSng(Math.Pow(2, value / 2))
				Case ExifTag.Iso
					_iso = GetShort(item.Value)
				Case ExifTag.Flash
					_flash = GetBoolean(item.Value)
			End Select
		Next
	End Sub
	' internal methods
	' some photos can have an empty PropertyItems collection and 
	' trying to check this for null throws an exception, wrap this
	' in a try / catch block and return boolean result
	Private Shared Function ContainsProperties(ByVal image As Bitmap) As Boolean
		Try
			If image.PropertyItems Is Nothing Then Return False
			Return True
		Catch ex As Exception
			Return False
		End Try
	End Function
	' init exif values
	Private Sub Clear()
		_make = ""
		_model = ""
		_userComment = ""
		_exposureTime = 0.0F
		_aperture = 0.0F
		_iso = 0
		_flash = False
	End Sub
	' return string from value, all cameras don't store the data the same
	' so need to be careful and make sure we only pull out the string data
	Private Function GetAscii(ByVal bits As Byte()) As String
		Try
			' the regular expression removes anything that is not a letter or 
			' number \w, white space \s or punctuation \p{{P}
			Dim data As String = ASCIIEncoding.ASCII.GetString( _
			 bits, 0, bits.Length - 1).Trim()
			Return Regex.Replace(data, "[^\w\s\p{P}]", "")
		Catch ex As Exception
			Return ""
		End Try
	End Function
	' stores values in 8 bytes, the numerator in the first 4 bytes
	' and the denominator in the last 4 bytes
	Private Function GetRational(ByVal bits As Byte()) As Single
		Try
			Return CSng( _
			 BitConverter.ToInt32(bits, 0) / _
			 BitConverter.ToInt32(bits, 4))
		Catch ex As Exception
			Return 0.0F
		End Try
	End Function
	' stores value in 2 bytes
	Private Function GetShort(ByVal bits As Byte()) As Integer
		Try
			Return CInt(BitConverter.ToInt16(bits, 0))
		Catch ex As Exception
			Return 0
		End Try
	End Function
	' stores value in 2 bytes
	Private Function GetBoolean(ByVal bits As Byte()) As Boolean
		Try
			Return CBool(BitConverter.ToInt16(bits, 0))
		Catch ex As Exception
			Return False
		End Try
	End Function
End Class</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=3324a51d-1fa9-461c-b318-2e5801061f9b</guid>
      <title>Build a Custom .NET "EVAL" Provider</title>
      <link>/PreviewSnippet.aspx?SnippetID=3324a51d-1fa9-461c-b318-2e5801061f9b</link>
      <description>Build a Custom .NET "EVAL" Provider [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 09:57:59 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=3324a51d-1fa9-461c-b318-2e5801061f9b#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Build a Custom .NET "EVAL" Provider</dc:title>
      <dc:date>4/16/2005 9:57:59 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports Microsoft.VisualBasic
Imports System
Imports System.Text
Imports System.CodeDom.Compiler
Imports System.Reflection
Imports System.IO
Namespace PAB.Util
    Public Class EvalProvider
        Public Function Eval(ByVal vbCode As String) As Object
            Dim c As VBCodeProvider = New VBCodeProvider
            Dim icc As ICodeCompiler = c.CreateCompiler()
            Dim cp As CompilerParameters = New CompilerParameters
            cp.ReferencedAssemblies.Add("system.dll")
            cp.ReferencedAssemblies.Add("system.xml.dll")
            cp.ReferencedAssemblies.Add("system.data.dll")
            ' Sample code for adding your own referenced assemblies
            'cp.ReferencedAssemblies.Add("c:\yourProjectDir\bin\YourBaseClass.dll")
            'cp.ReferencedAssemblies.Add("YourBaseclass.dll")
            cp.CompilerOptions = "/t:library"
            cp.GenerateInMemory = True
            Dim sb As StringBuilder = New StringBuilder("")
            sb.Append("Imports System" & vbCrLf)
            sb.Append("Imports System.Xml" & vbCrLf)
            sb.Append("Imports System.Data" & vbCrLf)
            sb.Append("Imports System.Data.SqlClient" & vbCrLf)
            sb.Append("Namespace PAB  " & vbCrLf)
            sb.Append("Class PABLib " & vbCrLf)
            sb.Append("public function  EvalCode() as Object " & vbCrLf)
            'sb.Append("YourNamespace.YourBaseClass thisObject = New YourNamespace.YourBaseClass()")
            sb.Append(vbCode & vbCrLf)
            sb.Append("End Function " & vbCrLf)
            sb.Append("End Class " & vbCrLf)
            sb.Append("End Namespace" & vbCrLf)
            Debug.WriteLine(sb.ToString()) ' look at this to debug your eval string
            Dim cr As CompilerResults = icc.CompileAssemblyFromSource(cp, sb.ToString())
            Dim a As System.Reflection.Assembly = cr.CompiledAssembly
            Dim o As Object
            Dim mi As MethodInfo
            o = a.CreateInstance("PAB.PABLib")
            Dim t As Type = o.GetType()
            mi = t.GetMethod("EvalCode")
            Dim s As Object
            s = mi.Invoke(o, Nothing)
            Return s
        End Function
    End Class
End Namespace</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=cab7c7bc-ef65-40a6-8aee-2fdbe7770fd6</guid>
      <title>how to launch the systems default email client</title>
      <link>/PreviewSnippet.aspx?SnippetID=cab7c7bc-ef65-40a6-8aee-2fdbe7770fd6</link>
      <description>how to launch the systems default email client [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:51:34 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=cab7c7bc-ef65-40a6-8aee-2fdbe7770fd6#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>how to launch the systems default email client</dc:title>
      <dc:date>4/9/2005 1:51:34 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System.Text;using System.Diagnostics;
string toEmail = "me@server.com";
string subject = "This is a test Subject";string body = "This is a test email message";
string message = string.Format("mailto:{0}?subject={1}&body={2}",     toEmail, subject, body);
Process.Start(message);
</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=aea6cbda-32c4-4abc-b30b-313b2e747383</guid>
      <title>Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format</title>
      <link>/PreviewSnippet.aspx?SnippetID=aea6cbda-32c4-4abc-b30b-313b2e747383</link>
      <description>Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 12 May 2005 19:03:39 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=aea6cbda-32c4-4abc-b30b-313b2e747383#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format</dc:title>
      <dc:date>5/12/2005 7:03:39 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>private string FormatSize (double fileSize)
{
	if (fileSize < 1024)
		return String.Format("{0:N0} B", fileSize);
	else if (fileSize < 1024*1024)
		return String.Format("{0:N2} KB", fileSize/1024);
	else
		return String.Format("{0:N2} MB", fileSize/(1024*1024));
}</pre>]]></content:encoded>
      <snippet:downloads>204</snippet:downloads>
      <snippet:rating>5</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a4136f77-ee86-496b-8524-3442d3480843</guid>
      <title>Creating a dynamic asssembly using System.CodeDOM</title>
      <link>/PreviewSnippet.aspx?SnippetID=a4136f77-ee86-496b-8524-3442d3480843</link>
      <description>Creating a dynamic asssembly using System.CodeDOM [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 09:37:48 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a4136f77-ee86-496b-8524-3442d3480843#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Creating a dynamic asssembly using System.CodeDOM</dc:title>
      <dc:date>4/6/2005 9:37:48 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public static Assembly CreateAssembly(string[] referencedAssemblies, string source)
{
// compile the code
CSharpCodeProvider prov = new CSharpCodeProvider();
ICodeCompiler comp = prov.CreateCompiler();CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
// setup references
p.ReferencedAssemblies.Add("System.dll");
if(referencedAssemblies != null){
     foreach(string assemblyName in referencedAssemblies)    {
        p.ReferencedAssemblies.Add(assemblyName);
    }
}
CompilerResults res = comp.CompileAssemblyFromSource(p, source);
return res.CompiledAssembly;
}
//And a quick code snippet showing how the above method may be used. 
StringBuilder sourceCode = new StringBuilder();
// create C# code for the EntityLoader with string Builder (omitted)
Assembly assembly = AssemblyGenerator.CreateAssembly(new string[] {"System.Data.dll" }, sourceCode.ToString());
EntityLoader loader = (EntityLoader) assembly.CreateInstance(assembly.GetTypes()[0].FullName);
return loader;
</pre>]]></content:encoded>
      <snippet:downloads>9</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=0adf7cd7-de8c-4bb6-b3c9-34ed37498e04</guid>
      <title>How do I load an image from a URI address?</title>
      <link>/PreviewSnippet.aspx?SnippetID=0adf7cd7-de8c-4bb6-b3c9-34ed37498e04</link>
      <description>How do I load an image from a URI address? [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 18 Apr 2005 08:59:22 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=0adf7cd7-de8c-4bb6-b3c9-34ed37498e04#comments</comments>
      <category>aeb15495-509d-43ee-9bb5-f59c47bca5ff</category>
      <dc:title>How do I load an image from a URI address?</dc:title>
      <dc:date>4/18/2005 8:59:22 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Function GetImageFromURL(ByVal url As String) As Byte() 
    Dim wr As HttpWebRequest = _ 
       DirectCast(WebRequest.Create(url), HttpWebRequest) 
    Dim wresponse As HttpWebResponse = _ 
       DirectCast(wr.GetResponse, HttpWebResponse) 
    Dim responseStream As Stream = wresponse.GetResponseStream 
    Dim br As BinaryReader = New BinaryReader(responseStream) 
    Dim bytesize As Long = wresponse.ContentLength 
    Return br.ReadBytes(bytesize) 
End Function 
To use the above function:
Dim img As New Bitmap(New IO.MemoryStream(GetImageFromURL("http://msdn.microsoft.com/longhorn/art/codenameLonghorn.JPG"))) 
Me.BackgroundImage = img 
</pre>]]></content:encoded>
      <snippet:downloads>9</snippet:downloads>
      <snippet:rating>5</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=2ece4971-37c1-4140-8d85-355528963aac</guid>
      <title>Simple web service example. When invoked it returns the string "Hello World". </title>
      <link>/PreviewSnippet.aspx?SnippetID=2ece4971-37c1-4140-8d85-355528963aac</link>
      <description>Simple web service example. When invoked it returns the string "Hello World".  [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:30:48 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=2ece4971-37c1-4140-8d85-355528963aac#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Simple web service example. When invoked it returns the string "Hello World". </dc:title>
      <dc:date>4/15/2005 6:30:48 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre><%@ WebService Language="c#" Class="WebServ1.Service1" %>
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
namespace WebServ1
{
	/// <summary>
	/// Summary description for Service1.
	/// </summary>
	public class Service1 : System.Web.Services.WebService
	{
		public Service1()
		{
			//CODEGEN: This call is required by the ASP.NET Web Services Designer
			InitializeComponent();
		}
		#region Component Designer generated code
		
		//Required by the Web Services Designer 
		private IContainer components = null;
				
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
		}
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if(disposing && components != null)
			{
				components.Dispose();
			}
			base.Dispose(disposing);		
		}
		
		#endregion
		// WEB SERVICE EXAMPLE
		// The HelloWorld() example service returns the string Hello World
		// To build, uncomment the following lines then save and build the project
		// To test this web service, press F5
		[WebMethod]
		public string HelloWorld()
		{
			return "Hello World";
		}
	}
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=bc4d9049-c775-4d2a-b806-36335f792bbf</guid>
      <title>Detecting the Web Server system up time</title>
      <link>/PreviewSnippet.aspx?SnippetID=bc4d9049-c775-4d2a-b806-36335f792bbf</link>
      <description>Detecting the Web Server system up time [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 17 Sep 2005 04:18:57 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=bc4d9049-c775-4d2a-b806-36335f792bbf#comments</comments>
      <category>5c13f9b1-b6fb-4509-aa9f-3281a114a487</category>
      <dc:title>Detecting the Web Server system up time</dc:title>
      <dc:date>9/17/2005 4:18:57 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>	public class SystemUptime : WebControl
	{
		protected override void Render (HtmlTextWriter writer)
		{
			TimeSpan ts = TimeSpan.FromMilliseconds (Environment.TickCount);
			writer.Write("System {0} has been up for {1} days {2} hours , {3} minutes and {4} seconds",
				Environment.MachineName ,
				ts.Days ,
				ts.Hours , 
				ts.Minutes ,
				ts.Seconds);
		}
	}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=d3fb50d9-c5af-4e46-98c4-3722f92ba804</guid>
      <title>App path in VB.net</title>
      <link>/PreviewSnippet.aspx?SnippetID=d3fb50d9-c5af-4e46-98c4-3722f92ba804</link>
      <description>App path in VB.net [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:36:46 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=d3fb50d9-c5af-4e46-98c4-3722f92ba804#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>App path in VB.net</dc:title>
      <dc:date>4/6/2005 1:36:46 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Module Module1 
Sub Main()
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory())
End Sub
End Module
</pre>]]></content:encoded>
      <snippet:downloads>13</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=139c7c19-7452-41f5-a82d-39fcea401335</guid>
      <title>Grabbing a remote web page in C#</title>
      <link>/PreviewSnippet.aspx?SnippetID=139c7c19-7452-41f5-a82d-39fcea401335</link>
      <description>Grabbing a remote web page in C# [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 14:25:09 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=139c7c19-7452-41f5-a82d-39fcea401335#comments</comments>
      <category>aeb15495-509d-43ee-9bb5-f59c47bca5ff</category>
      <dc:title>Grabbing a remote web page in C#</dc:title>
      <dc:date>4/16/2005 2:25:09 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System.Net;
using System.Text
private string GetWebPage(string url)
{
  try
  {
    HttpWebRequest webRequest = 
      (HttpWebRequest)WebRequest.Create(url);
    webRequest.Timeout = 6000;
    HttpWebResponse webResponse = 
      (HttpWebResponse)webRequest.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    string responseEncoding = webResponse.ContentEncoding.Trim();
    if (responseEncoding.Length == 0)
      responseEncoding="us-ascii";
    StreamReader responseReader = new StreamReader(responseStream, 
      System.Text.Encoding.GetEncoding(responseEncoding));
    return(responseReader.ReadToEnd());
  }
  catch
  {
    return(string.Empty);
  }
}</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>5</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a6ec66a4-cce1-4c4c-a7c3-3df5cb6fb622</guid>
      <title>Change Desktop screen resolution using Win32 API</title>
      <link>/PreviewSnippet.aspx?SnippetID=a6ec66a4-cce1-4c4c-a7c3-3df5cb6fb622</link>
      <description>Change Desktop screen resolution using Win32 API [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 14 Jun 2005 09:02:57 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a6ec66a4-cce1-4c4c-a7c3-3df5cb6fb622#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Change Desktop screen resolution using Win32 API</dc:title>
      <dc:date>6/14/2005 9:02:57 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CodeXchange.Samples.Win32
{
	[StructLayout(LayoutKind.Sequential)]
	public struct DEVMODE1 
	{
		[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)] public string dmDeviceName;
		public short  dmSpecVersion;
		public short  dmDriverVersion;
		public short  dmSize;
		public short  dmDriverExtra;
		public int    dmFields;
		public short dmOrientation;
		public short dmPaperSize;
		public short dmPaperLength;
		public short dmPaperWidth;
		public short dmScale;
		public short dmCopies;
		public short dmDefaultSource;
		public short dmPrintQuality;
		public short dmColor;
		public short dmDuplex;
		public short dmYResolution;
		public short dmTTOption;
		public short dmCollate;
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName;
		public short dmLogPixels;
		public short dmBitsPerPel;
		public int   dmPelsWidth;
		public int   dmPelsHeight;
		public int   dmDisplayFlags;
		public int   dmDisplayFrequency;
		public int   dmICMMethod;
		public int   dmICMIntent;
		public int   dmMediaType;
		public int   dmDitherType;
		public int   dmReserved1;
		public int   dmReserved2;
		public int   dmPanningWidth;
		public int   dmPanningHeight;
	};
	class User_32
	{
		[DllImport("user32.dll")]
		public static extern int EnumDisplaySettings (string deviceName, int modeNum, ref DEVMODE1 devMode );         
		[DllImport("user32.dll")]
		public static extern int ChangeDisplaySettings(ref DEVMODE1 devMode, int flags);
		public const int ENUM_CURRENT_SETTINGS = -1;
		public const int CDS_UPDATEREGISTRY = 0x01;
		public const int CDS_TEST = 0x02;
		public const int DISP_CHANGE_SUCCESSFUL = 0;
		public const int DISP_CHANGE_RESTART = 1;
		public const int DISP_CHANGE_FAILED = -1;
	}
	public class CResolution
	{
		int m_Height = 0;
		int m_Width  = 0;
		public CResolution (int height,int width)
		{
			m_Height = height;
			m_Width	 = width;
		}
		public CResolution () : 
			this (
			Screen.PrimaryScreen.Bounds.Height , 
			Screen.PrimaryScreen.Bounds.Width)
		{
			
		}
		public void Restore ()
		{
			ChangeResolution (m_Height , m_Width);
		}
		public void ChangeResolution (int a,int b)
		{
			Screen screen = Screen.PrimaryScreen;
			
			int iWidth =a;
			int iHeight =b;
			DEVMODE1 dm = new DEVMODE1();
			dm.dmDeviceName = new String (new char[32]);
			dm.dmFormName = new String (new char[32]);
			dm.dmSize = (short)Marshal.SizeOf (dm);
			if (0 != User_32.EnumDisplaySettings (null, User_32.ENUM_CURRENT_SETTINGS, ref dm))
			{
				dm.dmPelsWidth = iWidth;
				dm.dmPelsHeight = iHeight;
				int iRet = User_32.ChangeDisplaySettings (ref dm, User_32.CDS_TEST);
				if (iRet == User_32.DISP_CHANGE_FAILED)
				{
					MessageBox.Show("Description: Unable To Process Your Request. Sorry For This Inconvenience.","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
				}
				else
				{
					iRet = User_32.ChangeDisplaySettings (ref dm, User_32.CDS_UPDATEREGISTRY);
					switch (iRet) 
					{
						case User_32.DISP_CHANGE_SUCCESSFUL:
						{
							break;
						}
						case User_32.DISP_CHANGE_RESTART:
						{
							
							MessageBox.Show("Description: You Need To Reboot For The Change To Happen.\n If You Feel Any Problem After Rebooting Your Machine\nThen Try To Change Resolution In Safe Mode.","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
							break;
						}
						default:
						{
							
							MessageBox.Show("Description: Failed To Change The Resolution.","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
							break;
						}
					}
				}				
			}
		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=98496c24-7f88-4a90-9dd3-3e30f1514bfb</guid>
      <title>Determining if an assembly was built for debug or release</title>
      <link>/PreviewSnippet.aspx?SnippetID=98496c24-7f88-4a90-9dd3-3e30f1514bfb</link>
      <description>Determining if an assembly was built for debug or release [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 20 May 2005 21:24:05 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=98496c24-7f88-4a90-9dd3-3e30f1514bfb#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Determining if an assembly was built for debug or release</dc:title>
      <dc:date>5/20/2005 9:24:05 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Dim assm As Reflection.Assembly = Reflection.Assembly.LoadFrom(Application.ExecutablePath)
Dim found As Boolean = assm.GetCustomAttributes(GetType(DebuggableAttribute), False).Length > 0
Me.Text = "Assembly is " & IIf(found, "debug", "release") </pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=81ac17dc-45da-498c-acae-3f49094d61d0</guid>
      <title>Sending non US-ASCII emails</title>
      <link>/PreviewSnippet.aspx?SnippetID=81ac17dc-45da-498c-acae-3f49094d61d0</link>
      <description>Sending non US-ASCII emails [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 11:33:24 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=81ac17dc-45da-498c-acae-3f49094d61d0#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>Sending non US-ASCII emails</dc:title>
      <dc:date>4/9/2005 11:33:24 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Dim mail As New MailMessage()
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "this is a test email."
mail.Body = "Some Chinese characters or text goes here"
mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312") 'set the proper character set here
SmtpMail.SmtpServer = "localhost" 'your real server goes here
SmtpMail.Send(mail)</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=61afeda6-db6d-4c2f-9b31-4041fa55ebd6</guid>
      <title>File selector UITypeEditor</title>
      <link>/PreviewSnippet.aspx?SnippetID=61afeda6-db6d-4c2f-9b31-4041fa55ebd6</link>
      <description>File selector UITypeEditor [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 02 Jan 2006 07:18:19 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=61afeda6-db6d-4c2f-9b31-4041fa55ebd6#comments</comments>
      <category>03af4393-69f0-4f95-8d4c-60efe508c790</category>
      <dc:title>File selector UITypeEditor</dc:title>
      <dc:date>1/2/2006 7:18:19 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public class FileEditor : UITypeEditor {
    private OpenFileDialog openFileDialog;
    public override object EditValue(ITypeDescriptorContext context,  IServiceProvider  provider, object value) {
        if (openFileDialog == null){
            openFileDialog = new OpenFileDialog();
        }
        openFileDialog.DefaultExt = "dat";
        openFileDialog.Multiselect = false;
        openFileDialog.Title = "Select Attachment";
        openFileDialog.CheckFileExists = true;
        openFileDialog.CheckPathExists = true;
        if (openFileDialog.ShowDialog() == DialogResult.OK)
            return new FileName(openFileDialog.FileName);
        return null;
    }
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
        return UITypeEditorEditStyle.Modal;
    }
}</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=c4d42837-647c-4219-8b48-49c81011bb1d</guid>
      <title>Display the available mac addresses</title>
      <link>/PreviewSnippet.aspx?SnippetID=c4d42837-647c-4219-8b48-49c81011bb1d</link>
      <description>Display the available mac addresses [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:59:00 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=c4d42837-647c-4219-8b48-49c81011bb1d#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>Display the available mac addresses</dc:title>
      <dc:date>4/9/2005 1:59:00 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Private Sub Form_Load()
'add a reference to the Microsoft WMI Scripting 1.2 library
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_NetworkAdapter", , 48)
For Each objItem In colItems
Form1.Print "MACAddress: " & objItem.MACAddress
'MsgBox ("MACAddress: " & objItem.MACAddress)
Next
End Sub</pre>]]></content:encoded>
      <snippet:downloads>7</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=b3a0edfd-08e7-4b97-8141-49d6085c302c</guid>
      <title>fahrenheit to celsius conversion</title>
      <link>/PreviewSnippet.aspx?SnippetID=b3a0edfd-08e7-4b97-8141-49d6085c302c</link>
      <description>fahrenheit to celsius conversion [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:54:42 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=b3a0edfd-08e7-4b97-8141-49d6085c302c#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>fahrenheit to celsius conversion</dc:title>
      <dc:date>4/9/2005 1:54:42 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System; 
namespace csharp
{
   class Class1
   {
        static void Main(string[] args)
   {
   double celsius;
   double fahr = 75;
   celsius = ((0.5/0.9) * (fahr - 32));
   Console.WriteLine(celsius);
   }
 }
}
</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=03528785-fc64-4b30-95c5-4b476ea23fb8</guid>
      <title>How to send a NET SEND message in C#/.NET</title>
      <link>/PreviewSnippet.aspx?SnippetID=03528785-fc64-4b30-95c5-4b476ea23fb8</link>
      <description>How to send a NET SEND message in C#/.NET [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 14:24:01 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=03528785-fc64-4b30-95c5-4b476ea23fb8#comments</comments>
      <category>edde3ea1-24a6-4cb0-8446-ab91e1800116</category>
      <dc:title>How to send a NET SEND message in C#/.NET</dc:title>
      <dc:date>4/16/2005 2:24:01 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Runtime.InteropServices;
using System.IO;
namespace GruikSoft.Net
{
    /// <summary>
    /// Contains utility methods to send messages like the NET SEND command does.
    /// </summary>
    public class NetSend
    {
        [DllImport("kernel32.dll")]
        internal static extern IntPtr CreateFile(string name, int desiredAccess, int shareMode, IntPtr securityAttributes,
            int creationDisposition, int dwFlagsAndAttributes, IntPtr templateFile);
    
        /// <summary>
        /// Sends a NET SEND message.
        /// </summary>
        /// <param name="destination">Computer name to send the message to</param>
        /// <param name="from">Sender's name. Technically, you can put anything in here although it is better to put 
        /// your name or nickname.</param>
        /// <param name="to">Recipient's name. Same as for the sender, you can put whatever you want</param>
        /// <param name="message">Contents of the message.</param>
        public static void SendMessage(string destination, string from, string to, string message)
        {
            IntPtr handle = CreateFile(string.Format(@"\\{0}\mailslot\messngr", destination),
                (int) FileAccess.Write, (int) FileShare.Read, IntPtr.Zero, (int) FileMode.Open, 0, IntPtr.Zero);
            FileStream fs = new FileStream(handle, FileAccess.Write);
            try
            {
                string s = string.Format("{0}\0{1}\0{2}\0\0", from, to, message);
                byte[] msg = System.Text.Encoding.ASCII.GetBytes(s);
                fs.Write(msg, 0, msg.Length);
            }
            finally
            {
                fs.Close();    
            }
        }
    }
}
</pre>]]></content:encoded>
      <snippet:downloads>11</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a8b53c31-3187-4abe-8578-4be31020ea70</guid>
      <title>Capturing KeyPress</title>
      <link>/PreviewSnippet.aspx?SnippetID=a8b53c31-3187-4abe-8578-4be31020ea70</link>
      <description>Capturing KeyPress [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 17 Apr 2005 10:45:58 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a8b53c31-3187-4abe-8578-4be31020ea70#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Capturing KeyPress</dc:title>
      <dc:date>4/17/2005 10:45:58 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
  if( keyData == Keys.Enter )
  {
    MessageBox.Show( "Enter pressed!" );
    return true;
  }
  return base.ProcessCmdKey( ref msg, keyData );
} </pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=5f5a3844-4bd4-448c-b9a2-4d47449f50cd</guid>
      <title>This is a simple way to create a database connection for MS ACCESS</title>
      <link>/PreviewSnippet.aspx?SnippetID=5f5a3844-4bd4-448c-b9a2-4d47449f50cd</link>
      <description>This is a simple way to create a database connection for MS ACCESS [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:37:00 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=5f5a3844-4bd4-448c-b9a2-4d47449f50cd#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>This is a simple way to create a database connection for MS ACCESS</dc:title>
      <dc:date>4/15/2005 6:37:00 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.Data
Imports System.Data.OleDb
  Dim myConnection As OleDbConnection
  
  myConnection = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0; DATA Source=YOUR_ABSOLUTE_PATH\database\test.mdb")
  myConnection.Open()
  myConnection.Close()
Connection Opened!!!</pre>]]></content:encoded>
      <snippet:downloads>37</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ddd388bd-d96a-473e-9c36-4d5df25f866d</guid>
      <title>CSV parser for C#</title>
      <link>/PreviewSnippet.aspx?SnippetID=ddd388bd-d96a-473e-9c36-4d5df25f866d</link>
      <description>CSV parser for C# [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 22 Apr 2005 11:34:15 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ddd388bd-d96a-473e-9c36-4d5df25f866d#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>CSV parser for C#</dc:title>
      <dc:date>4/22/2005 11:34:15 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Collections;
using System.IO;
using System.Text;
namespace JouniHeikniemi.Tools.Text {
  /// <summary>
  /// A data-reader style interface for reading CSV files.
  /// </summary>
  public class CSVReader : IDisposable {
    #region Private variables
    private Stream stream;
    private StreamReader reader;
    #endregion
    /// <summary>
    /// Create a new reader for the given stream.
    /// </summary>
    /// <param name="s">The stream to read the CSV from.</param>
    public CSVReader(Stream s) : this(s, null) { }
    /// <summary>
    /// Create a new reader for the given stream and encoding.
    /// </summary>
    /// <param name="s">The stream to read the CSV from.</param>
    /// <param name="enc">The encoding used.</param>
    public CSVReader(Stream s, Encoding enc) {
      this.stream = s;
      if (!s.CanRead) {
        throw new CSVReaderException("Could not read the given CSV stream!");
      }
      reader = (enc != null) ? new StreamReader(s, enc) : new StreamReader(s);
    }
    /// <summary>
    /// Creates a new reader for the given text file path.
    /// </summary>
    /// <param name="filename">The name of the file to be read.</param>
    public CSVReader(string filename) : this(filename, null) { }
    /// <summary>
    /// Creates a new reader for the given text file path and encoding.
    /// </summary>
    /// <param name="filename">The name of the file to be read.</param>
    /// <param name="enc">The encoding used.</param>
    public CSVReader(string filename, Encoding enc) 
      : this(new FileStream(filename, FileMode.Open), enc) { }
    /// <summary>
    /// Returns the fields for the next row of CSV data (or null if at eof)
    /// </summary>
    /// <returns>A string array of fields or null if at the end of file.</returns>
    public string[] GetCSVLine() {
      string data = reader.ReadLine();
      if (data == null) return null;
      if (data.Length == 0) return new string[0];
      
      ArrayList result = new ArrayList();
      ParseCSVFields(result, data);
      
      return (string[])result.ToArray(typeof(string));
    }
    // Parses the CSV fields and pushes the fields into the result arraylist
    private void ParseCSVFields(ArrayList result, string data) {
      int pos = -1;
      while (pos < data.Length)
        result.Add(ParseCSVField(data, ref pos));
    }
    // Parses the field at the given position of the data, modified pos to match
    // the first unparsed position and returns the parsed field
    private string ParseCSVField(string data, ref int startSeparatorPosition) {
      if (startSeparatorPosition == data.Length-1) {
        startSeparatorPosition++;
        // The last field is empty
        return "";
      }
      int fromPos = startSeparatorPosition + 1;
      // Determine if this is a quoted field
      if (data[fromPos] == '"') {
        // If we're at the end of the string, let's consider this a field that
        // only contains the quote
        if (fromPos == data.Length-1) {
          fromPos++;
          return "\"";
        }
        // Otherwise, return a string of appropriate length with double quotes collapsed
        // Note that FSQ returns data.Length if no single quote was found
        int nextSingleQuote = FindSingleQuote(data, fromPos+1);
        startSeparatorPosition = nextSingleQuote+1;
        return data.Substring(fromPos+1, nextSingleQuote-fromPos-1).Replace("\"\"", "\"");
      }
      // The field ends in the next comma or EOL
      int nextComma = data.IndexOf(',', fromPos);
      if (nextComma == -1) {
        startSeparatorPosition = data.Length;
        return data.Substring(fromPos);
      }
      else {
        startSeparatorPosition = nextComma;
        return data.Substring(fromPos, nextComma-fromPos);
      }
    }
    // Returns the index of the next single quote mark in the string 
    // (starting from startFrom)
    private int FindSingleQuote(string data, int startFrom) {
      int i = startFrom-1;
      while (++i < data.Length)
        if (data[i] == '"') {
          // If this is a double quote, bypass the chars
          if (i < data.Length-1 && data[i+1] == '"') {
            i++;
            continue;
          }
          else
            return i;
        }
      // If no quote found, return the end value of i (data.Length)
      return i;
    }
    /// <summary>
    /// Disposes the CSVReader. The underlying stream is closed.
    /// </summary>
    public void Dispose() {
      // Closing the reader closes the underlying stream, too
      if (reader != null) reader.Close();
      else if (stream != null)
        stream.Close(); // In case we failed before the reader was constructed
      GC.SuppressFinalize(this);
    }
  }

  /// <summary>
  /// Exception class for CSVReader exceptions.
  /// </summary>
  public class CSVReaderException : ApplicationException { 
  
    /// <summary>
    /// Constructs a new exception object with the given message.
    /// </summary>
    /// <param name="message">The exception message.</param>
    public CSVReaderException(string message) : base(message) { }
  }
}</pre>]]></content:encoded>
      <snippet:downloads>25</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=c33be95d-aaae-4326-ac0b-4e2fca52ca1c</guid>
      <title>Draw a Line on a WindowsForm</title>
      <link>/PreviewSnippet.aspx?SnippetID=c33be95d-aaae-4326-ac0b-4e2fca52ca1c</link>
      <description>Draw a Line on a WindowsForm [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:48:05 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=c33be95d-aaae-4326-ac0b-4e2fca52ca1c#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Draw a Line on a WindowsForm</dc:title>
      <dc:date>4/6/2005 1:48:05 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        'Draw line on form
        Dim bit As Bitmap = New Bitmap(Me.Width, Me.Height)
        Dim g As Graphics = Graphics.FromImage(bit)
        Dim myPen As Pen = New Pen (Color.Blue, 3)
        Me.CreateGraphics.DrawLine(myPen, 0, 0, Me.Width, Me.Height)
</pre>]]></content:encoded>
      <snippet:downloads>9</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=9878b29a-c69e-4092-8f94-4ffc4eb65892</guid>
      <title>Color your Console text (C#)</title>
      <link>/PreviewSnippet.aspx?SnippetID=9878b29a-c69e-4092-8f94-4ffc4eb65892</link>
      <description>Color your Console text (C#) [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:53:08 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=9878b29a-c69e-4092-8f94-4ffc4eb65892#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Color your Console text (C#)</dc:title>
      <dc:date>4/9/2005 1:53:08 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>// change text color in Windows console mode
// colors are 0=black 1=blue 2=green 4=red and so on to 15=white
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236
//
// the necessary WinApi functions are in kernel32.dll
// in C# Handle = IntPtr  DWORD = uint   WORD = int
// STD_OUTPUT_HANDLE = 0xfffffff5 (from winbase.h)
//
// this is a Console Application
using System;
using System.Runtime.InteropServices; // DllImport()
namespace TextColor1
{
        class MainClass
        {
                [DllImport("kernel32.dll")]
                public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput,
                int wAttributes);
                [DllImport("kernel32.dll")]
                public static extern IntPtr GetStdHandle(uint nStdHandle);
                public static void Main(string[] args)
                {
                        uint STD_OUTPUT_HANDLE = 0xfffffff5;
                        IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
                        // increase k for more color options
                        for (int k = 1; k < 255; k++)
                        {
                                SetConsoleTextAttribute(hConsole, k);
                                Console.WriteLine("{0:d3}  I want to be nice today!",k);
                        }
                        // final setting
                        SetConsoleTextAttribute(hConsole, 236);
                        Console.WriteLine("Press Enter to exit ...");
                        Console.Read();  // wait
                }
        }
}
</pre>]]></content:encoded>
      <snippet:downloads>20</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ea6f4c6b-feda-4b2e-a68e-502e13a678db</guid>
      <title>Encrypt / decrypt string using base64</title>
      <link>/PreviewSnippet.aspx?SnippetID=ea6f4c6b-feda-4b2e-a68e-502e13a678db</link>
      <description>Encrypt / decrypt string using base64 [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 02 Jun 2005 01:44:24 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ea6f4c6b-feda-4b2e-a68e-502e13a678db#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Encrypt / decrypt string using base64</dc:title>
      <dc:date>6/2/2005 1:44:24 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>	/// <summary>
	/// Encrypt / decrypt string using base64.
	/// </summary>
	public class SimpleEncrypt
	{
		private SimpleEncrypt()
		{
		}
		
		/// <summary>
		/// Return base64 version of string.
		/// </summary>
		public static string Encrypt(string text)
		{
			try
			{
				byte[] bytes = Encoding.ASCII.GetBytes(text);
				return Convert.ToBase64String(bytes, 0, bytes.Length);
			}
			catch (Exception ex)
			{	
				System.Diagnostics.Debug.WriteLine(ex.Message);
				return String.Empty;
			}
		}
		/// <summary>
		/// Return string version of base64 string.
		/// </summary>
		public static string Decrypt(string text)
		{
			try
			{
				byte[] bytes = Convert.FromBase64String(text);
				return Encoding.ASCII.GetString(bytes, 0, bytes.Length);
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				return String.Empty;
			}
		}
	}</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=564f8280-4828-4247-9687-50720d1f27bd</guid>
      <title>URLPictureBox , an Internet enabled PictureBox subclass</title>
      <link>/PreviewSnippet.aspx?SnippetID=564f8280-4828-4247-9687-50720d1f27bd</link>
      <description>URLPictureBox , an Internet enabled PictureBox subclass [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 03 Dec 2005 07:16:22 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=564f8280-4828-4247-9687-50720d1f27bd#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>URLPictureBox , an Internet enabled PictureBox subclass</dc:title>
      <dc:date>12/3/2005 7:16:22 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
namespace Sand.Services.MovieInfo.SDK.Controls
{
	/// <summary>
	/// Summary description for URLPictureBox.
	/// </summary>
	public class URLPictureBox : PictureBox
	{
		string m_ImageUrl = null;
		public string URL
		{
			set
			{
				m_ImageUrl = value;
				Thread imageThread = new Thread(new ThreadStart(LoadWebImage));
				imageThread.IsBackground = true; 
				imageThread.Start();
			}
			get
			{
				return m_ImageUrl;
			}
		}
		private void LoadWebImage ()
		{
			try
			{
				HttpWebRequest request= (HttpWebRequest)WebRequest.Create(m_ImageUrl); 
				request.Timeout = 10000; // 10 secs 
				request.AllowWriteStreamBuffering = true; 
				HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
				Image = Image.FromStream (response.GetResponseStream());
			}
			catch
			{
				Image = null;
			}
		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=196585c7-c4a9-4b0c-ba7b-50815ec2ace0</guid>
      <title>Download File From the Internet</title>
      <link>/PreviewSnippet.aspx?SnippetID=196585c7-c4a9-4b0c-ba7b-50815ec2ace0</link>
      <description>Download File From the Internet [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:46:28 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=196585c7-c4a9-4b0c-ba7b-50815ec2ace0#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Download File From the Internet</dc:title>
      <dc:date>4/6/2005 1:46:28 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        Imports System.Net
        Dim wClient As WebClient = New WebClient()
        'the web address to the file to download.
        Dim theAddy As String = "http://www.vbcodesource.com/dummyFile.txt"
        'the file to download and the file to save the downloaded file too.
        wClient.DownloadFile(theAddy, "c:\dummy.txt")
</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=8188ac52-0278-4b0c-9be0-50a96eabe4fb</guid>
      <title>Using Data Protection API (DPAPI) to encrypt and decrypt secrets</title>
      <link>/PreviewSnippet.aspx?SnippetID=8188ac52-0278-4b0c-9be0-50a96eabe4fb</link>
      <description>Using Data Protection API (DPAPI) to encrypt and decrypt secrets [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 05 Jun 2005 00:17:21 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=8188ac52-0278-4b0c-9be0-50a96eabe4fb#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Using Data Protection API (DPAPI) to encrypt and decrypt secrets</dc:title>
      <dc:date>6/5/2005 12:17:21 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>' Uses the Data Protection API (DPAPI) to encrypt and decrypt secrets
' based on the logged in user or local machine. 
Imports System.Runtime.InteropServices
Imports System.Security
Imports System.Text
Public NotInheritable Class DataProtection
	' use local machine or user to encrypt and decrypt the data
	Public Enum Store
		Machine
		User
	End Enum
	' const values
	Private Class Consts
		' specify an entropy so other DPAPI applications can't see the data
		Public Shared EntropyData As Byte() = _
		 ASCIIEncoding.ASCII.GetBytes("9EA4882F-F8D8-4f24-9402-FF951E5B4929")
	End Class
	' static class
	Private Sub New()
	End Sub
	' public methods
	' encrypt the data using DPAPI, returns a base64-encoded encrypted string
	Public Shared Function Encrypt(ByVal data As String, ByVal store As Store) As String
		' holds the result string
		Dim result As String = ""
		' blobs used in the CryptProtectData call
		Dim inBlob As New Win32.DATA_BLOB
		Dim entropyBlob As New Win32.DATA_BLOB
		Dim outBlob As New Win32.DATA_BLOB
		Try
			' setup flags passed to the CryptProtectData call
			Dim flags As Integer = Win32.CRYPTPROTECT_UI_FORBIDDEN Or _
			  CInt(IIf(store = store.Machine, Win32.CRYPTPROTECT_LOCAL_MACHINE, 0))
			' setup input blobs, the data to be encrypted and entropy blob
			SetBlobData(inBlob, ASCIIEncoding.ASCII.GetBytes(data))
			SetBlobData(entropyBlob, Consts.EntropyData)
			' call the DPAPI function, returns true if successful and fills in the outBlob
			If Win32.CryptProtectData(inBlob, "", entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, outBlob) Then
				Dim resultBits As Byte() = GetBlobData(outBlob)
				If Not resultBits Is Nothing Then
					result = Convert.ToBase64String(resultBits)
				End If
			End If
		Catch ex As Exception
			' an error occurred, return an empty string
		Finally
			' clean up
			If inBlob.pbData.ToInt32() <> 0 Then
				Marshal.FreeHGlobal(inBlob.pbData)
			End If
			If entropyBlob.pbData.ToInt32() <> 0 Then
				Marshal.FreeHGlobal(entropyBlob.pbData)
			End If
		End Try
		Return result
	End Function
	' decrypt the data using DPAPI, data is a base64-encoded encrypted string
	Public Shared Function Decrypt(ByVal data As String, ByVal store As Store) As String
		' holds the result string
		Dim result As String = ""
		' blobs used in the CryptUnprotectData call
		Dim inBlob As New Win32.DATA_BLOB
		Dim entropyBlob As New Win32.DATA_BLOB
		Dim outBlob As New Win32.DATA_BLOB
		Try
			' setup flags passed to the CryptUnprotectData call
			Dim flags As Integer = Win32.CRYPTPROTECT_UI_FORBIDDEN Or _
			 CInt(IIf(store = store.Machine, Win32.CRYPTPROTECT_LOCAL_MACHINE, 0))
			' the CryptUnprotectData works with a byte array, convert string data
			Dim bits As Byte() = Convert.FromBase64String(data)
			' setup input blobs, the data to be decrypted and entropy blob
			SetBlobData(inBlob, bits)
			SetBlobData(entropyBlob, Consts.EntropyData)
			' call the DPAPI function, returns true if successful and fills in the outBlob
			If Win32.CryptUnprotectData(inBlob, Nothing, entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, outBlob) Then
				Dim resultBits As Byte() = GetBlobData(outBlob)
				If Not resultBits Is Nothing Then
					result = ASCIIEncoding.ASCII.GetString(resultBits)
				End If
			End If
		Catch ex As Exception
			' an error occurred, return an empty string
		Finally
			' clean up
			If inBlob.pbData.ToInt32() <> 0 Then
				Marshal.FreeHGlobal(inBlob.pbData)
			End If
			If entropyBlob.pbData.ToInt32() <> 0 Then
				Marshal.FreeHGlobal(entropyBlob.pbData)
			End If
		End Try
		Return result
	End Function

	' internal methods
#Region " data protection api "
	Private Class Win32
		Public Const CRYPTPROTECT_UI_FORBIDDEN As Integer = &H1
		Public Const CRYPTPROTECT_LOCAL_MACHINE As Integer = &H4
		<StructLayout(LayoutKind.Sequential)> _
		  Public Structure DATA_BLOB
			Public cbData As Integer
			Public pbData As IntPtr
		End Structure
		<DllImport("crypt32", CharSet:=CharSet.Auto)> _
		Public Shared Function CryptProtectData(ByRef pDataIn As DATA_BLOB, _
		 ByVal szDataDescr As String, ByRef pOptionalEntropy As DATA_BLOB, _
		 ByVal pvReserved As IntPtr, ByVal pPromptStruct As IntPtr, _
		 ByVal dwFlags As Integer, ByRef pDataOut As DATA_BLOB) As Boolean
		End Function
		<DllImport("crypt32", CharSet:=CharSet.Auto)> _
		Public Shared Function CryptUnprotectData(ByRef pDataIn As DATA_BLOB, _
		 ByVal szDataDescr As StringBuilder, ByRef pOptionalEntropy As DATA_BLOB, _
		 ByVal pvReserved As IntPtr, ByVal pPromptStruct As IntPtr, _
		 ByVal dwFlags As Integer, ByRef pDataOut As DATA_BLOB) As Boolean
		End Function
		<DllImport("kernel32")> _
		Public Shared Function LocalFree(ByVal hMem As IntPtr) As IntPtr
		End Function
	End Class
#End Region
	' helper method that fills in a  DATA_BLOB, copies 
	' data from managed to unmanaged memory
	Private Shared Sub SetBlobData(ByRef blob As Win32.DATA_BLOB, ByVal bits As Byte())
		blob.cbData = bits.Length
		blob.pbData = Marshal.AllocHGlobal(bits.Length)
		Marshal.Copy(bits, 0, blob.pbData, bits.Length)
	End Sub
	' helper method that gets data from a DATA_BLOB, 
	' copies data from unmanaged memory to managed
	Private Shared Function GetBlobData(ByRef blob As Win32.DATA_BLOB) As Byte()
		' return null if the blob is empty
		If blob.pbData.ToInt32() = 0 Then Return Nothing
		' copy information from the blob
		Dim data(blob.cbData - 1) As Byte
		Marshal.Copy(blob.pbData, data, 0, blob.cbData)
		Win32.LocalFree(blob.pbData)
		Return data
	End Function
End Class</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ccee5edc-b7c8-462b-85e8-528e35f4d351</guid>
      <title>Create a file</title>
      <link>/PreviewSnippet.aspx?SnippetID=ccee5edc-b7c8-462b-85e8-528e35f4d351</link>
      <description>Create a file [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 14:00:26 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ccee5edc-b7c8-462b-85e8-528e35f4d351#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>Create a file</dc:title>
      <dc:date>4/9/2005 2:00:26 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.IO; 
namespace csharp
{
class Class1
{
static void Main(string[] args)
{
FileInfo fileInfo = null;
FileStream fileStream = null;
if (!File.Exists (@"c:\testfile1.txt"))
{
fileInfo = new FileInfo(@"c:\testfile1.txt");
fileStream = fileInfo.Create( );
Console.WriteLine("File created successfully");
}

}
}
}</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=c38b3f5e-4dcf-4477-8fa2-552e06accdda</guid>
      <title>Register .NET asembly windows installer class</title>
      <link>/PreviewSnippet.aspx?SnippetID=c38b3f5e-4dcf-4477-8fa2-552e06accdda</link>
      <description>Register .NET asembly windows installer class [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 10 Jan 2006 09:29:06 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=c38b3f5e-4dcf-4477-8fa2-552e06accdda#comments</comments>
      <category>0b8019ad-0497-47b3-ae19-9ee2582bceff</category>
      <dc:title>Register .NET asembly windows installer class</dc:title>
      <dc:date>1/10/2006 9:29:06 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>	[RunInstaller(true)]
	public class InstallClassRegAsm: Installer
	{
		public InstallClassRegAsm() :base()
		{
		}
		#region Install
		//---Override the 'Install' method.
		public override void Install(IDictionary savedState)
		{
			base.Install(savedState);
			//---the assembly to register
			string strAssemblyFile = base.Context.Parameters["name"].ToString();
			//---checkpoint 
			Trace.WriteLine(string.Format("Install {0}", strAssemblyFile));
			//---load assembly 
			Assembly objAsm = Assembly.LoadFrom(strAssemblyFile);
			
			//---action
			RegistrationServices  objRS = new RegistrationServices();
			objRS.RegisterAssembly(objAsm, AssemblyRegistrationFlags.SetCodeBase);		
		}
		#endregion
		#region Uninstall
		//---Override the 'Uninstall' method.
		public override void Uninstall(IDictionary savedState)
		{
			base.Uninstall(savedState);
			//---the assembly to register
			string strAssemblyFile = base.Context.Parameters["name"].ToString();
			//---checkpoint 
			Trace.WriteLine(string.Format("Uninstall {0}", strAssemblyFile));
			//---load assembly 
			Assembly objAsm = Assembly.LoadFrom(strAssemblyFile);
	
			//---action
			RegistrationServices  objRS = new RegistrationServices();
			objRS.UnregisterAssembly(objAsm);	
		}
		#endregion
	}</pre>]]></content:encoded>
      <snippet:downloads>1</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=7929ad31-802b-4a35-955d-559793d56f2d</guid>
      <title>Generating simple randow passwords</title>
      <link>/PreviewSnippet.aspx?SnippetID=7929ad31-802b-4a35-955d-559793d56f2d</link>
      <description>Generating simple randow passwords [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 30 Jan 2006 09:46:09 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=7929ad31-802b-4a35-955d-559793d56f2d#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Generating simple randow passwords</dc:title>
      <dc:date>1/30/2006 9:46:09 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		/// <summary>
		/// Generates a "Random Enough" password. :)
		/// </summary>
		/// <returns></returns>
		public static string RandomPassword()
		{
			return Guid.NewGuid().ToString().Substring(0,8);
		}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=76a9fc18-aa8d-4b94-b14d-5b162fad00fd</guid>
      <title>Using .NET reflection to create a managed RegSrv</title>
      <link>/PreviewSnippet.aspx?SnippetID=76a9fc18-aa8d-4b94-b14d-5b162fad00fd</link>
      <description>Using .NET reflection to create a managed RegSrv [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 05 Sep 2005 20:17:53 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=76a9fc18-aa8d-4b94-b14d-5b162fad00fd#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Using .NET reflection to create a managed RegSrv</dc:title>
      <dc:date>9/5/2005 8:17:53 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>//Original code by Mattias Sjogren
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
public class DllRegServer
{
  private string m_sDllFile;
  private static ModuleBuilder s_mb;
  private Type m_tDllReg;
  public DllRegServer(string dllFile)
  {
    m_sDllFile = dllFile;
    CreateDllRegType();
  }

  public void Register()
  {
    InternalRegServer( false );
  }
  public void UnRegister()
  {
    InternalRegServer( true );
  }
  private void InternalRegServer(bool fUnreg)
  {
    string sMemberName = fUnreg ? "DllUnregisterServer" : "DllRegisterServer";
    int hr = (int)m_tDllReg.InvokeMember( sMemberName, BindingFlags.InvokeMethod, null,
                                          Activator.CreateInstance( m_tDllReg ), null );
    if ( hr != 0 )
      Marshal.ThrowExceptionForHR( hr );
  }
  private void CreateDllRegType()
  {
    if ( s_mb == null ) {
      // Create dynamic assembly    
      AssemblyName an = new AssemblyName();
      an.Name = "DllRegServerAssembly" + Guid.NewGuid().ToString( "N" );
      AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly( an, AssemblyBuilderAccess.Run );
      // Add module to assembly
      s_mb = ab.DefineDynamicModule( "DllRegServerModule" );
    }
    // Add class to module
    TypeBuilder tb = s_mb.DefineType( "DllRegServerClass" + Guid.NewGuid().ToString( "N" ) );
    MethodBuilder meb;
    // Add PInvoke methods to class
    meb = tb.DefinePInvokeMethod( "DllRegisterServer", m_sDllFile,
      MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
      CallingConventions.Standard, typeof(int), null, CallingConvention.StdCall, CharSet.Auto );
    // Apply preservesig metadata attribute so we can handle return HRESULT ourselves
    meb.SetImplementationFlags( MethodImplAttributes.PreserveSig | meb.GetMethodImplementationFlags() );
    meb = tb.DefinePInvokeMethod("DllUnregisterServer", m_sDllFile,
      MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
      CallingConventions.Standard, typeof(int), null, CallingConvention.StdCall, CharSet.Auto );
    // Apply preservesig metadata attribute so we can handle return HRESULT ourselves
    meb.SetImplementationFlags( MethodImplAttributes.PreserveSig | meb.GetMethodImplementationFlags() );
    // Create the type
    m_tDllReg = tb.CreateType();
  }
}</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=6a3d3006-8f46-45ad-9e98-5b69cd765509</guid>
      <title>DNS information</title>
      <link>/PreviewSnippet.aspx?SnippetID=6a3d3006-8f46-45ad-9e98-5b69cd765509</link>
      <description>DNS information [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:59:57 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=6a3d3006-8f46-45ad-9e98-5b69cd765509#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>DNS information</dc:title>
      <dc:date>4/9/2005 1:59:57 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Net;
class MYDns
{
public static void Main ()
{
string hostName = Dns.GetHostName();
Console.WriteLine("Local hostname: {0}", hostName);
IPHostEntry myself = Dns.GetHostByName(hostName);
foreach (IPAddress address in myself.AddressList)
{
Console.WriteLine("IP Address: {0}", address.ToString());
}
}
}
</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=eb10f662-2da5-46e0-893f-5c33c37b9b71</guid>
      <title>Perform a DNS query</title>
      <link>/PreviewSnippet.aspx?SnippetID=eb10f662-2da5-46e0-893f-5c33c37b9b71</link>
      <description>Perform a DNS query [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:56:37 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=eb10f662-2da5-46e0-893f-5c33c37b9b71#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>Perform a DNS query</dc:title>
      <dc:date>4/9/2005 1:56:37 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Net;
class GetDnsInfo
{
public static void Main(string[] argv)
{
if (argv.Length != 1)
{
Console.WriteLine("Usage: GetDnsInfo hostname");
return;
}
IPHostEntry results = Dns.GetHostByName(argv[0]);
Console.WriteLine("Host name: {0}",
results.HostName);
foreach(string alias in results.Aliases)
{
Console.WriteLine("Alias: {0}", alias);
}
foreach(IPAddress address in results.AddressList)
{
Console.WriteLine("Address: {0}",
address.ToString());
}
}
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=78c4a855-96db-4da4-bbdb-5de9adbb1b91</guid>
      <title>Show a modal dialog with an exception</title>
      <link>/PreviewSnippet.aspx?SnippetID=78c4a855-96db-4da4-bbdb-5de9adbb1b91</link>
      <description>Show a modal dialog with an exception [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 10 Jan 2006 09:27:20 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=78c4a855-96db-4da4-bbdb-5de9adbb1b91#comments</comments>
      <category>def21cf5-7419-48cb-a8b7-ceb74299c62a</category>
      <dc:title>Show a modal dialog with an exception</dc:title>
      <dc:date>1/10/2006 9:27:20 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		/// <summary>
		/// Show a modal dialog with an exception.
		/// </summary>
		/// <param name="msg">Error Messsage</param>
		/// <param name="e">Exception that is caught</param>
		public static void ShowException(String msg, Exception e) 
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append(msg + e + "\n");
			sb.Append(e.StackTrace);
			System.Windows.Forms.MessageBox.Show(sb.ToString());
		}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=72d95142-ed71-430a-946b-60f4766d2acb</guid>
      <title>Extracts the manifest files from the executable and writes it to the file system.</title>
      <link>/PreviewSnippet.aspx?SnippetID=72d95142-ed71-430a-946b-60f4766d2acb</link>
      <description>Extracts the manifest files from the executable and writes it to the file system. [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 05 Jun 2005 00:16:06 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=72d95142-ed71-430a-946b-60f4766d2acb#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>Extracts the manifest files from the executable and writes it to the file system.</dc:title>
      <dc:date>6/5/2005 12:16:06 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.IO
Public NotInheritable Class ThemeManifest
	' const values
	Private Class Consts
		Public Const ResourceName As String = "FotoVision.ThemeManifest.xml"
	End Class
	' static class
	Private Sub New()
	End Sub
	' extract the manifest file from the executable and writes it to 
	' the file system, return true if created the file, otherwise false
	Public Shared Function Create() As Boolean
		' full path to where the manifest file should be written (app name + .manifest)
		Dim path As String = Application.ExecutablePath + ".manifest"
		' return right away if it already exist
		If File.Exists(path) Then Return False
		Try
			' read the manifest xml resource from the exe
			Dim assem As System.Reflection.Assembly
			assem = System.Reflection.Assembly.GetExecutingAssembly()
			Dim reader As TextReader = New StreamReader( _
			 assem.GetManifestResourceStream(Consts.ResourceName))
			Dim xml As String = reader.ReadToEnd()
			reader.Close()
			' create the manifest file
			Dim writer As New StreamWriter(path)
			writer.Write(xml)
			writer.Close()
			' created the manifest file			
			Return True
		Catch ex As Exception
			' could not create the file
			Return False
		End Try
	End Function
End Class
</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=8e9a2c01-c115-4c05-a796-62d6dcde4294</guid>
      <title>This snippets demonstrates how to check whether a user is logged in or not. The code also shows how you can extract the UserData from the Ticket that is retrieved from the User Identity.</title>
      <link>/PreviewSnippet.aspx?SnippetID=8e9a2c01-c115-4c05-a796-62d6dcde4294</link>
      <description>This snippets demonstrates how to check whether a user is logged in or not. The code also shows how you can extract the UserData from the Ticket that is retrieved from the User Identity. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 11 May 2005 13:06:43 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=8e9a2c01-c115-4c05-a796-62d6dcde4294#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>This snippets demonstrates how to check whether a user is logged in or not. The code also shows how you can extract the UserData from the Ticket that is retrieved from the User Identity.</dc:title>
      <dc:date>5/11/2005 1:06:43 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>if (HttpContext.Current.User.Identity.Name != null)
{
  if(HttpContext.Current.User.Identity.Name.Length != 0)
  {
    FormsIdentity id = (FormsIdentity) User.Identity;
    FormsAuthenticationTicket ticket = id.Ticket;
    string MyUserData = ticket.UserData;
  }
}</pre>]]></content:encoded>
      <snippet:downloads>26</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=486c9774-2671-48fd-8918-631606502cf7</guid>
      <title>Hello world sample in C#</title>
      <link>/PreviewSnippet.aspx?SnippetID=486c9774-2671-48fd-8918-631606502cf7</link>
      <description>Hello world sample in C# [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 14:18:46 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=486c9774-2671-48fd-8918-631606502cf7#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Hello world sample in C#</dc:title>
      <dc:date>4/16/2005 2:18:46 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>// A "Hello World!" program in C# 
class Hello 
{ 
   static void Main() 
   { 
      System.Console.WriteLine("Hello World!"); 
   } 
} </pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=25816198-cb6d-444c-a2d4-6422221f2c86</guid>
      <title>Extend Windows Form Controls to handle more UI events</title>
      <link>/PreviewSnippet.aspx?SnippetID=25816198-cb6d-444c-a2d4-6422221f2c86</link>
      <description>Extend Windows Form Controls to handle more UI events [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 24 Apr 2005 10:38:43 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=25816198-cb6d-444c-a2d4-6422221f2c86#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Extend Windows Form Controls to handle more UI events</dc:title>
      <dc:date>4/24/2005 10:38:43 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using Microsoft.WindowsCE.Forms;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//
// The MessageWin form is "home key" aware
//
public class MessageWin : MessageWindow
{
    // Event handler for the client to plug in.
    // This is the second callback.
    public System.EventHandler HomeKeyPress;
    
    public MessageWin()
    {
        //register to listen for home key
        RegisterHotKey(this.Hwnd, VK_LWIN, 8, VK_LWIN);
    }
    ~MessageWin()
    {
        Unregister();
    }
    // Receives the raw UI events.
    // This is the first callback.
    protected override void WndProc(ref Message m)
    {
        // Captures the key event
        if (m.Msg == WM_HOTKEY)
        {
            if ((int) m.WParam == VK_LWIN)
                // This is a home key event, we
                // should invoke the second callback
                // provided by the client to actually
                // handle the event.
                if (HomeKeyPress!=null)
                    HomeKeyPress(this, null);
        }
        // All other events are handled by the default
        // event handler.
        base.WndProc (ref m);
    }
    // Import the native methods
    #region P/Invokes
    private constint VK_LWIN     =   0x5B;
    private constint WM_HOTKEY   =   0x0312;
    
    [DllImport("coredll.dll")]
    public static extern bool RegisterHotKey(
        IntPtr hWnd, // handle to window
        int id, // hot key identifier
        int Modifiers, // key-modifier options
        int key //virtual-key code);
        
    [DllImport("coredll.dll")]
    public static extern bool UnregisterHotKey(
        IntPtr  hWnd,
        int     id);
    #endregion
}
// 
// Client side code
//
// Instantiate the MessageWin form.
MessageWin msgWin = new MessageWin();
// Plug in the event handler for the HomeKeyPress event.
msgWin.HomeKeyPress += new EventHandler(msgWin_HomeKeyPress);
... ...
// Actual write the HomeKeyPress event handler.
private void msgWin_HomeKeyPress(object sender, System.EventArgs e)
{
    MessageBox.Show("Home Key Pressed.");
}</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=1e104158-b339-47d3-9379-696dfba8b164</guid>
      <title>How do I find the "My Document's" folder of the current user?</title>
      <link>/PreviewSnippet.aspx?SnippetID=1e104158-b339-47d3-9379-696dfba8b164</link>
      <description>How do I find the "My Document's" folder of the current user? [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 17 Apr 2005 10:47:08 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=1e104158-b339-47d3-9379-696dfba8b164#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>How do I find the "My Document's" folder of the current user?</dc:title>
      <dc:date>4/17/2005 10:47:08 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>  OpenFileDialog o = new OpenFileDialog();
  // the "My Document's" folder of the current user
  o.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal).ToString();
  if( o.ShowDialog() == DialogResult.OK )
  {
    // do nothing
  }</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=407af7de-a582-4243-be20-69a5f0ef037a</guid>
      <title>Add all Known Colors to a ComboBox or ListBox Control</title>
      <link>/PreviewSnippet.aspx?SnippetID=407af7de-a582-4243-be20-69a5f0ef037a</link>
      <description>Add all Known Colors to a ComboBox or ListBox Control [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:44:23 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=407af7de-a582-4243-be20-69a5f0ef037a#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Add all Known Colors to a ComboBox or ListBox Control</dc:title>
      <dc:date>4/6/2005 1:44:23 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>       Imports System.Drawing
        Dim kColor As KnownColor
        For kColor = KnownColor.AliceBlue To KnownColor.YellowGreen
            cmbColor.Items.Add(kColor)
        Next
</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=62dde299-9b3e-4c85-acd8-6a0e3e97746a</guid>
      <title>AntiAlias Graphics</title>
      <link>/PreviewSnippet.aspx?SnippetID=62dde299-9b3e-4c85-acd8-6a0e3e97746a</link>
      <description>AntiAlias Graphics [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:45:22 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=62dde299-9b3e-4c85-acd8-6a0e3e97746a#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>AntiAlias Graphics</dc:title>
      <dc:date>4/6/2005 1:45:22 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>       Imports System.Drawing.Drawing2D
       Dim g As Graphics 'just a example for your graphics variable. Change g to whatever your object variable is.
       g.Graphics.SmoothingMode = SmoothingMode.AntiAlias 'will smooth out all your lines, edges, corners, ect....
</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=7de50517-0013-484d-9f1d-6b591cc6e463</guid>
      <title>SecondsToShortHMSString and SecondsToHMSString</title>
      <link>/PreviewSnippet.aspx?SnippetID=7de50517-0013-484d-9f1d-6b591cc6e463</link>
      <description>SecondsToShortHMSString and SecondsToHMSString [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 13 Oct 2005 18:44:04 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=7de50517-0013-484d-9f1d-6b591cc6e463#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>SecondsToShortHMSString and SecondsToHMSString</dc:title>
      <dc:date>10/13/2005 6:44:04 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		static public string SecondsToShortHMSString(int lSeconds)
		{
			if (lSeconds<0) return ("0:00");
			int hh = lSeconds / 3600;
			lSeconds = lSeconds%3600;
			int mm = lSeconds / 60;
			int ss = lSeconds % 60;

			string strHMS="";
			strHMS=String.Format("{0}:{1:00}",hh,mm);
			return strHMS;
		}

		static public string SecondsToHMSString(int lSeconds)
		{
			if (lSeconds<0) return ("0:00");
			int hh = lSeconds / 3600;
			lSeconds = lSeconds%3600;
			int mm = lSeconds / 60;
			int ss = lSeconds % 60;

			string strHMS="";
			if (hh>=1)
				strHMS=String.Format("{0}:{1:00}:{2:00}",hh,mm,ss);
			else
				strHMS=String.Format("{0}:{1:00}",mm,ss);
			return strHMS;
		}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=e5dd4550-df29-47b8-b702-6e02cd90fac6</guid>
      <title>Function to test for Positive Integers with Regular expressions</title>
      <link>/PreviewSnippet.aspx?SnippetID=e5dd4550-df29-47b8-b702-6e02cd90fac6</link>
      <description>Function to test for Positive Integers with Regular expressions [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 19 Apr 2005 09:38:57 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=e5dd4550-df29-47b8-b702-6e02cd90fac6#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Function to test for Positive Integers with Regular expressions</dc:title>
      <dc:date>4/19/2005 9:38:57 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>// Function to test for Positive Integers.
public bool IsNaturalNumber(String strNumber)
{
    Regex objNotNaturalPattern=new Regex("[^0-9]");
    Regex objNaturalPattern=new Regex("0*[1-9][0-9]*");
    return  !objNotNaturalPattern.IsMatch(strNumber) &&
            objNaturalPattern.IsMatch(strNumber);
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=09aedb41-e633-442a-bb64-6ebf662fd130</guid>
      <title>Converting different DateTime formats including RFC822 to .NET DateTime</title>
      <link>/PreviewSnippet.aspx?SnippetID=09aedb41-e633-442a-bb64-6ebf662fd130</link>
      <description>Converting different DateTime formats including RFC822 to .NET DateTime [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 10 Oct 2005 13:35:42 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=09aedb41-e633-442a-bb64-6ebf662fd130#comments</comments>
      <category>701a2ecc-98c3-467f-95c7-3274cc59e2f4</category>
      <dc:title>Converting different DateTime formats including RFC822 to .NET DateTime</dc:title>
      <dc:date>10/10/2005 1:35:42 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>private DateTime FormatDate( string date )
{
    string RFC822 = "ddd, dd MMM yyyy HH:mm:ss zzz";
    //string RFC1123 = "yyyyMMddTHHmmss";
    //string RFCUnknown = "yyyy-MM-ddTHH:mm:ssZ";
    int indexOfPlus = date.LastIndexOf('+');
    if( indexOfPlus > 0 )
        date = date.Substring( 0, indexOfPlus-1 );
    string [] formats = new string[] { "r", "S", "U" };
    try
    {
      // Parse the dates using the standard
      // universal date format
      return DateTime.Parse(date,
           CultureInfo.InvariantCulture,
           DateTimeStyles.AdjustToUniversal);
    }
    catch
    {
       try
       {
          // Standard formats failed, try the "r" "S"
          // and "U" formats
          return DateTime.ParseExact( date, formats,
                    DateTimeFormatInfo.InvariantInfo,
                    DateTimeStyles.AdjustToUniversal);
       }
       catch
       {
           try
           {
              // All the standards formats have failed,
              //try the dreaded RFC822 format
              return DateTime.ParseExact( date, RFC822,
                      DateTimeFormatInfo.InvariantInfo,
                      DateTimeStyles.AdjustToUniversal);
           }
           catch
           {
              // All failed! The RSS Feed source
              // should be sued
              return DateTime.Now;
           }
       }
    }
}</pre>]]></content:encoded>
      <snippet:downloads>1</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=5b086449-2c20-4736-940a-7071136766cb</guid>
      <title>SQL Server Connection string for C#</title>
      <link>/PreviewSnippet.aspx?SnippetID=5b086449-2c20-4736-940a-7071136766cb</link>
      <description>SQL Server Connection string for C# [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 21 Apr 2005 19:02:11 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=5b086449-2c20-4736-940a-7071136766cb#comments</comments>
      <category>799cf308-a281-4275-a02e-d19edd44a797</category>
      <dc:title>SQL Server Connection string for C#</dc:title>
      <dc:date>4/21/2005 7:02:11 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>//Add this reference
using System.Data.SqlClient;
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString="Server=Aron1;Database=pubs;User ID=sa;Password=asdasd;Trusted_Connection=False";
oSQLConn.Open(); </pre>]]></content:encoded>
      <snippet:downloads>23</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=e304d956-5bc2-4f97-a143-7196c4250a60</guid>
      <title>Provides a reference of common MIME content-types, and retrieves additional types from the Windows registry if available.</title>
      <link>/PreviewSnippet.aspx?SnippetID=e304d956-5bc2-4f97-a143-7196c4250a60</link>
      <description>Provides a reference of common MIME content-types, and retrieves additional types from the Windows registry if available. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 01 Jan 2006 11:26:27 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=e304d956-5bc2-4f97-a143-7196c4250a60#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Provides a reference of common MIME content-types, and retrieves additional types from the Windows registry if available.</dc:title>
      <dc:date>1/1/2006 11:26:27 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Collections;
using System.Globalization;
using Microsoft.Win32;
/// reinux
namespace CodeXchange.Samples
{
	/// <summary>
	/// Provides a reference of common MIME content-types, and retrieves additional types from the Windows registry if available.
	/// </summary>
	public sealed class ContentTypes
	{
		private ContentTypes()
		{
		}
		static Hashtable InitContentTypes()
		{
			Hashtable extensionTypes = new Hashtable(
				new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture),
				new CaseInsensitiveComparer(CultureInfo.InvariantCulture)
				);
			#region Extensions from http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html
			extensionTypes.Add(".bin", "application/octet-stream");
			extensionTypes.Add(".uu", "application/octet-stream");
			extensionTypes.Add(".exe", "application/octet-stream");
			extensionTypes.Add(".ai", "application/postscript");
			extensionTypes.Add(".eps", "application/postscript");
			extensionTypes.Add(".ps", "application/postscript");
			extensionTypes.Add(".latex", "application/x-latex");
			extensionTypes.Add(".ram", "application/x-pn-realaudio");
			extensionTypes.Add(".swf", "application/x-shockwave-flash");
			extensionTypes.Add(".tar", "application/x-tar");
			extensionTypes.Add(".tcl", "application/x-tcl");
			extensionTypes.Add(".tex", "application/x-tex");
			extensionTypes.Add(".zip", "application/zip");
			extensionTypes.Add(".rar", "application/rar");
			extensionTypes.Add(".au", "audio/basic");
			extensionTypes.Add(".mpa", "audio/x-mpeg");
			extensionTypes.Add(".abs", "audio/x-mpeg");
			extensionTypes.Add(".mpega", "audio/x-mpeg");
			extensionTypes.Add(".mp2a", "audio/x-mpeg-2");
			extensionTypes.Add(".mpa2", "audio/x-mpeg-2");
			extensionTypes.Add(".wma", "audio/x-ms-wma");
			extensionTypes.Add(".wav", "audio/x-wav");
			extensionTypes.Add(".jpeg", "image/jpeg");
			extensionTypes.Add(".jpg", "image/jpeg");
			extensionTypes.Add(".jpe", "image/jpeg");
			extensionTypes.Add(".tiff", "image/tiff");
			extensionTypes.Add(".tif", "image/tiff");
			extensionTypes.Add(".bmp", "image/x-ms-bmp");
			extensionTypes.Add(".png", "image/x-png");
			extensionTypes.Add(".pnm", "image/x-portable-anymap");
			extensionTypes.Add(".pbm", "image/x-portable-bitmap");
			extensionTypes.Add(".pgm", "image/x-portable-graymap");
			extensionTypes.Add(".ppm", "image/x-portable-pixmap");
			extensionTypes.Add(".xbm", "image/x-xbitmap");
			extensionTypes.Add(".xpm", "image/x-xpixmap");
			extensionTypes.Add(".xwd", "image/x-xwindowdump");
			extensionTypes.Add(".css", "text/css");
			extensionTypes.Add(".html", "text/html");
			extensionTypes.Add(".htm", "text/html");
			extensionTypes.Add(".js", "text/javascript");
			extensionTypes.Add(".ls", "text/javascript");
			extensionTypes.Add(".mocha", "text/javascript");
			extensionTypes.Add(".txt", "text/plain");
			extensionTypes.Add(".bat", "text/plain");
			extensionTypes.Add(".c", "text/plain");
			extensionTypes.Add(".cpp", "text/plain");
			extensionTypes.Add(".c++", "text/plain");
			extensionTypes.Add(".cc", "text/plain");
			extensionTypes.Add(".h", "text/plain");
			extensionTypes.Add(".log", "text/plain");
			extensionTypes.Add(".cs", "text/plain");
			extensionTypes.Add(".vb", "text/plain");
			extensionTypes.Add(".mpeg", "video/mpeg");
			extensionTypes.Add(".mpg", "video/mpeg");
			extensionTypes.Add(".mpe", "video/mpeg");
			extensionTypes.Add(".mpv2", "video/mpeg-2");
			extensionTypes.Add(".mp2v", "video/mpeg-2");
			extensionTypes.Add(".qt", "video/quicktime");
			extensionTypes.Add(".mov", "video/quicktime");
			extensionTypes.Add(".asf", "video/x-ms-asf");
			extensionTypes.Add(".asx", "video/x-ms-asx");
			extensionTypes.Add(".wmv", "video/x-ms-wmv");
			extensionTypes.Add(".avi", "video/x-msvideo");
			#endregion
			return extensionTypes;
		}
		static Hashtable extensionTypes = InitContentTypes();
		/// <summary>
		/// Get a MIME content-type from a file extension.
		/// </summary>
		/// <param name="extension">A file extension.</param>
		/// <returns>A MIME compatible file file-type.</returns>
		public static string GetExtensionType(string extension)
		{
			string ret = extensionTypes[extension] as string;
			if(ret == null)
			{
				try
				{
					ret = GetContentTypeFromRegistry(extension);
				}
				catch(MemberAccessException)
				{
				}
				catch(NotImplementedException)
				{
				}
				finally
				{
					if(ret != null)
						extensionTypes[extension] = ret;
				}
			}
			return ret;
		}
		static string GetContentTypeFromRegistry(string extension)
		{
			RegistryKey classroot = Registry.ClassesRoot;
			RegistryKey extkey = classroot.OpenSubKey(extension, false);
			if(extkey == null)
				return null;
			object type = extkey.GetValue("Content Type");
			if(!(type is string))
				return null;
			return type as string;
		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>1</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=e186e658-6f68-4376-af69-74da4410304e</guid>
      <title>How to set a Windows environment variable</title>
      <link>/PreviewSnippet.aspx?SnippetID=e186e658-6f68-4376-af69-74da4410304e</link>
      <description>How to set a Windows environment variable [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 24 Apr 2005 10:42:24 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=e186e658-6f68-4376-af69-74da4410304e#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>How to set a Windows environment variable</dc:title>
      <dc:date>4/24/2005 10:42:24 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Runtime.InteropServices;
namespace EnvironmentVariables
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    {
        [DllImport("Kernel32.DLL", SetLastError=true)] 
        public static extern bool SetEnvironmentVariable(string lpName, string lpValue); 
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Current path
            string CurrentPath; 
            // Get the current path
            CurrentPath = Environment.GetEnvironmentVariable("Path"); 
            Console.WriteLine(CurrentPath);
            // Make sure the current path is not already present 
            if (CurrentPath.IndexOf(@"C:\MyPath") == -1) 
                // Set the new path 
                SetEnvironmentVariable( 
                    "Path", CurrentPath + ";" + @"C:\MyPath"); 
            // Get the current path 
            Console.WriteLine(Environment.GetEnvironmentVariable("Path")); 
            // Return the path to its original state 
            SetEnvironmentVariable("Path", CurrentPath); 
            Console.WriteLine(Environment.GetEnvironmentVariable("Path")); 
            
            Console.ReadLine();
        }
    }
}</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=81f09a62-ad31-4337-8061-76c709dbd356</guid>
      <title>Saving JPEG images with a specified quality</title>
      <link>/PreviewSnippet.aspx?SnippetID=81f09a62-ad31-4337-8061-76c709dbd356</link>
      <description>Saving JPEG images with a specified quality [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 05 Jun 2005 00:20:06 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=81f09a62-ad31-4337-8061-76c709dbd356#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Saving JPEG images with a specified quality</dc:title>
      <dc:date>6/5/2005 12:20:06 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>' Saves JPEG images with a specified quality, the quality ranges from 
' 1 (small file with low quality) to 100 (larger file with high quality). 
' The quality setting defines the amount of compression by generating
' different quantization tables which are stored in the JPEG image.
Imports System.Drawing.Imaging
Public NotInheritable Class JpegQuality
	' internal members
	Private Shared _codec As ImageCodecInfo
	' properties
	'  return the jpeg codec, only look up the first time
	Private Shared ReadOnly Property Codec() As ImageCodecInfo
		Get
			' return if already looked up the codec value
			If Not (_codec Is Nothing) Then Return _codec
			' loop through the list and find the jpeg codec
			Dim list As ImageCodecInfo() = ImageCodecInfo.GetImageDecoders()
			For Each codecInfo As ImageCodecInfo In list
				If codecInfo.MimeType = "image/jpeg" Then
					_codec = codecInfo
					Return _codec
				End If
			Next
			Return Nothing
		End Get
	End Property
	' static class
	Private Sub New()
	End Sub
	' public methods
	' save the image using the specified quality, the quality ranges
	' from 1 (low quality) to 100 (high quality)
	Public Shared Sub Save(ByVal imagePath As String, ByVal image As Bitmap, ByVal quality As Integer)
		' if can't find the jpeg codec, just use the
		' default .net framework quality setting (75)
		If JpegQuality.Codec Is Nothing Then
			image.Save(imagePath, Imaging.ImageFormat.Jpeg)
		Else
			Dim ep As EncoderParameters = New EncoderParameters
			ep.Param(0) = New EncoderParameter(Encoder.Quality, quality)
			image.Save(imagePath, JpegQuality.Codec, ep)
			ep.Dispose()
		End If
	End Sub
End Class</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a424f6bd-3bc5-40fe-af92-81c2f3923ca1</guid>
      <title>degrees to radians conversion</title>
      <link>/PreviewSnippet.aspx?SnippetID=a424f6bd-3bc5-40fe-af92-81c2f3923ca1</link>
      <description>degrees to radians conversion [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:56:06 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a424f6bd-3bc5-40fe-af92-81c2f3923ca1#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>degrees to radians conversion</dc:title>
      <dc:date>4/9/2005 1:56:06 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System; 
namespace csharp
{
class Class1
{
static void Main(string[] args)
{
double degrees;
double radians;
degrees = 50;
radians = (Math.PI / 180) * degrees;
Console.WriteLine(radians); 
}
}
}
</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=bb4fc115-a022-456e-8e4d-81f9f602e2ae</guid>
      <title>Display all system drives</title>
      <link>/PreviewSnippet.aspx?SnippetID=bb4fc115-a022-456e-8e4d-81f9f602e2ae</link>
      <description>Display all system drives [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:35:25 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=bb4fc115-a022-456e-8e4d-81f9f602e2ae#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Display all system drives</dc:title>
      <dc:date>4/6/2005 1:35:25 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Display all drives on your system
'create a new console application and paste this between the Sub Main() and End Sub Dim drives() As String 
drives = System.IO.Directory.GetLogicalDrives()
Dim enumerator As System.Collections.IEnumerator
enumerator = drives.GetEnumerator
While enumerator.MoveNext
Console.WriteLine(CStr(enumerator.Current))
End While
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=cc1cc62d-615a-40ad-b73f-8281c38a2059</guid>
      <title>Convert a mapped path to its equivalent UNC path</title>
      <link>/PreviewSnippet.aspx?SnippetID=cc1cc62d-615a-40ad-b73f-8281c38a2059</link>
      <description>Convert a mapped path to its equivalent UNC path [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 29 Oct 2005 10:20:01 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=cc1cc62d-615a-40ad-b73f-8281c38a2059#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Convert a mapped path to its equivalent UNC path</dc:title>
      <dc:date>10/29/2005 10:20:01 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Runtime.InteropServices;
namespace ConvertMappedPathToUNC
{
    /// <summary>
    /// Converts a Mapped Path to its equivalent UNC Path
    /// </summary>
    class MyApp
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            string fileName = @"r:\myfile.txt";
            string UNCPath = PathConversions.GetUNCPath(fileName);
            Console.WriteLine(UNCPath);
            Console.ReadLine();
        }
    }
    class PathConversions
    {
        // 
        // Import Declarations 
        // 
        [DllImport("mpr.dll")] 
        private static extern int WNetGetUniversalName (string lpLocalPath, 
            int dwInfoLevel, ref UNIVERSAL_NAME_INFO lpBuffer, ref int lpBufferSize); 

        [DllImport("mpr", CharSet=CharSet.Auto)] 
        protected static extern int WNetGetUniversalName (string lpLocalPath, 
            int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize); 

        [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] 
        private struct UNIVERSAL_NAME_INFO 
        { 
            [MarshalAs(UnmanagedType.LPTStr)] 
            public string lpUniversalName; 
        } 

        // 
        // Constants 
        // 
        protected const int NO_ERROR = 0; 
        protected const int ERROR_MORE_DATA = 234; 
        protected const int ERROR_NOT_CONNECTED = 2250; 
        protected const int UNIVERSAL_NAME_INFO_LEVEL = 1; 

        /// <summary>
        /// Converts a Mapped Path to its equivalent UNC Path
        /// </summary>
        public static string GetUNCPath(string mappedDrive) 
        { 
            UNIVERSAL_NAME_INFO uni = new UNIVERSAL_NAME_INFO(); 
            int bufferSize = Marshal.SizeOf(uni); 

            int returnValue = WNetGetUniversalName( 
                mappedDrive, UNIVERSAL_NAME_INFO_LEVEL, 
                ref uni, ref bufferSize); 

            if (ERROR_MORE_DATA == returnValue) 
            { 
                IntPtr pBuffer = Marshal.AllocHGlobal(bufferSize);; 
                try 
                { 
                    returnValue = WNetGetUniversalName( 
                        mappedDrive, UNIVERSAL_NAME_INFO_LEVEL, 
                        pBuffer, ref bufferSize); 

                    if (NO_ERROR == returnValue) 
                    { 
                        uni = (UNIVERSAL_NAME_INFO)Marshal.PtrToStructure(pBuffer, 
                              typeof(UNIVERSAL_NAME_INFO)); 
                    } 
                } 
                finally 
                { 
                    Marshal.FreeHGlobal(pBuffer); 
                } 
            } 
            switch (returnValue) 
            { 
                case NO_ERROR: 
                    return uni.lpUniversalName; 
                case ERROR_NOT_CONNECTED: 
                    Console.WriteLine("Share is not connected"); 
                    return string.Empty; 
                default: 
                    return string.Empty; 
            } 
        } 
    }
}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=08333f18-1f01-4135-9b1c-835b10636c70</guid>
      <title>Free disk space, WMI version</title>
      <link>/PreviewSnippet.aspx?SnippetID=08333f18-1f01-4135-9b1c-835b10636c70</link>
      <description>Free disk space, WMI version [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:58:13 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=08333f18-1f01-4135-9b1c-835b10636c70#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Free disk space, WMI version</dc:title>
      <dc:date>4/9/2005 1:58:13 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Management;
class DiskSpace
{
public static void Main (string[] argv)
{
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
Console.WriteLine("Logical Disk FreeSpace = " + disk["FreeSpace"]+ " bytes"); 
}
}
</pre>]]></content:encoded>
      <snippet:downloads>7</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=eb17dff1-83e2-4185-b548-83744860a5f9</guid>
      <title>find the hostname for a known IP address</title>
      <link>/PreviewSnippet.aspx?SnippetID=eb17dff1-83e2-4185-b548-83744860a5f9</link>
      <description>find the hostname for a known IP address [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:57:04 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=eb17dff1-83e2-4185-b548-83744860a5f9#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>find the hostname for a known IP address</dc:title>
      <dc:date>4/9/2005 1:57:04 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Net;
class GetAddress
{
public static void Main(string[] argv)
{
if (argv.Length != 1)
{
Console.WriteLine("Usage: GetAddress address");
return;
}
IPAddress test = IPAddress.Parse(argv[0]);
IPHostEntry iphe = Dns.GetHostByAddress(test);
Console.WriteLine("Information for {0}",
test.ToString());
Console.WriteLine("Host name: {0}", iphe.HostName);
foreach(string alias in iphe.Aliases)
{
Console.WriteLine("Alias: {0}", alias);
}
foreach(IPAddress address in iphe.AddressList)
{
Console.WriteLine("Address: {0}", address.ToString());
}
}
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=e7c80906-d0f2-4c06-a63e-8482c50cee0b</guid>
      <title>This snippet shows you how to implement a Singleton class in C#</title>
      <link>/PreviewSnippet.aspx?SnippetID=e7c80906-d0f2-4c06-a63e-8482c50cee0b</link>
      <description>This snippet shows you how to implement a Singleton class in C# [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 11 May 2005 13:05:41 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=e7c80906-d0f2-4c06-a63e-8482c50cee0b#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>This snippet shows you how to implement a Singleton class in C#</dc:title>
      <dc:date>5/11/2005 1:05:41 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>class Singleton
{
    private static Singleton singleton = null;
    public static Singleton Instance()
    {
        if (null == singleton)
            singleton = new Singleton();
        return singleton;
    }
    private Singleton()
    {
    }
}</pre>]]></content:encoded>
      <snippet:downloads>45</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=b5ce02dc-802a-48ed-979c-848fa87879f6</guid>
      <title>Getting the Names of all Embedded Resources in an Assembly</title>
      <link>/PreviewSnippet.aspx?SnippetID=b5ce02dc-802a-48ed-979c-848fa87879f6</link>
      <description>Getting the Names of all Embedded Resources in an Assembly [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 11 May 2005 13:08:23 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=b5ce02dc-802a-48ed-979c-848fa87879f6#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Getting the Names of all Embedded Resources in an Assembly</dc:title>
      <dc:date>5/11/2005 1:08:23 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>string[] resourceNames = this.GetType().Assembly.GetManifestResourceNames();
foreach(string resourceName in resourceNames)
{
    System.Diagnostics.Trace.WriteLine(resourceName);
}
</pre>]]></content:encoded>
      <snippet:downloads>35</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a00379ff-9424-4d1c-a964-85615e69671e</guid>
      <title>A generic sorter for strongly-typed collections</title>
      <link>/PreviewSnippet.aspx?SnippetID=a00379ff-9424-4d1c-a964-85615e69671e</link>
      <description>A generic sorter for strongly-typed collections [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 20 May 2005 21:20:25 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a00379ff-9424-4d1c-a964-85615e69671e#comments</comments>
      <category>f8b47dd5-9f0a-4831-b7ad-ae8d5083baf3</category>
      <dc:title>A generic sorter for strongly-typed collections</dc:title>
      <dc:date>5/20/2005 9:20:25 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Collections;
using System.Globalization;
using System.Reflection; 
namespace CodeXchangeSamples
{
    /// <SUMMARY>
    /// A generic sorter, inheriting from IComparer, 
    /// intended to allow for the sorting of
    /// strongly-typed collections on any named public property
    /// which implements IComparable
    /// </SUMMARY>
    public class GenericSorter : IComparer
    {
        string sortPropertyName;
        SortOrder sortOrder;
        public GenericSorter(string sortPropertyName)
        {
            this.sortPropertyName=sortPropertyName;
            this.sortOrder=SortOrder.Ascending;    
                                // default to ascending order
        }
        public GenericSorter(string sortPropertyName, 
                                           SortOrder sortOrder)
        {
            this.sortPropertyName=sortPropertyName;
            this.sortOrder=sortOrder;
        }
        public int Compare(object x, object y)
        {
            // Get the values of the relevant property on the
            //  x and y objects
            object valueOfX = x.GetType().
                 GetProperty(sortPropertyName).GetValue(x,null);
            object valueOfY = y.GetType().
                 GetProperty(sortPropertyName).GetValue(y,null);
            // Do the comparison
            if (sortOrder==SortOrder.Ascending)
            {
             return ((IComparable)valueOfX).CompareTo(valueOfY); 
            }
            else
            {
             return ((IComparable)valueOfY).CompareTo(valueOfX);
            }
        }
    }
    /// 
    /// Enumerator to indicate whether to sort in ascending or
    /// descending order
    /// 
    public enum SortOrder
    {
        Ascending,
        Descending
    }
}
//To use this class, within a collection which inherits from System.Collections.CollectionBase, we just //need to expose a Sort() method along the lines of:
public void Sort(string sortPropertyName, SortOrder sortOrder)
{
   InnerList.Sort(new CodeXchangeSamples(sortPropertyName,sortOrder));
}
</pre>]]></content:encoded>
      <snippet:downloads>13</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=33ee3564-b83d-4335-8fb7-86aca1496765</guid>
      <title>Ping is a very useful utility used to determine the speed of a Network Connection.</title>
      <link>/PreviewSnippet.aspx?SnippetID=33ee3564-b83d-4335-8fb7-86aca1496765</link>
      <description>Ping is a very useful utility used to determine the speed of a Network Connection. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 23 Jun 2005 15:52:04 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=33ee3564-b83d-4335-8fb7-86aca1496765#comments</comments>
      <category>edde3ea1-24a6-4cb0-8446-ab91e1800116</category>
      <dc:title>Ping is a very useful utility used to determine the speed of a Network Connection.</dc:title>
      <dc:date>6/23/2005 3:52:04 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>namespace SaurabhPing
{
  using System;
  using System.Net;
  using System.Net.Sockets;
  /// <summary>
  ///		The Main Ping Class
  /// </summary>
  class Ping
  {
    //Declare some Constant Variables
    const int SOCKET_ERROR = -1;        
    const int ICMP_ECHO = 8;
    /// <summary>
    ///		The Starting Point of the Class
    ///		It Takes the Hostname parameter
    /// </summary>
    public static void Main(string[] argv)
    {
      if(argv.Length==0)
      {
	//If user did not enter any Parameter inform him
	Console.WriteLine("Usage:Ping <hostname> /r") ;
	Console.WriteLine("<hostname> The name of the Host who you want to ping");
	Console.WriteLine("/r Ping the host continuously") ;
      }
      else if(argv.Length==1)
      {
	//Just the hostname provided by the user
	//call the method "PingHost" and pass the HostName as a parameter
	PingHost(argv[0]) ;
      }
      else if(argv.Length==2)
      {
	//the user provided the hostname and the switch
	if(argv[1]=="/r")
	{
	  //loop the ping program
	  while(true)
	  {
		//call the method "PingHost" and pass the HostName as a parameter
		PingHost(argv[0]) ;
	  }
        }
	else
	{
	  //if the user provided some other switch
	  PingHost(argv[0]) ;
	 }
       }
       else
       {
	 //Some error occurred
	 Console.WriteLine("Error in Arguments") ;
        }
     }
		
      /// <summary>
      ///		This method takes the "hostname" of the server
      ///		and then it ping's it and shows the response time
      /// </summary>
      public static void PingHost(string host)
      {
	//Declare the IPHostEntry 
	IPHostEntry serverHE, fromHE;
	int nBytes = 0;
	int dwStart = 0, dwStop = 0;
	//Initilize a Socket of the Type ICMP
	Socket socket = 
	new Socket(AddressFamily.AfINet, SocketType.SockRaw, ProtocolType.ProtICMP);
	
	// Get the server endpoint
	try
	{
	  serverHE = DNS.GetHostByName(host);	
	}
	catch(Exception)
	{
	  Console.WriteLine("Host not found"); // fail
	  return ;
	}
	// Convert the server IP_EndPoint to an EndPoint
	IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0);
	EndPoint epServer = (ipepServer);	
	// Set the receiving endpoint to the client machine
	fromHE = DNS.GetHostByName(DNS.GetHostName());
	IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0);        
	EndPoint EndPointFrom = (ipEndPointFrom);
	int PacketSize = 0;
	IcmpPacket packet = new IcmpPacket();
	// Construct the packet to send
	packet.Type = ICMP_ECHO; //8
	packet.SubCode = 0;
	packet.CheckSum = UInt16.Parse("0");
	packet.Identifier   = UInt16.Parse("45"); 
	packet.SequenceNumber  = UInt16.Parse("0"); 
	int PingData = 32; // sizeof(IcmpPacket) - 8;
	packet.Data = new Byte[PingData];
	//Initilize the Packet.Data
	for (int i = 0; i < PingData; i++)
	{
	  packet.Data[i] = (byte)'#';
	}
	             
	//Variable to hold the total Packet size
	PacketSize = PingData + 8;
	Byte [] icmp_pkt_buffer = new Byte[ PacketSize ]; 
	Int32 Index = 0;
	//Call a Method Serialize which counts
	//The total number of Bytes in the Packet
	Index = Serialize(  
	                  packet, 
	                 icmp_pkt_buffer, 
	                  PacketSize, 
	                   PingData );
	//Error in Packet Size
	if( Index == -1 )
	{
	  Console.WriteLine("Error in Making Packet");
	  return ;
	}
          
	// now get this critter into a UInt16 array
	         
	//Get the Half size of the Packet
	Double double_length = Convert.ToDouble(Index);
	Double dtemp = Math.Ceil( double_length / 2);
	int cksum_buffer_length = Convert.ToInt32(dtemp);
	//Create a Byte Array
	UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length];
	//Code to initialize the Uint16 array 
	int icmp_header_buffer_index = 0;
	for( int i = 0; i < cksum_buffer_length; i++ ) {
	  cksum_buffer[i] = 
	        BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);
	  icmp_header_buffer_index += 2;
	}
	//Call a method which will return a checksum             
	UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);
	//Save the checksum to the Packet
	packet.CheckSum  = u_cksum; 
	            
	// Now that we have the checksum, serialize the packet again
	Byte [] sendbuf = new Byte[ PacketSize ]; 
	//again check the packet size
	Index = Serialize(  
	                  packet, 
	                  sendbuf, 
	                  PacketSize, 
	                  PingData );
	//if there is a error report it
	if( Index == -1 )
	{
	  Console.WriteLine("Error in Making Packet");
	  return ;
	}
	                
	dwStart = System.Environment.TickCount; // Start timing
	//send the Pack over the socket
	if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) 
	{		
	  Console.WriteLine("Socket Error cannot Send Packet");
	}
	// Initialize the buffers. The receive buffer is the size of the
	// ICMP header plus the IP header (20 bytes)
	Byte [] ReceiveBuffer = new Byte[256]; 
	nBytes = 0;
	//Receive the bytes
	bool recd =false ;
	int timeout=0 ;
 
	//loop for checking the time of the server responding 
	while(!recd)
	{
	  nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom);
	  if (nBytes == SOCKET_ERROR) 
	  {
	    Console.WriteLine("Host not Responding") ;
	    recd=true ;
	    break;
	  }
	  else if(nBytes>0)
	  {
	    dwStop = System.Environment.TickCount - dwStart; // stop timing
	    Console.WriteLine("Reply from "+epServer.ToString()+" in "
		+dwStop+"MS :Bytes Received"+nBytes);
	    recd=true;
	    break;
	  }
	  timeout=System.Environment.TickCount - dwStart;
	  if(timeout>1000)
	  {
	    Console.WriteLine("Time Out") ;
	    recd=true;
	  }
        }
	            
	//close the socket
	socket.Close();     
      }
      /// <summary>
      ///  This method get the Packet and calculates the total size 
      ///  of the Pack by converting it to byte array
      /// </summary>
      public static Int32 Serialize(IcmpPacket packet, Byte[] Buffer,
			Int32 PacketSize, Int32 PingData )
      {
	Int32 cbReturn = 0;
	// serialize the struct into the array
	int Index=0;
	Byte [] b_type = new Byte[1];
	b_type[0] = (packet.Type);
	Byte [] b_code = new Byte[1];
	b_code[0] = (packet.SubCode);
	Byte [] b_cksum = BitConverter.GetBytes(packet.CheckSum);
	Byte [] b_id = BitConverter.GetBytes(packet.Identifier);
	Byte [] b_seq = BitConverter.GetBytes(packet.SequenceNumber);
	        
	// Console.WriteLine("Serialize type ");
	Array.Copy( b_type, 0, Buffer, Index, b_type.Length );
	Index += b_type.Length;
	        
	// Console.WriteLine("Serialize code ");
	Array.Copy( b_code, 0, Buffer, Index, b_code.Length );
	Index += b_code.Length;
	// Console.WriteLine("Serialize cksum ");
	Array.Copy( b_cksum, 0, Buffer, Index, b_cksum.Length );
	Index += b_cksum.Length;
	// Console.WriteLine("Serialize id ");
	Array.Copy( b_id, 0, Buffer, Index, b_id.Length );
	Index += b_id.Length;
	Array.Copy( b_seq, 0, Buffer, Index, b_seq.Length );
	Index += b_seq.Length;
	// copy the data	        
	Array.Copy( packet.Data, 0, Buffer, Index, PingData );
	Index += PingData;
	if( Index != PacketSize/* sizeof(IcmpPacket)  */) {
	  cbReturn = -1;
	  return cbReturn;
	}
	cbReturn = Index;
	return cbReturn;
      }
      /// <summary>
      ///		This Method has the algorithm to make a checksum 
      /// </summary>
      public static UInt16 checksum( UInt16[] buffer, int size )
      {
	Int32 cksum = 0;
	int counter;
 	counter = 0;
	while ( size > 0 ) {
          UInt16 val = buffer[counter];
	  cksum += Convert.ToInt32( buffer[counter] );
	  counter += 1;
	  size -= 1;
	}
	cksum = (cksum >> 16) + (cksum & 0xffff);
	cksum += (cksum >> 16);
	return (UInt16)(~cksum);
      }
    } // class ping
    /// <summary>
    ///		Class that holds the Pack information
    /// </summary>
    public class IcmpPacket 
    { 
       public Byte  Type;    // type of message
       public Byte  SubCode;    // type of sub code
       public UInt16 CheckSum;   // ones complement checksum of struct
       public UInt16 Identifier;      // identifier
       public UInt16 SequenceNumber;     // sequence number  
       public Byte [] Data;
     } // class IcmpPacket
}</pre>]]></content:encoded>
      <snippet:downloads>9</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=dcb60b4d-9659-4e07-afc6-884220d409b5</guid>
      <title>Using the XP Photo Printing Wizard to print one or more photos.</title>
      <link>/PreviewSnippet.aspx?SnippetID=dcb60b4d-9659-4e07-afc6-884220d409b5</link>
      <description>Using the XP Photo Printing Wizard to print one or more photos. [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 05 Jun 2005 00:21:28 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=dcb60b4d-9659-4e07-afc6-884220d409b5#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Using the XP Photo Printing Wizard to print one or more photos.</dc:title>
      <dc:date>6/5/2005 12:21:28 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>' Uses the XP Photo Printing Wizard to print one or more photos.
' The implementation of the photo wizard is in photowiz.dll but the 
' interface is not exposed. Instead, Microsoft provides the Windows 
' Image Acquisition Library (WIA). 
'
' Use late binding incase the user does not have the WIA component
' installed (and easier for developers to use the source if it's
' not installed).
' use late binding for this source file
Option Strict Off
Public NotInheritable Class Print
	' const values
	Private Class Consts
		Public Const DialogProgId As String = "WIA.CommonDialog"
		Public Const VectorProgId As String = "WIA.Vector"
	End Class
	' static class
	Private Sub New()
	End Sub
	' public methods
	' print the specified photo (full path to the photo)
	Public Shared Sub PrintFile(ByVal file As String)
		PrintFiles(New String() {file})
	End Sub
	' print the list of photos
	Public Shared Sub PrintFiles(ByVal photos() As Photo)
		' convert to a string array
		Dim files(photos.Length - 1) As String
		For i As Integer = 0 To files.Length - 1
			files(i) = photos(i).PhotoPath
		Next
		PrintFiles(files)
	End Sub
	' print the list of files
	Public Shared Sub PrintFiles(ByVal files() As String)
		Try
			' create the vector COM object
			Dim vector As Object = CreateObject(Consts.VectorProgId)
			' add files to the vector object
			For Each file As String In files
				vector.Add(file)
			Next
			' create the common dialog COM object, and
			' display the photo print wizard
			Dim dialog As Object = CreateObject(Consts.DialogProgId)
			dialog.ShowPhotoPrintingWizard(vector)
			vector = Nothing
			dialog = Nothing
		Catch ex As Exception
			Global.DisplayError("The photo could not be printed.", ex)
		End Try
	End Sub
End Class</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=fc999b16-d8b8-4626-8b88-8b93d2267c0b</guid>
      <title>Generates random password, which complies with the strong password rules</title>
      <link>/PreviewSnippet.aspx?SnippetID=fc999b16-d8b8-4626-8b88-8b93d2267c0b</link>
      <description>Generates random password, which complies with the strong password rules [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 16 Aug 2005 13:02:38 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=fc999b16-d8b8-4626-8b88-8b93d2267c0b#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Generates random password, which complies with the strong password rules</dc:title>
      <dc:date>8/16/2005 1:02:38 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Generates random password, which complies with the strong password
//         rules and does not contain ambiguous characters.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// Copyright (C) Obviex(TM). All rights reserved.
// 
using System;
using System.Security.Cryptography;
/// <summary>
/// This class can generate random passwords, which do not include ambiguous 
/// characters, such as I, l, and 1. The generated password will be made of
/// 7-bit ASCII symbols. Every four characters will include one lower case
/// character, one upper case character, one number, and one special symbol
/// (such as '%') in a random order. The password will always start with an
/// alpha-numeric character; it will not start with a special symbol (we do
/// this because some back-end systems do not like certain special
/// characters in the first position).
/// </summary>
public class RandomPassword
{
    // Define default min and max password lengths.
    private static int DEFAULT_MIN_PASSWORD_LENGTH  = 8;
    private static int DEFAULT_MAX_PASSWORD_LENGTH  = 10;
    // Define supported password characters divided into groups.
    // You can add (or remove) characters to (from) these groups.
    private static string PASSWORD_CHARS_LCASE  = "abcdefgijkmnopqrstwxyz";
    private static string PASSWORD_CHARS_UCASE  = "ABCDEFGHJKLMNPQRSTWXYZ";
    private static string PASSWORD_CHARS_NUMERIC= "23456789";
    private static string PASSWORD_CHARS_SPECIAL= "*$-+?_&=!%{}/";
    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random. It will be no shorter than the minimum default and
    /// no longer than maximum default.
    /// </remarks>
    public static string Generate()
    {
        return Generate(DEFAULT_MIN_PASSWORD_LENGTH, 
                        DEFAULT_MAX_PASSWORD_LENGTH);
    }
    /// <summary>
    /// Generates a random password of the exact length.
    /// </summary>
    /// <param name="length">
    /// Exact password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    public static string Generate(int length)
    {
        return Generate(length, length);
    }
    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <param name="minLength">
    /// Minimum password length.
    /// </param>
    /// <param name="maxLength">
    /// Maximum password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random and it will fall with the range determined by the
    /// function parameters.
    /// </remarks>
    public static string Generate(int   minLength,
                                  int   maxLength)
    {
        // Make sure that input parameters are valid.
        if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
            return null;
        // Create a local array containing supported password characters
        // grouped by types. You can remove character groups from this
        // array, but doing so will weaken the password strength.
        char[][] charGroups = new char[][] 
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
            PASSWORD_CHARS_SPECIAL.ToCharArray()
        };
        // Use this array to track the number of unused characters in each
        // character group.
        int[] charsLeftInGroup = new int[charGroups.Length];
        // Initially, all characters in each group are not used.
        for (int i=0; i<charsLeftInGroup.Length; i++)
            charsLeftInGroup[i] = charGroups[i].Length;
        
        // Use this array to track (iterate through) unused character groups.
        int[] leftGroupsOrder = new int[charGroups.Length];
        // Initially, all character groups are not used.
        for (int i=0; i<leftGroupsOrder.Length; i++)
            leftGroupsOrder[i] = i;
        // Because we cannot use the default randomizer, which is based on the
        // current time (it will produce the same "random" number within a
        // second), we will use a random number generator to seed the
        // randomizer.
        
        // Use a 4-byte array to fill it with random bytes and convert it then
        // to an integer value.
        byte[] randomBytes = new byte[4];
        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);
        // Convert 4 bytes into a 32-bit integer value.
        int seed = (randomBytes[0] & 0x7f) << 24 |
                    randomBytes[1]         << 16 |
                    randomBytes[2]         <<  8 |
                    randomBytes[3];
        // Now, this is real randomization.
        Random  random  = new Random(seed);
        // This array will hold password characters.
        char[] password = null;
        // Allocate appropriate memory for the password.
        if (minLength < maxLength)
            password = new char[random.Next(minLength, maxLength+1)];
        else
            password = new char[minLength];
        // Index of the next character to be added to password.
        int nextCharIdx;
        
        // Index of the next character group to be processed.
        int nextGroupIdx;
        // Index which will be used to track not processed character groups.
        int nextLeftGroupsOrderIdx;
        
        // Index of the last non-processed character in a group.
        int lastCharIdx;
        // Index of the last non-processed group.
        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
        
        // Generate password characters one at a time.
        for (int i=0; i<password.Length; i++)
        {
            // If only one character group remained unprocessed, process it;
            // otherwise, pick a random character group from the unprocessed
            // group list. To allow a special character to appear in the
            // first position, increment the second parameter of the Next
            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
            if (lastLeftGroupsOrderIdx == 0)
                nextLeftGroupsOrderIdx = 0;
            else
                nextLeftGroupsOrderIdx = random.Next(0, 
                                                     lastLeftGroupsOrderIdx);
            // Get the actual index of the character group, from which we will
            // pick the next character.
            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
            // Get the index of the last unprocessed characters in this group.
            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
            
            // If only one unprocessed character is left, pick it; otherwise,
            // get a random character from the unused character list.
            if (lastCharIdx == 0)
                nextCharIdx = 0;
            else
                nextCharIdx = random.Next(0, lastCharIdx+1);
            // Add this character to the password.
            password[i] = charGroups[nextGroupIdx][nextCharIdx];
            
            // If we processed the last character in this group, start over.
            if (lastCharIdx == 0)
                charsLeftInGroup[nextGroupIdx] = 
                                          charGroups[nextGroupIdx].Length;
            // There are more unprocessed characters left.
            else
            {
                // Swap processed character with the last unprocessed character
                // so that we don't pick it until we process all characters in
                // this group.
                if (lastCharIdx != nextCharIdx)
                {
                    char temp = charGroups[nextGroupIdx][lastCharIdx];
                    charGroups[nextGroupIdx][lastCharIdx] = 
                                charGroups[nextGroupIdx][nextCharIdx];
                    charGroups[nextGroupIdx][nextCharIdx] = temp;
                }
                // Decrement the number of unprocessed characters in
                // this group.
                charsLeftInGroup[nextGroupIdx]--;
            }
            // If we processed the last group, start all over.
            if (lastLeftGroupsOrderIdx == 0)
                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // There are more unprocessed groups left.
            else
            {
                // Swap processed group with the last unprocessed group
                // so that we don't pick it until we process all groups.
                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                {
                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                    leftGroupsOrder[lastLeftGroupsOrderIdx] = 
                                leftGroupsOrder[nextLeftGroupsOrderIdx];
                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                }
                // Decrement the number of unprocessed groups.
                lastLeftGroupsOrderIdx--;
            }
        }
        // Convert password characters into a string and return the result.
        return new string(password);
     }
}
/// <summary>
/// Illustrates the use of the RandomPassword class.
/// </summary>
public class RandomPasswordTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        // Print 100 randomly generated passwords (8-to-10 char long).
        for (int i=0; i<100; i++)
            Console.WriteLine(RandomPassword.Generate(8, 10));
    }
}</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=1e4184f9-80e9-494d-83ec-8bc44f97c92b</guid>
      <title>Obtaining Active Directory User Information Using System.DirectoryServices</title>
      <link>/PreviewSnippet.aspx?SnippetID=1e4184f9-80e9-494d-83ec-8bc44f97c92b</link>
      <description>Obtaining Active Directory User Information Using System.DirectoryServices [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 05 Apr 2005 21:44:02 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=1e4184f9-80e9-494d-83ec-8bc44f97c92b#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Obtaining Active Directory User Information Using System.DirectoryServices</dc:title>
      <dc:date>4/5/2005 9:44:02 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public static string GetUserInfo(string user, string propertyName)
{
    DirectoryEntry adRootDSE = new DirectoryEntry("LDAP://rootDSE");
    DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + (string)adRootDSE.Properties["defaultNamingContext"].Value);
    DirectorySearcher searcher = new DirectorySearcher(adRoot);
    searcher.Filter = "(&(objectClass=user)(samAccountName=" + user + "))";
    SearchResult result = searcher.FindOne();
    if (result == null)
        return "null";
    ResultPropertyValueCollection values = result.Properties[propertyName];
    return ((values != null) && (values.Count > 0)) ? values[0].ToString() : "null";
}
///Example use for this function:
string firstName = ActiveDirectory.GetUserInfo(userName, "givenName");
string middleName = ActiveDirectory.GetUserInfo(userName, "middleName");
string lastName = ActiveDirectory.GetUserInfo(userName, "sn");
string primaryMail = ActiveDirectory.GetUserInfo(userName, "mail");
string secondaryMail = ActiveDirectory.GetUserInfo(userName, "otherMailbox");
string phoneWork = ActiveDirectory.GetUserInfo(userName, "telephoneNumber");
string phoneHome = ActiveDirectory.GetUserInfo(userName, "homePhone");
string phoneMobile = ActiveDirectory.GetUserInfo(userName, "mobile");
string phonePager = ActiveDirectory.GetUserInfo(userName, "pager");
string fax = ActiveDirectory.GetUserInfo(userName, "facsimileTelephoneNumber");
string www = ActiveDirectory.GetUserInfo(userName, "wwwHomePage");
string company = ActiveDirectory.GetUserInfo(userName, "company");
string department = ActiveDirectory.GetUserInfo(userName, "department");</pre>]]></content:encoded>
      <snippet:downloads>20</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=22daa448-19f6-4ce8-b57e-8f437ae2e5f9</guid>
      <title>Hashing data with salt using MD5 and several SHA algorithms.</title>
      <link>/PreviewSnippet.aspx?SnippetID=22daa448-19f6-4ce8-b57e-8f437ae2e5f9</link>
      <description>Hashing data with salt using MD5 and several SHA algorithms. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 16 Aug 2005 13:07:48 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=22daa448-19f6-4ce8-b57e-8f437ae2e5f9#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>Hashing data with salt using MD5 and several SHA algorithms.</dc:title>
      <dc:date>8/16/2005 1:07:48 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Hashing data with salt using MD5 and several SHA algorithms.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// Copyright (C) Obviex(TM). All rights reserved.
// 
using System;
using System.Text;
using System.Security.Cryptography;
/// <summary>
/// This class generates and compares hashes using MD5, SHA1, SHA256, SHA384, 
/// and SHA512 hashing algorithms. Before computing a hash, it appends a
/// randomly generated salt to the plain text, and stores this salt appended
/// to the result. To verify another plain text value against the given hash,
/// this class will retrieve the salt value from the hash string and use it
/// when computing a new hash of the plain text. Appending a salt value to
/// the hash may not be the most efficient approach, so when using hashes in
/// a real-life application, you may choose to store them separately. You may
/// also opt to keep results as byte arrays instead of converting them into
/// base64-encoded strings.
/// </summary>
public class SimpleHash
{
    /// <summary>
    /// Generates a hash for the given plain text value and returns a
    /// base64-encoded result. Before the hash is computed, a random salt
    /// is generated and appended to the plain text. This salt is stored at
    /// the end of the hash value, so it can be used later for hash
    /// verification.
    /// </summary>
    /// <param name="plainText">
    /// Plaintext value to be hashed. The function does not check whether
    /// this parameter is null.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
    /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
    /// MD5 hashing algorithm will be used). This value is case-insensitive.
    /// </param>
    /// <param name="saltBytes">
    /// Salt bytes. This parameter can be null, in which case a random salt
    /// value will be generated.
    /// </param>
    /// <returns>
    /// Hash value formatted as a base64-encoded string.
    /// </returns>
    public static string ComputeHash(string   plainText,
                                     string   hashAlgorithm,
                                     byte[]   saltBytes)
    {
        // If salt is not specified, generate it on the fly.
        if (saltBytes == null)
        {
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;
            // Generate a random number for the size of the salt.
            Random  random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);
            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];
            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes); 
        }
        
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        
        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes = 
                new byte[plainTextBytes.Length + saltBytes.Length];
        // Copy plain text bytes into resulting array.
        for (int i=0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];
        
        // Append salt bytes to the resulting array.
        for (int i=0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
        // Because we support multiple hashing algorithms, we must define
        // hash object as a common (abstract) base class. We will specify the
        // actual hashing algorithm class later during object creation.
        HashAlgorithm hash;
        
        // Make sure hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";
        
        // Initialize appropriate hashing algorithm class.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;
            case "SHA256":
                hash = new SHA256Managed();
                break;
            case "SHA384":
                hash = new SHA384Managed();
                break;
            case "SHA512":
                hash = new SHA512Managed();
                break;
            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }
        
        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
        
        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length + 
                                            saltBytes.Length];
        
        // Copy hash bytes into resulting array.
        for (int i=0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];
            
        // Append salt bytes to the result.
        for (int i=0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            
        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);
        
        // Return the result.
        return hashValue;
    }
    /// <summary>
    /// Compares a hash of the specified plain text value to a given hash
    /// value. Plain text is hashed with the same salt value as the original
    /// hash.
    /// </summary>
    /// <param name="plainText">
    /// Plain text to be verified against the specified hash. The function
    /// does not check whether this parameter is null.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", 
    /// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
    /// MD5 hashing algorithm will be used). This value is case-insensitive.
    /// </param>
    /// <param name="hashValue">
    /// Base64-encoded hash value produced by ComputeHash function. This value
    /// includes the original salt appended to it.
    /// </param>
    /// <returns>
    /// If computed hash mathes the specified hash the function the return
    /// value is true; otherwise, the function returns false.
    /// </returns>
    public static bool VerifyHash(string   plainText,
                                  string   hashAlgorithm,
                                  string   hashValue)
    {
        // Convert base64-encoded hash value into a byte array.
        byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
        
        // We must know size of hash (without salt).
        int hashSizeInBits, hashSizeInBytes;
        
        // Make sure that hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";
        
        // Size of hash is based on the specified algorithm.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hashSizeInBits = 160;
                break;
            case "SHA256":
                hashSizeInBits = 256;
                break;
            case "SHA384":
                hashSizeInBits = 384;
                break;
            case "SHA512":
                hashSizeInBits = 512;
                break;
            default: // Must be MD5
                hashSizeInBits = 128;
                break;
        }
        // Convert size of hash from bits to bytes.
        hashSizeInBytes = hashSizeInBits / 8;
        // Make sure that the specified hash value is long enough.
        if (hashWithSaltBytes.Length < hashSizeInBytes)
            return false;
        // Allocate array to hold original salt bytes retrieved from hash.
        byte[] saltBytes = new byte[hashWithSaltBytes.Length - 
                                    hashSizeInBytes];
        // Copy salt from the end of the hash to the new array.
        for (int i=0; i < saltBytes.Length; i++)
            saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];
        // Compute a new hash string.
        string expectedHashString = 
                    ComputeHash(plainText, hashAlgorithm, saltBytes);
        // If the computed hash matches the specified hash,
        // the plain text value must be correct.
        return (hashValue == expectedHashString);
    }
}
/// <summary>
/// Illustrates the use of the SimpleHash class.
/// </summary>
public class SimpleHashTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        string password      = "myP@5sw0rd";  // original password
        string wrongPassword = "password";    // wrong password
 
        string passwordHashMD5 = 
               SimpleHash.ComputeHash(password, "MD5", null);
        string passwordHashSha1 = 
               SimpleHash.ComputeHash(password, "SHA1", null);
        string passwordHashSha256 = 
               SimpleHash.ComputeHash(password, "SHA256", null);
        string passwordHashSha384 = 
               SimpleHash.ComputeHash(password, "SHA384", null);
        string passwordHashSha512 = 
               SimpleHash.ComputeHash(password, "SHA512", null);
        Console.WriteLine("COMPUTING HASH VALUES\r\n");
        Console.WriteLine("MD5   : {0}", passwordHashMD5);
        Console.WriteLine("SHA1  : {0}", passwordHashSha1);
        Console.WriteLine("SHA256: {0}", passwordHashSha256);
        Console.WriteLine("SHA384: {0}", passwordHashSha384);
        Console.WriteLine("SHA512: {0}", passwordHashSha512);
        Console.WriteLine("");
        Console.WriteLine("COMPARING PASSWORD HASHES\r\n");
        Console.WriteLine("MD5    (good): {0}",
                            SimpleHash.VerifyHash(
                            password, "MD5", 
                            passwordHashMD5).ToString());
        Console.WriteLine("MD5    (bad) : {0}",
                            SimpleHash.VerifyHash(
                            wrongPassword, "MD5", 
                            passwordHashMD5).ToString());
        Console.WriteLine("SHA1   (good): {0}",
                            SimpleHash.VerifyHash(
                            password, "SHA1", 
                            passwordHashSha1).ToString());
        Console.WriteLine("SHA1   (bad) : {0}",
                            SimpleHash.VerifyHash(
                            wrongPassword, "SHA1", 
                            passwordHashSha1).ToString());
        Console.WriteLine("SHA256 (good): {0}",
                            SimpleHash.VerifyHash(
                            password, "SHA256", 
                            passwordHashSha256).ToString());
        Console.WriteLine("SHA256 (bad) : {0}",
                            SimpleHash.VerifyHash(
                            wrongPassword, "SHA256", 
                            passwordHashSha256).ToString());
        Console.WriteLine("SHA384 (good): {0}",
                            SimpleHash.VerifyHash(
                            password, "SHA384", 
                            passwordHashSha384).ToString());
        Console.WriteLine("SHA384 (bad) : {0}", 
                            SimpleHash.VerifyHash(
                            wrongPassword, "SHA384", 
                            passwordHashSha384).ToString());
        Console.WriteLine("SHA512 (good): {0}",
                            SimpleHash.VerifyHash(
                            password, "SHA512", 
                            passwordHashSha512).ToString());
        Console.WriteLine("SHA512 (bad) : {0}",
                            SimpleHash.VerifyHash(
                            wrongPassword, "SHA512", 
                            passwordHashSha512).ToString());
    }
}
</pre>]]></content:encoded>
      <snippet:downloads>13</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=368ba387-97b4-4d1d-8440-90089e9984b6</guid>
      <title>WallPaper class used to set the Windows Wallpaper.</title>
      <link>/PreviewSnippet.aspx?SnippetID=368ba387-97b4-4d1d-8440-90089e9984b6</link>
      <description>WallPaper class used to set the Windows Wallpaper. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 28 Aug 2005 20:28:34 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=368ba387-97b4-4d1d-8440-90089e9984b6#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>WallPaper class used to set the Windows Wallpaper.</dc:title>
      <dc:date>8/28/2005 8:28:34 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>    /// <summary>
    /// WallPaper class used to set the Windows Wallpaper. This code was originally taken from Steve Dunn's example
    /// http://www.codeproject.com/dotnet/SettingWallpaperDotNet.asp
    /// </summary>
    public sealed class Wallpaper
    {
        Wallpaper() { }
        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        public enum Style : int
        {
            Tiled,
            Centered,
            Stretched
        }
        public static void SetWallpaper(Image img, Style style)
        {
            string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
            img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            if (style == Style.Stretched)
            {
                key.SetValue(@"WallpaperStyle", 2.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }
            else if (style == Style.Centered)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }
            else if (style == Style.Tiled)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 1.ToString());
            }
            SystemParametersInfo(SPI_SETDESKWALLPAPER,
                0,
                tempPath,
                SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
    }      
</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=344ac53a-04a0-44ce-ad79-928b2c1a1201</guid>
      <title>MD5 String Hash</title>
      <link>/PreviewSnippet.aspx?SnippetID=344ac53a-04a0-44ce-ad79-928b2c1a1201</link>
      <description>MD5 String Hash [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:33:40 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=344ac53a-04a0-44ce-ad79-928b2c1a1201#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>MD5 String Hash</dc:title>
      <dc:date>4/15/2005 6:33:40 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.Text
Imports System.Security.Cryptography 
Public Function GenerateMD5Hash(ByVal StrPassword As String) As String
Dim Ue As New UnicodeEncoding
Dim ByteSourceText() As Byte = Ue.GetBytes(StrPassword)
Dim Md5 As New MD5CryptoServiceProvider
Dim ByteHash() As Byte = Md5.ComputeHash(ByteSourceText)
Return Convert.ToBase64String(ByteHash)
End Function</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=2e178ad1-0fbd-48e8-88b5-96e781c39d77</guid>
      <title>Remote host information</title>
      <link>/PreviewSnippet.aspx?SnippetID=2e178ad1-0fbd-48e8-88b5-96e781c39d77</link>
      <description>Remote host information [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:57:34 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=2e178ad1-0fbd-48e8-88b5-96e781c39d77#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>Remote host information</dc:title>
      <dc:date>4/9/2005 1:57:34 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Net;
class ResolveIt
{
public static void Main(string[] argv)
{
if (argv.Length != 1)
{
Console.WriteLine("Usage: ResolveIt address");
return;
}
IPHostEntry iphe = Dns.Resolve(argv[0]);
Console.WriteLine("Information for {0}", argv[0]);
Console.WriteLine("Host name: {0}", iphe.HostName);
foreach(string alias in iphe.Aliases)
{
Console.WriteLine("Alias: {0}", alias);
}
foreach(IPAddress address in iphe.AddressList)
{
Console.WriteLine("Address: {0}",
address.ToString());
}
}
}</pre>]]></content:encoded>
      <snippet:downloads>9</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=43ebf9dd-d8ef-4867-a112-97762e65fc75</guid>
      <title>Sending non US-ASCII emails</title>
      <link>/PreviewSnippet.aspx?SnippetID=43ebf9dd-d8ef-4867-a112-97762e65fc75</link>
      <description>Sending non US-ASCII emails [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 11:33:47 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=43ebf9dd-d8ef-4867-a112-97762e65fc75#comments</comments>
      <category>9f0117ac-b4a8-45e1-a41f-d78807524b04</category>
      <dc:title>Sending non US-ASCII emails</dc:title>
      <dc:date>4/9/2005 11:33:47 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>MailMessage mail = new MailMessage();
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "Some Chinese characters or text goes here";
mail.BodyEncoding = System.Text.Encoding.GetEncoding( "GB2312" ); //set the proper character set here
SmtpMail.SmtpServer = "localhost";  //your real server goes here
SmtpMail.Send( mail );</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=4ea10682-f6cd-45f4-a267-a3e9c7cf07a0</guid>
      <title>Open a web page from a Windows Forms application</title>
      <link>/PreviewSnippet.aspx?SnippetID=4ea10682-f6cd-45f4-a267-a3e9c7cf07a0</link>
      <description>Open a web page from a Windows Forms application [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 05 Apr 2005 21:39:01 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=4ea10682-f6cd-45f4-a267-a3e9c7cf07a0#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Open a web page from a Windows Forms application</dc:title>
      <dc:date>4/5/2005 9:39:01 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Process proc = new Process(); 
proc.StartInfo.UseShellExecute = true; 
proc.StartInfo.FileName = @"http://www.microsoft.com"; 
proc.Start(); 
// or just put it all as one statement 
System.Diagnostics.Process.Start(@"http://www.microsoft.com"); </pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=d8b8ae97-8cb6-49f4-934b-a7eb0b573200</guid>
      <title>Allow only Numbers in a Textbox Control</title>
      <link>/PreviewSnippet.aspx?SnippetID=d8b8ae97-8cb6-49f4-934b-a7eb0b573200</link>
      <description>Allow only Numbers in a Textbox Control [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:45:02 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=d8b8ae97-8cb6-49f4-934b-a7eb0b573200#comments</comments>
      <category>1d8fc1e9-bf77-4c63-a26a-6cdedfb43eaf</category>
      <dc:title>Allow only Numbers in a Textbox Control</dc:title>
      <dc:date>4/6/2005 1:45:02 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        'Allow only numbers when someone types in a textbox control
        'Add a textbox to the form and name is: txt . Then put the following 
        'code in the Key_Press event of the textbox control.
        If e.KeyChar.IsNumber(e.KeyChar) = False Then
            e.Handled = True
        End If
</pre>]]></content:encoded>
      <snippet:downloads>8</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=80686275-2f90-460a-9db8-ac23a080deb1</guid>
      <title>Output DataSet as XML</title>
      <link>/PreviewSnippet.aspx?SnippetID=80686275-2f90-460a-9db8-ac23a080deb1</link>
      <description>Output DataSet as XML [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 18 May 2006 07:36:23 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=80686275-2f90-460a-9db8-ac23a080deb1#comments</comments>
      <category>e5dc5661-427e-4d33-8be6-187bd2783223</category>
      <dc:title>Output DataSet as XML</dc:title>
      <dc:date>5/18/2006 7:36:23 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>   Private Sub OutputDataSetAsXML(ByRef dsSource As System.Data.DataSet)

      Dim xmlDoc As System.Xml.XmlDataDocument
      Dim xmlDec As System.Xml.XmlDeclaration
      Dim xmlWriter As System.Xml.XmlWriter

      ' setup response
      Me.Response.Clear()
      Me.Response.ContentType = "text/xml"
      Me.Response.Charset = "utf-8"
      xmlWriter = New System.Xml.XmlTextWriter(Me.Response.OutputStream, System.Text.Encoding.UTF8)

      ' create xml data document with xml declaration
      xmlDoc = New System.Xml.XmlDataDocument(dsSource)
      xmlDoc.DataSet.EnforceConstraints = False
      xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing)
      xmlDoc.PrependChild(xmlDec)

      ' write xml document to response
      xmlDoc.WriteTo(xmlWriter)
      xmlWriter.Flush()
      xmlWriter.Close()
      Response.End()

   End Sub</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=f4a35a1d-af48-40f9-a35b-acd158f18bb7</guid>
      <title>Detect an Visual Studio running instance</title>
      <link>/PreviewSnippet.aspx?SnippetID=f4a35a1d-af48-40f9-a35b-acd158f18bb7</link>
      <description>Detect an Visual Studio running instance [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 14:44:28 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=f4a35a1d-af48-40f9-a35b-acd158f18bb7#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Detect an Visual Studio running instance</dc:title>
      <dc:date>4/6/2005 2:44:28 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
try
{
	foreach(System.Diagnostics.Process p in processes)
	{
		if(p != null && p.MainModule != null)
		{
			String fileName = Path.GetFileName(p.MainModule.FileName);
			if(String.Compare(fileName, "devenv.exe", true) == 0)
				return true;
		}
	}
}
catch
{
}
return false;</pre>]]></content:encoded>
      <snippet:downloads>12</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=1d9eb791-f88c-4ec4-b036-b0c5f1a9434d</guid>
      <title>Validate XML Fragments Against an XML Schema in Visual C#.NET</title>
      <link>/PreviewSnippet.aspx?SnippetID=1d9eb791-f88c-4ec4-b036-b0c5f1a9434d</link>
      <description>Validate XML Fragments Against an XML Schema in Visual C#.NET [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 19 May 2005 19:37:28 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=1d9eb791-f88c-4ec4-b036-b0c5f1a9434d#comments</comments>
      <category>e5dc5661-427e-4d33-8be6-187bd2783223</category>
      <dc:title>Validate XML Fragments Against an XML Schema in Visual C#.NET</dc:title>
      <dc:date>5/19/2005 7:37:28 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Xml;
using System.Xml.Schema;

namespace ConsoleApplication3
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		System.Boolean m_success;
		[STAThread]
		static void Main(string[] args)
		{
			//
			// TODO: Add code to start application here.
			//
			XmlValidatingReader reader  = null;
           XmlSchemaCollection myschema = new XmlSchemaCollection();
			ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors );

			try
			{
				//Create the XML fragment to be parsed.
				String xmlFrag = "<author  xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
					"<first-name>Herman</first-name>" +
					"<last-name>Melville</last-name>" +
					"</author>";
				//Create the XmlParserContext.
				XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
				//Implement the reader.
				reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
				//Add the schema.
				myschema.Add("urn:bookstore-schema", "c:\\Books.xsd");
				//Set the schema type and add the schema to the reader.
				reader.ValidationType = ValidationType.Schema;
				reader.Schemas.Add(myschema);
				while (reader.Read())
				{
				}
				Console.WriteLine("Completed validating xmlfragment");
			}
			catch (XmlException XmlExp)
			{
				Console.WriteLine(XmlExp.Message);
			}
			catch(XmlSchemaException XmlSchExp)
			{
				Console.WriteLine(XmlSchExp.Message);
			}
			catch(Exception GenExp)
			{
				Console.WriteLine(GenExp.Message);
			}
			finally
			{
				Console.Read();
			}
		}
		public static void ShowCompileErrors(object sender, ValidationEventArgs args)
		{
			Console.WriteLine("Validation Error: {0}", args.Message);
		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=3bd802b5-b419-49db-966f-b1db3907124e</guid>
      <title>Basic Error Handling</title>
      <link>/PreviewSnippet.aspx?SnippetID=3bd802b5-b419-49db-966f-b1db3907124e</link>
      <description>Basic Error Handling [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:45:44 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=3bd802b5-b419-49db-966f-b1db3907124e#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Basic Error Handling</dc:title>
      <dc:date>4/6/2005 1:45:44 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        'This shows how to use the Try and Catch method for some error handling. Below is just some random code to test with.
        Dim f As File
        Try
            f.Open("D:\fileDoesNotExistFile.txt", FileMode.Open) 'this will cause a file not found error to be thrown.
        Catch exc As Exception
            MessageBox.Show(exc.Message, " Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 'This will give a description of the error.
        End Try</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=96d9eced-9c6a-477a-a164-b3aa3c37de22</guid>
      <title>Retrieve and format DateTime data</title>
      <link>/PreviewSnippet.aspx?SnippetID=96d9eced-9c6a-477a-a164-b3aa3c37de22</link>
      <description>Retrieve and format DateTime data [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 31 May 2005 00:18:50 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=96d9eced-9c6a-477a-a164-b3aa3c37de22#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Retrieve and format DateTime data</dc:title>
      <dc:date>5/31/2005 12:18:50 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>// retrieve and format date/time data
// tested with VCS.NET 2003
using System;  // has all the date/time stuff
class myApp
{
        public static void Main()
        {
                DateTime CurrTime = DateTime.Now;
                Console.WriteLine("DateTime display listing specifier and result:\n");
                Console.WriteLine("d = {0:d}", CurrTime );  // Short date mm/dd/yyyy
                Console.WriteLine("D = {0:D}", CurrTime );  // Long date day, month dd, yyyy
                Console.WriteLine("f = {0:f}", CurrTime );  // Full date/short time day, month dd, yyyy hh:mm
                Console.WriteLine("F = {0:F}", CurrTime );  // Full date/full time day, month dd, yyyy HH:mm:ss AM/PM
                Console.WriteLine("g = {0:g}", CurrTime );  // Short date/short time mm/dd/yyyy HH:mm
                Console.WriteLine("G = {0:G}", CurrTime );  // Short date/long time mm/dd/yyyy hh:mm:ss
                Console.WriteLine("M = {0:M}", CurrTime );  // Month dd
                Console.WriteLine("R = {0:R}", CurrTime );  // ddd Month yyyy hh:mm:ss GMT
                Console.WriteLine("s = {0:s}", CurrTime );  // yyyy-mm-dd hh:mm:ss  can be sorted!
                Console.WriteLine("t = {0:t}", CurrTime );  // Short time hh:mm AM/PM
                Console.WriteLine("T = {0:T}", CurrTime );  // Long time hh:mm:ss AM/PM
                Console.WriteLine("u = {0:u}", CurrTime );  // yyyy-mm-dd hh:mm:ss  universal/sortable
                Console.WriteLine("U = {0:U}", CurrTime );  // day, month dd, yyyy hh:mm:ss AM/PM
                Console.WriteLine("Y = {0:Y}", CurrTime );  // Month, yyyy
                Console.WriteLine();
                Console.WriteLine("DateTime.Month     = " + CurrTime.Month);      // number of month
                Console.WriteLine("DateTime.DayOfWeek = " + CurrTime.DayOfWeek);  // full name of day
                Console.WriteLine("DateTime.TimeOfDay = " + CurrTime.TimeOfDay);  // 24 hour time
                // number of 100-nanosecond intervals that have elapsed since 1/1/0001, 12:00am
                // useful for time-elapsed measurements
                Console.WriteLine("DateTime.Ticks     = " + CurrTime.Ticks);
                Console.Read();  // wait
        }
}</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ddd21892-de52-4b51-80f7-b606b1298855</guid>
      <title>Regex to split CSV files</title>
      <link>/PreviewSnippet.aspx?SnippetID=ddd21892-de52-4b51-80f7-b606b1298855</link>
      <description>Regex to split CSV files [Regex]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 10 Nov 2005 10:40:31 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ddd21892-de52-4b51-80f7-b606b1298855#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Regex to split CSV files</dc:title>
      <dc:date>11/10/2005 10:40:31 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>/(("(\\\\|\\"|.)*?",?)|(.*?,))|(.+)/</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>Regex</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=d845fa3f-fd9a-40a6-959d-bd0c2ef9c5aa</guid>
      <title>Play a wave file using PlaySound() from the winmm.dll</title>
      <link>/PreviewSnippet.aspx?SnippetID=d845fa3f-fd9a-40a6-959d-bd0c2ef9c5aa</link>
      <description>Play a wave file using PlaySound() from the winmm.dll [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 05 Apr 2005 21:48:41 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=d845fa3f-fd9a-40a6-959d-bd0c2ef9c5aa#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Play a wave file using PlaySound() from the winmm.dll</dc:title>
      <dc:date>4/5/2005 9:48:41 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>                [DllImport("WinMM.dll")]
                public static extern bool  PlaySound(string fname, int Mod, int flag);

                // these are the SoundFlags we are using here, check mmsystem.h for more
                public int SND_ASYNC    = 0x0001;     // play asynchronously
                public int SND_FILENAME = 0x00020000; // use file name
                public int SND_PURGE    = 0x0040;     // purge non-static events

                public void Play(string fname, int SoundFlags)
                {
                        PlaySound(fname, 0, SoundFlags);
                }

                public void StopPlay()
                {
                        PlaySound(null, 0, SND_PURGE);
                }
</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=9cecb710-9690-450e-bdfb-bd4c841af58d</guid>
      <title>Send email from VB.NET</title>
      <link>/PreviewSnippet.aspx?SnippetID=9cecb710-9690-450e-bdfb-bd4c841af58d</link>
      <description>Send email from VB.NET [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:35:48 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=9cecb710-9690-450e-bdfb-bd4c841af58d#comments</comments>
      <category>aeb15495-509d-43ee-9bb5-f59c47bca5ff</category>
      <dc:title>Send email from VB.NET</dc:title>
      <dc:date>4/15/2005 6:35:48 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.Web.Mail
====================================================
    Public Function SendEmail(ByVal strMessage As String, _
                              ByVal strToAddress As String, _
                              ByVal strFromAddress As String, _
                              ByVal strSubject As String) As Boolean
        Dim bReturn As Boolean = True
        Try
            Dim m As Web.Mail.MailMessage = New Web.Mail.MailMessage
            With m
                .From = strFromAddress
                .To = strToAddress
                .Body = strMessage
                .Subject = strSubject
                .BodyFormat = MailFormat.Text
                .Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
                .Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
                .Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "sendmail.brinkster.com"
                .Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "you@domain.com"
                .Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "yourpassword"
                .Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
            End With
            SmtpMail.Send(m)
        Catch ex As Exception
            bReturn = False
        End Try
        Return bReturn
    End Function
</pre>]]></content:encoded>
      <snippet:downloads>47</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=6339930a-ae7d-471f-9349-bdfad1d5ce42</guid>
      <title>How to create a stream from a string in .Net</title>
      <link>/PreviewSnippet.aspx?SnippetID=6339930a-ae7d-471f-9349-bdfad1d5ce42</link>
      <description>How to create a stream from a string in .Net [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 24 Jan 2006 08:28:24 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=6339930a-ae7d-471f-9349-bdfad1d5ce42#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>How to create a stream from a string in .Net</dc:title>
      <dc:date>1/24/2006 8:28:24 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes("Test String"));</pre>]]></content:encoded>
      <snippet:downloads>1</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=3b53f6f9-81cf-4b6c-936b-be90c38ac08d</guid>
      <title>Creating XML Files with XmlTextWriter</title>
      <link>/PreviewSnippet.aspx?SnippetID=3b53f6f9-81cf-4b6c-936b-be90c38ac08d</link>
      <description>Creating XML Files with XmlTextWriter [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 05 Apr 2005 21:33:45 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=3b53f6f9-81cf-4b6c-936b-be90c38ac08d#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Creating XML Files with XmlTextWriter</dc:title>
      <dc:date>4/5/2005 9:33:45 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>      string xmlDoc = Server.MapPath("xmltextwriter.xml");
      XmlTextWriter writer = null;		
      try
         {
         writer = new XmlTextWriter(xmlDoc,Encoding.UTF8);
         writer.Formatting = Formatting.Indented;
         writer.WriteStartDocument(true);
         writer.WriteComment("XML Nodes added using the XmlTextWriter");
         writer.WriteStartElement("golfers");
            writer.WriteStartElement("golfer", null);
               writer.WriteAttributeString("skill","moderate");
               writer.WriteAttributeString("handicap","12");
               writer.WriteAttributeString("clubs","Taylor Made");
               writer.WriteAttributeString("id","1111");
             writer.WriteEndElement(); //golfer
         writer.WriteEndElement(); //golfers
         writer.Close();
         }
      catch (Exception er)
      {
         Console.WriteLine("Exception: {0}", er.ToString());
      }</pre>]]></content:encoded>
      <snippet:downloads>42</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=f843c9d6-548c-4c94-abfc-c147625bd5b7</guid>
      <title>How to convert a colour image to grayscale</title>
      <link>/PreviewSnippet.aspx?SnippetID=f843c9d6-548c-4c94-abfc-c147625bd5b7</link>
      <description>How to convert a colour image to grayscale [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 09:40:38 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=f843c9d6-548c-4c94-abfc-c147625bd5b7#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>How to convert a colour image to grayscale</dc:title>
      <dc:date>4/6/2005 9:40:38 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public Bitmap ConvertToGrayscale(Bitmap source)
{
  Bitmap bm = new Bitmap(source.Width,source.Height);
  for(int y=0;y<bm.Height;y++)
  {
    for(int x=0;x<bm.Width;x++)
    {
      Color c=source.GetPixel(x,y);
      int luma = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11);
      bm.SetPixel(x,y,Color.FromArgb(luma,luma,luma));
    }
  }
  return bm;
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ea976621-fc6a-460c-9d60-c17e60d2fbde</guid>
      <title>Check for Previous Instance of an Application Using Mutex</title>
      <link>/PreviewSnippet.aspx?SnippetID=ea976621-fc6a-460c-9d60-c17e60d2fbde</link>
      <description>Check for Previous Instance of an Application Using Mutex [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 18 Apr 2005 20:07:25 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ea976621-fc6a-460c-9d60-c17e60d2fbde#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Check for Previous Instance of an Application Using Mutex</dc:title>
      <dc:date>4/18/2005 8:07:25 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.Threading
'Form level declaration
 Dim objMutex As Mutex
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        objMutex = New Mutex(False, "SINGLE_INSTANCE_APP_MUTEX")
        If objMutex.WaitOne(0, False) = False Then
            objMutex.Close()
            objMutex = Nothing
            MessageBox.Show("Instance already running")
            End
        End If
        'if you get to this point it's frist instance
           'continue with app
     
End Sub</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>5</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=5f2da7ed-3275-459a-94ab-c2ed17a26949</guid>
      <title>How do I translate a Win32 error number into a human readable text message?</title>
      <link>/PreviewSnippet.aspx?SnippetID=5f2da7ed-3275-459a-94ab-c2ed17a26949</link>
      <description>How do I translate a Win32 error number into a human readable text message? [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 18 Apr 2005 08:57:43 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=5f2da7ed-3275-459a-94ab-c2ed17a26949#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>How do I translate a Win32 error number into a human readable text message?</dc:title>
      <dc:date>4/18/2005 8:57:43 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Private Declare Function FormatMessageA Lib "kernel32" (ByVal flags As Integer, ByRef source As Object, ByVal messageID As Integer, ByVal languageID As Integer, ByVal buffer As String, ByVal size As Integer, ByRef arguments As Integer) As Integer
Public Shared Function FormatMessage(ByVal [error] As Integer) As String
  Const FORMAT_MESSAGE_FROM_SYSTEM As Short = &H1000
  Const LANG_NEUTRAL As Short = &H0
  Dim buffer As String = Space(999)
  FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, [error], LANG_NEUTRAL, buffer, 999, 0)
  buffer = Replace(Replace(buffer, Chr(13), ""), Chr(10), "")
  Return buffer.Substring(0, buffer.IndexOf(Chr(0)))
End Function </pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=b7cd944e-ffcc-4bb0-a306-c4889d242fb8</guid>
      <title>The MessageBeep function plays a waveform sound. The waveform sound for each sound type is identified by an entry in the registry.</title>
      <link>/PreviewSnippet.aspx?SnippetID=b7cd944e-ffcc-4bb0-a306-c4889d242fb8</link>
      <description>The MessageBeep function plays a waveform sound. The waveform sound for each sound type is identified by an entry in the registry. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 30 Jun 2005 23:23:05 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=b7cd944e-ffcc-4bb0-a306-c4889d242fb8#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>The MessageBeep function plays a waveform sound. The waveform sound for each sound type is identified by an entry in the registry.</dc:title>
      <dc:date>6/30/2005 11:23:05 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>[DllImport("user32.dll")]
private extern static int MessageBeep(int uType);
private void MessageBeep(MessageBeepType beepType)
{
	MessageBeep((int)beepType);
}
private enum MessageBeepType
{
	Asterisk = 0x40,
	Exclamation = 0x30,
	Hand = 0x10,
	Question = 0x20
}</pre>]]></content:encoded>
      <snippet:downloads>2</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=7284e367-d455-455b-acb2-c495e6413a50</guid>
      <title>Painting a Control onto a Graphics object</title>
      <link>/PreviewSnippet.aspx?SnippetID=7284e367-d455-455b-acb2-c495e6413a50</link>
      <description>Painting a Control onto a Graphics object [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 24 Apr 2005 11:09:24 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=7284e367-d455-455b-acb2-c495e6413a50#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Painting a Control onto a Graphics object</dc:title>
      <dc:date>4/24/2005 11:09:24 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ControlPainter
{
  private const int
    WM_PRINT = 0x317, PRF_CLIENT = 4,
    PRF_CHILDREN = 0x10, PRF_NON_CLIENT = 2,
    COMBINED_PRINTFLAGS = PRF_CLIENT | PRF_CHILDREN | PRF_NON_CLIENT;
  [DllImport("USER32.DLL")]
  private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, int lParam);
  public static void PaintControl(Graphics graphics, Control control)
  { // paint control onto graphics
    IntPtr hWnd = control.Handle;
    IntPtr hDC = graphics.GetHdc();
    SendMessage(hWnd, WM_PRINT, hDC, COMBINED_PRINTFLAGS);
    graphics.ReleaseHdc(hDC);
  }
}</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=7ca498c9-e603-4abb-afb3-cafa8d9e8cc9</guid>
      <title>Capturing screen and saving it to an image</title>
      <link>/PreviewSnippet.aspx?SnippetID=7ca498c9-e603-4abb-afb3-cafa8d9e8cc9</link>
      <description>Capturing screen and saving it to an image [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 21 Apr 2005 16:16:59 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=7ca498c9-e603-4abb-afb3-cafa8d9e8cc9#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Capturing screen and saving it to an image</dc:title>
      <dc:date>4/21/2005 4:16:59 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
class GDI32
{
      [DllImport("GDI32.dll")]
      public static extern bool BitBlt(int hdcDest,int nXDest,int nYDest,
                                       int nWidth,int nHeight,int hdcSrc,
                                       int nXSrc,int nYSrc,int dwRop);
     [DllImport("GDI32.dll")]
      public static extern int CreateCompatibleBitmap(int hdc,int nWidth, 
                                                       int nHeight);
      [DllImport("GDI32.dll")]
      public static extern int CreateCompatibleDC(int hdc);
      [DllImport("GDI32.dll")]
      public static extern bool DeleteDC(int hdc);
      [DllImport("GDI32.dll")]
      public static extern bool DeleteObject(int hObject);
      [DllImport("GDI32.dll")]
      public static extern int GetDeviceCaps(int hdc,int nIndex);
      [DllImport("GDI32.dll")]
      public static extern int SelectObject(int hdc,int hgdiobj);
 
class User32
{
      [DllImport("User32.dll")]
      public static extern int GetDesktopWindow();
      [DllImport("User32.dll")]
      public static extern int GetWindowDC(int hWnd);
      [DllImport("User32.dll")]
      public static extern int ReleaseDC(int hWnd,int hDC);
}
 
class Example
{
      public void CaptureScreen(string fileName,ImageFormat imageFormat)
      {
            int hdcSrc = User32.GetWindowDC(User32.GetDesktopWindow()), 
                hdcDest = GDI32.CreateCompatibleDC(hdcSrc),
                hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,
                GDI32.GetDeviceCaps(hdcSrc,8),GDI32.GetDeviceCaps(hdcSrc,10)); 
            GDI32.SelectObject(hdcDest,hBitmap);
            GDI32.BitBlt(hdcDest,0,0,GDI32.GetDeviceCaps(hdcSrc,8),
                            GDI32.GetDeviceCaps(hdcSrc,10),
                            hdcSrc,0,0,0x00CC0020);
            SaveImageAs(hBitmap,fileName,imageFormat);
            Cleanup(hBitmap,hdcSrc,hdcDest);
      }
      private void Cleanup(int hBitmap,int hdcSrc,int hdcDest)
      {
            User32.ReleaseDC(User32.GetDesktopWindow(),hdcSrc);
            GDI32.DeleteDC(hdcDest);
            GDI32.DeleteObject(hBitmap);
      }      
      private void SaveImageAs(int hBitmap,string fileName,ImageFormat imageFormat)
      {
            Bitmap image = 
            new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)),
                       Image.FromHbitmap(new IntPtr(hBitmap)).Width,
                       Image.FromHbitmap(new IntPtr(hBitmap)).Height);
            image.Save(fileName,imageFormat);
      }
}</pre>]]></content:encoded>
      <snippet:downloads>11</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=68d494d9-1f28-4aa3-9835-ce25dd546008</guid>
      <title>Simple Threading</title>
      <link>/PreviewSnippet.aspx?SnippetID=68d494d9-1f28-4aa3-9835-ce25dd546008</link>
      <description>Simple Threading [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 11:37:47 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=68d494d9-1f28-4aa3-9835-ce25dd546008#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Simple Threading</dc:title>
      <dc:date>4/9/2005 11:37:47 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>/*
This example does not take into account Thread() being called in sucession as ThreadTarget() is running. It does not deal with data being passed to/from ThreadTarget() as well.
*/
    using System.Threading;
    private void Thread()
    {
        ThreadStart myThreadDelegate = new ThreadStart(this.ThreadTarget);
        Thread myThread = new Thread(myThreadDelegate);
        myThread.Priority = ThreadPriority.AboveNormal;
        myThread.Start();
    }
    private void ThreadTarget()
    {
        //Perform task on thread.
    }</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=5ae33397-b614-4a30-9fd9-cfa67212a98c</guid>
      <title>Validates the structure of an email address.</title>
      <link>/PreviewSnippet.aspx?SnippetID=5ae33397-b614-4a30-9fd9-cfa67212a98c</link>
      <description>Validates the structure of an email address. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:32:14 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=5ae33397-b614-4a30-9fd9-cfa67212a98c#comments</comments>
      <category>aeb15495-509d-43ee-9bb5-f59c47bca5ff</category>
      <dc:title>Validates the structure of an email address.</dc:title>
      <dc:date>4/15/2005 6:32:14 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		public bool CheckEmail( String Email)
		{
			// Create the regular expresion object
			Regex reg = new Regex("^[\\w\\-]+[\\.\\w\\-]*[\\@]+[\\w\\-\\.]+\\.[A-Z_a-z]{2,}$");
			// Chech the email structure and return true if OK
			return reg.IsMatch(Email,0 ) ? true : false;
			
		}</pre>]]></content:encoded>
      <snippet:downloads>22</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=4fad6e4f-89b7-4565-a7ef-d132de2fba04</guid>
      <title>Convert from binary to decimal</title>
      <link>/PreviewSnippet.aspx?SnippetID=4fad6e4f-89b7-4565-a7ef-d132de2fba04</link>
      <description>Convert from binary to decimal [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 14:00:54 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=4fad6e4f-89b7-4565-a7ef-d132de2fba04#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Convert from binary to decimal</dc:title>
      <dc:date>4/9/2005 2:00:54 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System; 
namespace csharp
{
class Class1
{
static void Main(string[] args)
{
string binary = "111";
Console.WriteLine(Convert.ToInt32(binary,2));
}
}
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=470573b9-600a-4459-a057-d1e67ca82a79</guid>
      <title>Return full path to settings file. Appends .config to the assembly name</title>
      <link>/PreviewSnippet.aspx?SnippetID=470573b9-600a-4459-a057-d1e67ca82a79</link>
      <description>Return full path to settings file. Appends .config to the assembly name [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 22 May 2005 14:18:24 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=470573b9-600a-4459-a057-d1e67ca82a79#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Return full path to settings file. Appends .config to the assembly name</dc:title>
      <dc:date>5/22/2005 2:18:24 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		/// <summary>
		/// Return full path to settings file. Appends .config to the assembly name.
		/// </summary>
		private string GetFilePath()
		{
			return Assembly.GetExecutingAssembly().GetName().CodeBase + ".config";
		}</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=0e4cce26-4291-449d-a4ca-d20647336a04</guid>
      <title>This snippet shows a Regular Expression for a strong password.</title>
      <link>/PreviewSnippet.aspx?SnippetID=0e4cce26-4291-449d-a4ca-d20647336a04</link>
      <description>This snippet shows a Regular Expression for a strong password. [Regex]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 19 May 2005 19:54:19 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=0e4cce26-4291-449d-a4ca-d20647336a04#comments</comments>
      <category>8cb6de83-1dca-44e9-964e-1bca7209fada</category>
      <dc:title>This snippet shows a Regular Expression for a strong password.</dc:title>
      <dc:date>5/19/2005 7:54:19 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>Regex</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=36eed46c-2a72-4e4b-b4f7-d2fb137d6c92</guid>
      <title>Random String Generator</title>
      <link>/PreviewSnippet.aspx?SnippetID=36eed46c-2a72-4e4b-b4f7-d2fb137d6c92</link>
      <description>Random String Generator [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 11:41:31 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=36eed46c-2a72-4e4b-b4f7-d2fb137d6c92#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Random String Generator</dc:title>
      <dc:date>4/9/2005 11:41:31 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Private Function RandomStringGenerator(ByVal intLen As Integer) As String
Dim r As New Random()
Dim i As Integer
Dim strTemp As String
For i = 0 To intLen
strTemp = strTemp & Chr(Int((26 * r.NextDouble()) + 65))
Next
Return strTemp
End Function
</pre>]]></content:encoded>
      <snippet:downloads>13</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=6eb4828e-8e8a-46e5-bdf9-d4776195c248</guid>
      <title>This is a Class you can use to connect to an RSS (Real Simple Syndication) service.</title>
      <link>/PreviewSnippet.aspx?SnippetID=6eb4828e-8e8a-46e5-bdf9-d4776195c248</link>
      <description>This is a Class you can use to connect to an RSS (Real Simple Syndication) service. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 15 Apr 2005 18:29:31 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=6eb4828e-8e8a-46e5-bdf9-d4776195c248#comments</comments>
      <category>aeb15495-509d-43ee-9bb5-f59c47bca5ff</category>
      <dc:title>This is a Class you can use to connect to an RSS (Real Simple Syndication) service.</dc:title>
      <dc:date>4/15/2005 6:29:31 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Xml;
using System.Data;
namespace ForFun
{
	/// <summary>
	/// Summary description for RSSReader.
	/// </summary>
	public class RSSReader
	{
		private string url;
		private XmlDocument xml;
		private DataSet ds;
		public RSSReader(string URL)
		{
                                                if(URL==null)
                                                   URL = "http://rss.news.yahoo.com/rss/topstories";
			url = URL;
			xml = new XmlDocument();
			xml.Load(url);
			LoadDataSet();
		}
		public XmlDocument GetXmlDocument()
		{
			return xml;
		}
		public DataSet GetDataSet()
		{
			return ds;
		}
		private void LoadDataSet()
		{
			ds = new DataSet();
			DataTable dt = new DataTable("channel");
			DataColumn dc = new DataColumn("title", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("link", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("description", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("lastBuildDate", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("ttl", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			DataRow dr = dt.NewRow();
			XmlNode xm = xml.LastChild["channel"];
			dr[0] = xm["title"].InnerText;
			dr[1] = xm["link"].InnerText;
			dr[2] = xm["description"].InnerText;
			dr[3] = xm["lastBuildDate"].InnerText;
			dr[4] = xm["ttl"].InnerText;
			dt.Rows.Add(dr);
			ds.Tables.Add(dt);
			dt = new DataTable("image");
			dc = new DataColumn("title", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("width", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("height", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("link", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("url", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dr = dt.NewRow();
			dr[0] = xm["image"]["title"].InnerText;
			dr[1] = xm["image"]["width"].InnerText;
			dr[2] = xm["image"]["height"].InnerText;
			dr[3] = xm["image"]["link"].InnerText;
			dr[4] = xm["image"]["url"].InnerText;
			dt.Rows.Add(dr);
			ds.Tables.Add(dt);
			dt = new DataTable("items");
			dc = new DataColumn("title", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("link", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("guid", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("guid_isPermaLink", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("pubDate", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			dc = new DataColumn("description", System.Type.GetType("System.String"));
			dt.Columns.Add(dc);
			
			foreach(XmlNode xn in xml.LastChild["channel"].ChildNodes)
			{
				if(xn.Name=="item")
				{
					dr = dt.NewRow();
					dr[0] = xn["title"].InnerText;
					dr[1] = xn["link"].InnerText;
					dr[2] = xn["guid"].InnerText;
					dr[3] = xn["guid"].Attributes[0].Value;
					dr[4] = xn["pubDate"].InnerText;
					dr[5] = xn["description"].InnerText;
					dt.Rows.Add(dr);
				}
			}
			ds.Tables.Add(dt);

		}
	}
}</pre>]]></content:encoded>
      <snippet:downloads>17</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=2786f21c-9b4c-4295-9516-d774a0a34aa0</guid>
      <title>Using the Beep function</title>
      <link>/PreviewSnippet.aspx?SnippetID=2786f21c-9b4c-4295-9516-d774a0a34aa0</link>
      <description>Using the Beep function [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 07 Apr 2005 11:52:04 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=2786f21c-9b4c-4295-9516-d774a0a34aa0#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Using the Beep function</dc:title>
      <dc:date>4/7/2005 11:52:04 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>public static void Beep()
{
    // Frequency 500Hz, Length 500ms
    Beep( 500, 500 );
}
[DllImport("kernel32.dll")]
private static extern bool Beep( int freq, int dur );
</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=183c2c0a-778e-45d6-937e-d92697fc6e9c</guid>
      <title>Run a single instance of an application and activate previous one if already running</title>
      <link>/PreviewSnippet.aspx?SnippetID=183c2c0a-778e-45d6-937e-d92697fc6e9c</link>
      <description>Run a single instance of an application and activate previous one if already running [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 10 Oct 2005 13:25:43 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=183c2c0a-778e-45d6-937e-d92697fc6e9c#comments</comments>
      <category>bb47ac87-7cde-45ac-aa6e-e677d46fc216</category>
      <dc:title>Run a single instance of an application and activate previous one if already running</dc:title>
      <dc:date>10/10/2005 1:25:43 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>// -----------------------------------------
// This class has been taken from Manish K Agarwal's 
// article on Code Project:
// http://www.codeproject.com/csharp/singleinstance.asp
// -------------------------------------------
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.IO;
namespace CodeXchange.Samples
{
	/// <summary>
	/// Summary description for SingleApp.
	/// </summary>
	public class SingleApplication
	{
		public SingleApplication()
		{
		}
		/// <summary>
		/// Imports 
		/// </summary>
	
		[DllImport("user32.dll")]
		private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
		[DllImport("user32.dll")]
		private static extern int SetForegroundWindow(IntPtr hWnd);
		[DllImport("user32.dll")]
		private static extern int IsIconic(IntPtr hWnd);
		/// <summary>
		/// GetCurrentInstanceWindowHandle
		/// </summary>
		/// <returns></returns>
		private static IntPtr GetCurrentInstanceWindowHandle()
		{    
			IntPtr hWnd = IntPtr.Zero;
			Process process = Process.GetCurrentProcess();
			Process[] processes = Process.GetProcessesByName(process.ProcessName);
			foreach(Process _process in processes)
			{
				// Get the first instance that is not this instance, has the
				// same process name and was started from the same file name
				// and location. Also check that the process has a valid
				// window handle in this session to filter out other user's
				// processes.
				if (_process.Id != process.Id &&
					_process.MainModule.FileName == process.MainModule.FileName &&
					_process.MainWindowHandle != IntPtr.Zero)    
				{
					hWnd = _process.MainWindowHandle;
					break;
				}
			}
			return hWnd;
		}
		/// <summary>
		/// SwitchToCurrentInstance
		/// </summary>
		public static void SwitchToCurrentInstance()
		{    
			IntPtr hWnd = GetCurrentInstanceWindowHandle();
			if (hWnd != IntPtr.Zero)    
			{    
				// Restore window if minimised. Do not restore if already in
				// normal or maximised window state, since we don't want to
				// change the current state of the window.
				if (IsIconic(hWnd) != 0)
				{
					ShowWindow(hWnd, SW_RESTORE);
				}
				// Set foreground window.
				SetForegroundWindow(hWnd);
			}
		}
		/// <summary>
		/// Execute a form base application if another instance already running on
		/// the system activate previous one
		/// </summary>
		/// <param name="frmMain">main form</param>
		/// <returns>true if no previous instance is running</returns>
		public static bool Run(System.Windows.Forms.Form frmMain)
		{
			if(IsAlreadyRunning())
			{
				//set focus on previously running app
				SwitchToCurrentInstance();
				return false;
			}
			Application.Run(frmMain);
			return true;
		}
		/// <summary>
		/// for console base application
		/// </summary>
		/// <returns></returns>
		public static bool Run()
		{
			if(IsAlreadyRunning()) 
			{
				return false;
			}
			return true;
		}
		/// <summary>
		/// check if given exe alread running or not
		/// </summary>
		/// <returns>returns true if already running</returns>
		public static bool IsAlreadyRunning()
		{
			string strLoc = Assembly.GetExecutingAssembly().Location;
			FileSystemInfo fileInfo = new FileInfo(strLoc);
			string sExeName = fileInfo.Name;
			bool bCreatedNew;
			mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
			if (bCreatedNew)
				mutex.ReleaseMutex();
			return !bCreatedNew;
		}
		
		static Mutex mutex;
		const int SW_RESTORE = 9;
	}
}
</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=13da9554-4c8c-439a-a94e-da1eeebd804e</guid>
      <title>Add an assembly to the Visual Studio.NET 2003 'Add References' dialog box</title>
      <link>/PreviewSnippet.aspx?SnippetID=13da9554-4c8c-439a-a94e-da1eeebd804e</link>
      <description>Add an assembly to the Visual Studio.NET 2003 'Add References' dialog box [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 02 May 2005 09:29:58 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=13da9554-4c8c-439a-a94e-da1eeebd804e#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>Add an assembly to the Visual Studio.NET 2003 'Add References' dialog box</dc:title>
      <dc:date>5/2/2005 9:29:58 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		private const string application = "CodeXchange";
		private const string source = application + ".Install";
		private const string subKey = @"SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\" + application;
		private void AddToVSReferencesDialog ()
		{
			StringBuilder sb = new StringBuilder();
			try
			{
				// add the assemblies to the 'Add References' dialog box.
				RegistryKey hklm = Registry.LocalMachine;
				using(hklm)
				{
					RegistryKey key = hklm.CreateSubKey(subKey);
				
					using(key)
					{
						string directory = this.SetupFolder;
						key.SetValue(string.Empty, directory);
						sb.AppendFormat("{0}={1}\n", subKey, directory);
					}
				}
				EventLog.WriteEntry(source, sb.ToString());
			}
			catch
			{
				//May happen
			}
		}
		private void RemoveFromVSReferencesDialog ()
		{
			StringBuilder sb = new StringBuilder();
			try
			{
				// remove the assemblies from the 'Add References' dialog box.
				RegistryKey hklm = Registry.LocalMachine;
				using(hklm)
				{
					hklm.DeleteSubKey(subKey);
					sb.AppendFormat("RegKey deleted: {0}", subKey);
				}
				EventLog.WriteEntry(source, sb.ToString());
			}
			catch
			{
				//May happen
			}
		}
</pre>]]></content:encoded>
      <snippet:downloads>3</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=21a6ade1-aec3-400f-bdc8-df4a09a22f33</guid>
      <title>Bind to Active Directory and create a new user</title>
      <link>/PreviewSnippet.aspx?SnippetID=21a6ade1-aec3-400f-bdc8-df4a09a22f33</link>
      <description>Bind to Active Directory and create a new user [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 24 Apr 2005 10:22:13 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=21a6ade1-aec3-400f-bdc8-df4a09a22f33#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Bind to Active Directory and create a new user</dc:title>
      <dc:date>4/24/2005 10:22:13 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.DirectoryServices
Imports ActiveDs
Module Module1
    Sub Main()
        ' connect to my Active Directory
        Dim root As New DirectoryEntry("LDAP://MyDomainControllerServer/dc=digeratisoftware,dc=local")
        Try
            ' create a new user object whose RDN is John Brennan
            Dim user As DirectoryEntry = root.Children.Add("CN=John Brennan", "user")
            ' set properties on the user
            user.Properties("givenName").Value = "John"
            user.Properties("sn").Value = "Brennan"
            user.Properties("mail").Value = "john@somemailaddress.com"
            user.Properties("description").Value = "new test user"
            user.Properties("sAMAccountName").Value = "John.Brennan"            
            ' userPrincipalName. This property is domain specific
            user.Properties("description").Value = "John.Brennan@digeratsoftware.local"             
            ' enable the user account and set their password to never expire
            user.Properties("userAccountControl").Value = ADS_USER_FLAG.ADS_UF_NORMAL_ACCOUNT Or ADS_USER_FLAG.ADS_UF_PASSWD_NOTREQD Or ADS_USER_FLAG.ADS_UF_DONT_EXPIRE_PASSWD
            ' commit the object from memory to the directory store
            user.CommitChanges()
            ' next set the user's password
            user.Invoke("SetPassword", New Object() {"mypassword"})
        Catch ex As Exception
            Throw
        End Try
    End Sub
End Module</pre>]]></content:encoded>
      <snippet:downloads>16</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=abc847cb-8f0b-4c9d-9ed1-e219e5298cb1</guid>
      <title>Scheduling using System.Timers.Timer class</title>
      <link>/PreviewSnippet.aspx?SnippetID=abc847cb-8f0b-4c9d-9ed1-e219e5298cb1</link>
      <description>Scheduling using System.Timers.Timer class [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 11:40:32 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=abc847cb-8f0b-4c9d-9ed1-e219e5298cb1#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Scheduling using System.Timers.Timer class</dc:title>
      <dc:date>4/9/2005 11:40:32 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Public Function StartSchedule() As String
        Dim myTimer As New System.Timers.Timer()
        AddHandler myTimer.Elapsed, AddressOf MyScheduledOperation
        myTimer.Interval = New TimeSpan(1, 0, 0, 0, 0).TotalMilliseconds
        myTimer.Enabled = True
End Function
Public Sub MyScheduledOperation(ByVal sender As Object, ByVal e As ElapsedEventArgs)
        Select Case e.SignalTime.DayOfWeek
           Case e.SignalTime.DayOfWeek.Monday
                'Do Monday's work
            Case e.SignalTime.DayOfWeek.Tuesday
                'Do Tuesday's work
            Case e.SignalTime.DayOfWeek.Wednesday
                'Do Wednesdays's work
            Case e.SignalTime.DayOfWeek.Thursday
                'Do Thursday's work
            
            Case e.SignalTime.DayOfWeek.Friday
                'Do Friday's work
            Case e.SignalTime.DayOfWeek.Saturday
                'Do Saturday's work
            Case e.SignalTime.DayOfWeek.Sunday
                'Do Sunday's work
        End Select
    End Sub
</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=157360e2-f44d-4d92-9421-e2dad20b6811</guid>
      <title>Provides functionality for programmatically uploading files with the HTTP protocol.</title>
      <link>/PreviewSnippet.aspx?SnippetID=157360e2-f44d-4d92-9421-e2dad20b6811</link>
      <description>Provides functionality for programmatically uploading files with the HTTP protocol. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Fri, 02 Sep 2005 21:02:16 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=157360e2-f44d-4d92-9421-e2dad20b6811#comments</comments>
      <category>edde3ea1-24a6-4cb0-8446-ab91e1800116</category>
      <dc:title>Provides functionality for programmatically uploading files with the HTTP protocol.</dc:title>
      <dc:date>9/2/2005 9:02:16 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.IO;
using System.Net;
namespace JouniHeikniemi.Tools.Http {
  /// <summary>
  /// Provides functionality for programmatically uploading files 
  /// with the HTTP protocol.
  /// </summary>
  public class HttpFileUpload {
    // Prevent construction
    private HttpFileUpload() { }
    /// <summary>
    /// Holds the information about the file(s) to be uploaded.
    /// </summary>
    public struct UploadSpec {
      
      public byte[] Contents;
      public string FileName;
      public string FieldName;
      /// <summary>
      /// Creates a new upload spec based on a byte array.
      /// </summary>
      /// <param name="contents">The contents to be uploaded.</param>
      /// <param name="fileName">The file to be uploaded.</param>
      /// <param name="fieldName">The field name as which this file shall be sent to.</param>
      public UploadSpec(byte[] contents, string fileName, string fieldName) {
        this.Contents = contents;
        this.FileName = fileName;
        this.FieldName = fieldName;
      }

      /// <summary>
      /// Creates a new upload spec based on a file name.
      /// </summary>
      /// <param name="pathname"></param>
      /// <param name="fieldName"></param>
      public UploadSpec(string pathname, string fieldName) {
        using (FileStream inFile = new FileStream(pathname, FileMode.Open)) {
          byte[] inBytes = new byte[inFile.Length];
          inFile.Read(inBytes, 0, inBytes.Length);
          this.Contents = inBytes;
        }
        this.FileName = Path.GetFileName(pathname);
        this.FieldName = fieldName;
      }
    }
    /// <summary>
    /// Uploads the given file to the given url.
    /// </summary>
    /// <param name="pathname">The pathname of the file to be uploaded.</param>
    /// <param name="url">The url to which the file shall be sent.</param>
    /// <param name="fieldName">The name of the form field for the upload.</param>
    /// <param name="cookies">Cookies to be sent with the request.</param>
    /// <param name="credentials">Login credentials to be passed.</param>
    public static HttpWebResponse UploadFile(string pathname, string url, string fieldName, 
                                             CookieContainer cookies, CredentialCache credentials) {
      return Upload(url, cookies, credentials, new UploadSpec(pathname, fieldName));
    }

    /// <summary>
    /// Uploads the given byte array to the given url.
    /// </summary>
    /// <param name="data">The data to be uploaded.</param>
    /// <param name="fileName">The name to be sent as the filename.</param>
    /// <param name="url">The url to which the file shall be sent.</param>
    /// <param name="fieldName">The name of the form field for the upload.</param>
    /// <param name="cookies">Cookies to be sent with the request.</param>
    /// <param name="credentials">Login credentials to be passed.</param>
    public static HttpWebResponse UploadByteArray(byte[] data, string fileName, string url, string fieldName, 
                                                  CookieContainer cookies, CredentialCache credentials) {
      return Upload(url, cookies, credentials, new UploadSpec(data, fileName, fieldName));
    }

    /// <summary>
    /// Uploads the given data.
    /// </summary>
    /// <param name="url">The url to which the data shall be sent.</param>
    /// <param name="cookies">Cookies to be sent with the request.</param>
    /// <param name="credentials">Login credentials to be passed.</param>
    /// <param name="objects">The data to be sent.</param>
    public static HttpWebResponse Upload(string url, CookieContainer cookies, CredentialCache credentials,
                                         params UploadSpec[] objects) {
      // Initialize the request object
      HttpWebRequest req = (WebRequest.Create(url) as HttpWebRequest);
      if (cookies != null) req.CookieContainer = cookies;
      if (credentials != null) req.Credentials = credentials;
      
      string boundary = Guid.NewGuid().ToString().Replace("-", "");
      req.ContentType = "multipart/form-data; boundary=" + boundary;
      req.Method = "POST";
      MemoryStream postData = new MemoryStream();
      string newLine = "\r\n";
      StreamWriter sw = new StreamWriter(postData);
      
      foreach (UploadSpec us in objects) {
        sw.Write("--" + boundary + newLine);
        sw.Write(
          "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}",
          us.FieldName,
          us.FileName,
          newLine
          );
        sw.Write("Content-Type: application/octet-stream" + newLine + newLine);
        sw.Flush();
        postData.Write(us.Contents, 0, us.Contents.Length);
        sw.Write(newLine);
      }
      sw.Write("--{0}--{1}", boundary, newLine);
      sw.Flush();
      req.ContentLength = postData.Length;
      using (Stream s = req.GetRequestStream())
        postData.WriteTo(s);
      postData.Close();
      return (req.GetResponse() as HttpWebResponse);
    }
  }</pre>]]></content:encoded>
      <snippet:downloads>13</snippet:downloads>
      <snippet:rating>4</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ef036887-9f41-4bd1-8437-e3bee07c39ff</guid>
      <title>Obtains the 100-nanosecond time from a time given in hours, minutes, seconds and milliseconds.</title>
      <link>/PreviewSnippet.aspx?SnippetID=ef036887-9f41-4bd1-8437-e3bee07c39ff</link>
      <description>Obtains the 100-nanosecond time from a time given in hours, minutes, seconds and milliseconds. [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 02 Jan 2006 18:30:56 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ef036887-9f41-4bd1-8437-e3bee07c39ff#comments</comments>
      <category>701a2ecc-98c3-467f-95c7-3274cc59e2f4</category>
      <dc:title>Obtains the 100-nanosecond time from a time given in hours, minutes, seconds and milliseconds.</dc:title>
      <dc:date>1/2/2006 6:30:56 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>		/// <summary>
		/// Obtains the 100-nanosecond time from a time given in hours, minutes, seconds and milliseconds.
		/// </summary>
		/// <param name="hours">Hours</param>
		/// <param name="minutes">Minutes</param>
		/// <param name="seconds">Seconds</param>
		/// <param name="mseconds">Milliseconds</param>
		/// <returns>100-nanosecond time</returns>
		public static ulong HMSmS2WMTime(int hours, int minutes, int seconds, int mseconds)
		{
			return (ulong)((hours*3600000) + (minutes*60000) + (seconds*1000) + mseconds)*10000;
		}</pre>]]></content:encoded>
      <snippet:downloads>0</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=e3a75435-4434-4fbc-8f62-e3eb023ed4af</guid>
      <title>This code snippet uses System.Drawing namespace to convert the image formats.</title>
      <link>/PreviewSnippet.aspx?SnippetID=e3a75435-4434-4fbc-8f62-e3eb023ed4af</link>
      <description>This code snippet uses System.Drawing namespace to convert the image formats. [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 09:55:22 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=e3a75435-4434-4fbc-8f62-e3eb023ed4af#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>This code snippet uses System.Drawing namespace to convert the image formats.</dc:title>
      <dc:date>4/16/2005 9:55:22 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System
Imports System.Drawing
Class ConvertImageFormats
 Shared Sub main()
  Dim strFileToConvert As String
  Console.Write("Image File to Convert :")
  strFileToConvert = Console.ReadLine()
  'Initialize the bitmap object by supplying the image file path
  Dim b As New Bitmap(strFileToConvert)
 'Conver the file in GIF format, also check out other formats like JPG, TIFF
  b.Save(strFileToConvert + ".gif",  System.Drawing.Imaging.ImageFormat.Gif)
  Console.Write("Sucessfully Converted to " & strFileToConvert & ".gif")
 End Sub
End Class
Check out the relevent C# code to convert the image formats.
  Bitmap b;
  mybmp Bitmap = new Bitmap("FileName");
  b.Save("FileName",System.Drawing.Imaging.ImageFormat.Gif);</pre>]]></content:encoded>
      <snippet:downloads>12</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=e953b587-fd27-48e2-920c-e48ad52a4c26</guid>
      <title>Simple Encryption and Decryption Using VB.NET</title>
      <link>/PreviewSnippet.aspx?SnippetID=e953b587-fd27-48e2-920c-e48ad52a4c26</link>
      <description>Simple Encryption and Decryption Using VB.NET [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 16 Apr 2005 09:53:56 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=e953b587-fd27-48e2-920c-e48ad52a4c26#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Simple Encryption and Decryption Using VB.NET</dc:title>
      <dc:date>4/16/2005 9:53:56 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Imports System.Security.Cryptography 
Imports System.Text 
******* Encrypt the Data *******
Public Function GetEncryptedData(ByVal Data As String) As String
Dim shaM As New SHA1Managed
Convert.ToBase64String(shaM.ComputeHash(Encoding.ASCII.GetBytes(Data)))
Dim eNC_data() As Byte = ASCIIEncoding.ASCII.GetBytes(Data)
Dim eNC_str As String = Convert.ToBase64String(eNC_data)
GetEncryptedData = eNC_str
End Function
******* Decrypt the Data *******
Public Function GetDecryptedData(ByVal Data As String) As String
Dim dEC_data() As Byte = Convert.FromBase64String(Data)
Dim dEC_Str As String = ASCIIEncoding.ASCII.GetString(dEC_data)
GetDecryptedData = dEC_Str
End Function
*********************************
'The above code snippet demonstrates simple encryption/Decryption a given string very use full in password encryption. 
'The function uses SHA1 to Compute the SHA1 hash for the input data. 
'The hash is used as a unique value of fixed size representing a large amount of data. 
'The hash size for the SHA1 algorithm is 160 bits.
'This function Imports the  System.Security.Cryptography and System.Text namespace for this. </pre>]]></content:encoded>
      <snippet:downloads>23</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a3614b49-72af-4be6-bbbb-e8856a66151e</guid>
      <title>Drawing outsite a Windows forms Window</title>
      <link>/PreviewSnippet.aspx?SnippetID=a3614b49-72af-4be6-bbbb-e8856a66151e</link>
      <description>Drawing outsite a Windows forms Window [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Tue, 05 Apr 2005 21:41:01 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a3614b49-72af-4be6-bbbb-e8856a66151e#comments</comments>
      <category>d6a7b127-53c6-4223-9b5d-5e8915ca1519</category>
      <dc:title>Drawing outsite a Windows forms Window</dc:title>
      <dc:date>4/5/2005 9:41:01 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>[DllImport("User32.dll")] 
public extern static System.IntPtr GetDC(System.IntPtr hWnd); 
private void button1_Click(object sender, System.EventArgs e) 
{ 
          System.IntPtr DesktopHandle = GetDC(System.IntPtr.Zero); 
          Graphics g = System.Drawing.Graphics.FromHdc(DesktopHandle); 
          g.FillRectangle(new SolidBrush(Color.Red),0,0,100,100); 
}</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=6aff55a7-1909-4cb1-9db7-e9d099b387f0</guid>
      <title>Draw String on Form</title>
      <link>/PreviewSnippet.aspx?SnippetID=6aff55a7-1909-4cb1-9db7-e9d099b387f0</link>
      <description>Draw String on Form [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:48:28 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=6aff55a7-1909-4cb1-9db7-e9d099b387f0#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Draw String on Form</dc:title>
      <dc:date>4/6/2005 1:48:28 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        'create a new brush with a single, solid color
        Dim myBrush As New SolidBrush(Color.Purple)
        'create a new basic font. you can mess around and make it cooler
        Dim f As Font = New Font(Font.Bold, 20)
        'draw the string onto the form. At Position (0 left), (10 top)
        Me.CreateGraphics.DrawString("Hello, This is just a test!", f, myBrush, 0, 10)</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=f66c54e7-636e-495e-8f84-ea1cfe0ca455</guid>
      <title>CRC calculation algorithm</title>
      <link>/PreviewSnippet.aspx?SnippetID=f66c54e7-636e-495e-8f84-ea1cfe0ca455</link>
      <description>CRC calculation algorithm [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 16 Jun 2005 07:41:20 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=f66c54e7-636e-495e-8f84-ea1cfe0ca455#comments</comments>
      <category>8c2f06f8-1c90-43ba-b7f6-72416ef60c2b</category>
      <dc:title>CRC calculation algorithm</dc:title>
      <dc:date>6/16/2005 7:41:20 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
namespace CRC
{
	/// <summary>
	/// 
	/// </summary>
	public class CRC32
	{
		readonly static ulong[] crcLookup = new ulong[256] 
		{0x00000000, 0x77033096, 0xEE0E612C, 0x990D51BA,
		0x076DC419, 0x706EF48F, 0xE963A535, 0x9E6095A3,
		0x0EDF8832, 0x79DCB8A4, 0xE0D1E91E, 0x97D2D988,
		0x09B24C2B, 0x7EB17CBD, 0xE7BC2D07, 0x90BF1D91,
		0x1DB31064, 0x6AB020F2, 0xF3BD7148, 0x84BE41DE,
		0x1ADED47D, 0x6DDDE4EB, 0xF4D0B551, 0x83D385C7,
		0x136C9856, 0x646FA8C0, 0xFD62F97A, 0x8A61C9EC,
		0x14015C4F, 0x63026CD9, 0xFA0F3D63, 0x8D0C0DF5,
		0x3B6E20C8, 0x4C6D105E, 0xD56041E4, 0xA2637172,
		0x3C03E4D1, 0x4B00D447, 0xD20D85FD, 0xA50EB56B,
		0x35B1A8FA, 0x42B2986C, 0xDBBFC9D6, 0xACBCF940,
		0x32DC6CE3, 0x45DF5C75, 0xDCD20DCF, 0xABD13D59,
		0x26DD30AC, 0x51DE003A, 0xC8D35180, 0xBFD06116,
		0x21B0F4B5, 0x56B3C423, 0xCFBE9599, 0xB8BDA50F,
		0x2802B89E, 0x5F018808, 0xC60CD9B2, 0xB10FE924,
		0x2F6F7C87, 0x586C4C11, 0xC1611DAB, 0xB6622D3D,
		0x76DC4190, 0x01DF7106, 0x98D220BC, 0xEFD1102A,
		0x71B18589, 0x06B2B51F, 0x9FBFE4A5, 0xE8BCD433,
		0x7803C9A2, 0x0F00F934, 0x960DA88E, 0xE10E9818,
		0x7F6E0DBB, 0x086D3D2D, 0x91606C97, 0xE6635C01,
		0x6B6F51F4, 0x1C6C6162, 0x856130D8, 0xF262004E,
		0x6C0295ED, 0x1B01A57B, 0x820CF4C1, 0xF50FC457,
		0x65B0D9C6, 0x12B3E950, 0x8BBEB8EA, 0xFCBD887C,
		0x62DD1DDF, 0x15DE2D49, 0x8CD37CF3, 0xFBD04C65,
		0x4DB26158, 0x3AB151CE, 0xA3BC0074, 0xD4BF30E2,
		0x4ADFA541, 0x3DDC95D7, 0xA4D1C46D, 0xD3D2F4FB,
		0x436DE96A, 0x346ED9FC, 0xAD638846, 0xDA60B8D0,
		0x44002D73, 0x33031DE5, 0xAA0E4C5F, 0xDD0D7CC9,
		0x5001713C, 0x270241AA, 0xBE0F1010, 0xC90C2086,
		0x576CB525, 0x206F85B3, 0xB962D409, 0xCE61E49F,
		0x5EDEF90E, 0x29DDC998, 0xB0D09822, 0xC7D3A8B4,
		0x59B33D17, 0x2EB00D81, 0xB7BD5C3B, 0xC0BE6CAD,
		0xEDBC8320, 0x9ABFB3B6, 0x03B2E20C, 0x74B1D29A,
		0xEAD14739, 0x9DD277AF, 0x04DF2615, 0x73DC1683,
		0xE3630B12, 0x94603B84, 0x0D6D6A3E, 0x7A6E5AA8,
		0xE40ECF0B, 0x930DFF9D, 0x0A00AE27, 0x7D039EB1,
		0xF00F9344, 0x870CA3D2, 0x1E01F268, 0x6902C2FE,
		0xF762575D, 0x806167CB, 0x196C3671, 0x6E6F06E7,
		0xFED01B76, 0x89D32BE0, 0x10DE7A5A, 0x67DD4ACC,
		0xF9BDDF6F, 0x8EBEEFF9, 0x17B3BE43, 0x60B08ED5,
		0xD6D2A3E8, 0xA1D1937E, 0x38DCC2C4, 0x4FDFF252,
		0xD1BF67F1, 0xA6BC5767, 0x3FB106DD, 0x48B2364B,
		0xD80D2BDA, 0xAF0E1B4C, 0x36034AF6, 0x41007A60,
		0xDF60EFC3, 0xA863DF55, 0x316E8EEF, 0x466DBE79,
		0xCB61B38C, 0xBC62831A, 0x256FD2A0, 0x526CE236,
		0xCC0C7795, 0xBB0F4703, 0x220216B9, 0x5501262F,
		0xC5BE3BBE, 0xB2BD0B28, 0x2BB05A92, 0x5CB36A04,
		0xC2D3FFA7, 0xB5D0CF31, 0x2CDD9E8B, 0x5BDEAE1D,
		0x9B60C2B0, 0xEC63F226, 0x756EA39C, 0x026D930A,
		0x9C0D06A9, 0xEB0E363F, 0x72036785, 0x05005713,
		0x95BF4A82, 0xE2BC7A14, 0x7BB12BAE, 0x0CB21B38,
		0x92D28E9B, 0xE5D1BE0D, 0x7CDCEFB7, 0x0BDFDF21,
		0x86D3D2D4, 0xF1D0E242, 0x68DDB3F8, 0x1FDE836E,
		0x81BE16CD, 0xF6BD265B, 0x6FB077E1, 0x18B34777,
		0x880C5AE6, 0xFF0F6A70, 0x66023BCA, 0x11010B5C,
		0x8F619EFF, 0xF862AE69, 0x616FFFD3, 0x166CCF45,
		0xA00EE278, 0xD70DD2EE, 0x4E008354, 0x3903B3C2,
		0xA7632661, 0xD06016F7, 0x496D474D, 0x3E6E77DB,
		0xAED16A4A, 0xD9D25ADC, 0x40DF0B66, 0x37DC3BF0,
		0xA9BCAE53, 0xDEBF9EC5, 0x47B2CF7F, 0x30B1FFE9,
		0xBDBDF21C, 0xCABEC28A, 0x53B39330, 0x24B0A3A6,
		0xBAD03605, 0xCDD30693, 0x54DE5729, 0x23DD67BF,
		0xB3627A2E, 0xC4614AB8, 0x5D6C1B02, 0x2A6F2B94,
		0xB40FBE37, 0xC30C8EA1, 0x5A01DF1B, 0x2D02EF8D};
		readonly static ulong crc = 0xFFFFFFFF;
		public CRC32()
		{
			// 
			// TODO: Add constructor logic here
			//
		}
		public long CalculateCRC(byte[] by) 
		{
			ulong ulCRC = crc;
			long len;
			len = by.Length;
			for(long i = 0; i < len; i++) 
			{ 
				ulCRC = (ulCRC >> 8) ^ crcLookup[(ulCRC & 0xFF) ^ by[i]];
			}
			return Convert.ToInt64( ulCRC ^ crc); 
		} 
		public long CalculateCRC(uint[] ui) 
		{
			ulong ulCRC = crc;
			long len;
			len = ui.Length;
			for(long i = 0; i < len; i++) 
			{ 
				byte[] By = BitConverter.GetBytes(ui[i]);
				for(long j = 0; j < 4; j++)
				{
					ulCRC = (ulCRC >> 8) ^ crcLookup[(ulCRC & 0xFF) ^ By[j]];
				}
			}
			return Convert.ToInt64( ulCRC ^ crc); 
		} 
	}
}</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=f3f52e54-4efb-46a5-9769-eb60b447855c</guid>
      <title>This code attempts to get a response from the passed URL</title>
      <link>/PreviewSnippet.aspx?SnippetID=f3f52e54-4efb-46a5-9769-eb60b447855c</link>
      <description>This code attempts to get a response from the passed URL [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Thu, 12 Jan 2006 17:55:33 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=f3f52e54-4efb-46a5-9769-eb60b447855c#comments</comments>
      <category>edde3ea1-24a6-4cb0-8446-ab91e1800116</category>
      <dc:title>This code attempts to get a response from the passed URL</dc:title>
      <dc:date>1/12/2006 5:55:33 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>#Region " ... WebSiteIsAvailable Function "
    Private Function WebSiteIsAvailable(ByVal linkText As String) As Boolean
        '----------------------------------------------------
        ' Attempt to get a response from the passed URL
        ' Pass:       linkText    URL to site being checked
        ' Return:     True        The site responded
        '             False       The site did not respond
        '----------------------------------------------------
        '     Date    Developer            Code Change
        '  ---------- -------------------- ------------------
        '  12/11/2005 G Gilbert            Original code
        '----------------------------------------------------
        '----------------------------------------------------
        ' Local Constant/Variable Declarations
        '----------------------------------------------------
        Dim URL_Object As New System.Uri(linkText)
        Dim URL_WebRequest As System.Net.WebRequest
        Dim URL_WebResponse As System.Net.WebResponse
        Dim Response_Result As Boolean
        '----------------------------------------------------
        ' Attempt to get a response from the URL
        '----------------------------------------------------
        Try
            URL_WebRequest = System.Net.WebRequest.Create(URL_Object)
            URL_WebResponse = URL_WebRequest.GetResponse
            Response_Result = True
        Catch Any_Error As Exception
            Response_Result = False
        End Try
        URL_WebResponse = Nothing
        URL_WebRequest = Nothing
        URL_Object = Nothing
        '----------------------------------------------------
        ' Return the result
        '----------------------------------------------------
        Return Response_Result
    End Function
#End Region</pre>]]></content:encoded>
      <snippet:downloads>1</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=d3a5038e-e85a-4423-8cfa-efd8e9250c73</guid>
      <title>Strip Images From Animated Gif</title>
      <link>/PreviewSnippet.aspx?SnippetID=d3a5038e-e85a-4423-8cfa-efd8e9250c73</link>
      <description>Strip Images From Animated Gif [C#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Mon, 14 Nov 2005 20:40:07 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=d3a5038e-e85a-4423-8cfa-efd8e9250c73#comments</comments>
      <category>ca0f8ad3-3e10-42c2-a83f-238871d14351</category>
      <dc:title>Strip Images From Animated Gif</dc:title>
      <dc:date>11/14/2005 8:40:07 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace StripAnimation
{
 
  class Class1
  {
		
     [STAThread]
     static void Main(string[] args)
     {
        StripAnimation.Stripper oStripper = new StripAnimation.Stripper();
        oStripper.Strip("sample.gif","","frame"); 
     }
  }
 
  public class Stripper
  {
    public void Strip(string FileName,string OutputFolder,string OutputBaseName)
    {
			 
      ImageManipulation.OctreeQuantizer quantizer = null;
      string OutputFileName = OutputFolder + OutputBaseName;
			
      Image MasterImage = Image.FromFile(FileName);
		 
      FrameDimension oDimension = new FrameDimension(MasterImage.FrameDimensionsList[0]);
      int FrameCount = MasterImage.GetFrameCount(oDimension);
      for(int i=0;i<FrameCount;i++)
      {
        MasterImage.SelectActiveFrame(oDimension,i); 
        quantizer = new ImageManipulation.OctreeQuantizer(255,8);
			  
        using ( Bitmap quantized = quantizer.Quantize(MasterImage) )
        {
          quantized.Save(OutputFileName + i.ToString() + ".gif",ImageFormat.Gif);
        }
      } 
      MasterImage.Dispose(); 			
   } 
  }
}
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>0</snippet:rating>
      <snippet:language>C#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=8fcf3819-7cf0-454e-8e9a-f4ba24e07be6</guid>
      <title>Show all files in a directory</title>
      <link>/PreviewSnippet.aspx?SnippetID=8fcf3819-7cf0-454e-8e9a-f4ba24e07be6</link>
      <description>Show all files in a directory [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:36:05 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=8fcf3819-7cf0-454e-8e9a-f4ba24e07be6#comments</comments>
      <category>de2012da-757e-4af6-8537-6799adb7bce1</category>
      <dc:title>Show all files in a directory</dc:title>
      <dc:date>4/6/2005 1:36:05 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Dim file() As String 
file = System.IO.Directory.GetFiles("c:\")
Dim enumerator As System.Collections.IEnumerator
enumerator = file.GetEnumerator
While enumerator.MoveNext
Console.WriteLine(CStr(enumerator.Current))
End While
</pre>]]></content:encoded>
      <snippet:downloads>4</snippet:downloads>
      <snippet:rating>2</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=7cb66774-4b90-4b55-86f1-f548fdebc1f8</guid>
      <title>Email validation w/ DNS in java</title>
      <link>/PreviewSnippet.aspx?SnippetID=7cb66774-4b90-4b55-86f1-f548fdebc1f8</link>
      <description>Email validation w/ DNS in java [J#]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sun, 17 Apr 2005 10:28:19 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=7cb66774-4b90-4b55-86f1-f548fdebc1f8#comments</comments>
      <category>05d0a09e-56f8-4801-9132-4efc8674eae6</category>
      <dc:title>Email validation w/ DNS in java</dc:title>
      <dc:date>4/17/2005 10:28:19 AM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>function IsEmailAddrValid($email, $check_dns = false)
{ 
  if( 
      (preg_match('/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/', $email)) 
      || 
      (preg_match('/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/', $email)) 
    ) 
  { 
    if($check_dns) 
    { 
      $host = explode('@', $email);
      // Check for MX record 
      if( checkdnsrr($host[1], 'MX') ) return true; 
      // Check for A record 
      if( checkdnsrr($host[1], 'A') ) return true; 
      // Check for CNAME record 
      if( checkdnsrr($host[1], 'CNAME') ) return true; 
    } 
    else 
    { 
      return true; 
    } 
  }  return false; 
}</pre>]]></content:encoded>
      <snippet:downloads>6</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>J#</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=a18d6368-1696-49fb-884d-f815c4440199</guid>
      <title>Read Contents of a Text File and Add to a Textbox Control With Stream Reader Class</title>
      <link>/PreviewSnippet.aspx?SnippetID=a18d6368-1696-49fb-884d-f815c4440199</link>
      <description>Read Contents of a Text File and Add to a Textbox Control With Stream Reader Class [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:49:02 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=a18d6368-1696-49fb-884d-f815c4440199#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>Read Contents of a Text File and Add to a Textbox Control With Stream Reader Class</dc:title>
      <dc:date>4/6/2005 1:49:02 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        Imports System.IO
        'Read from a text file to a textbox with the Stream Reader Class
        'Put a textbox on the form and name txt and set to multi-line
        'Make the Reader read the entire contents of the textfile and write to the textbox
        'Add to text file
        Dim sReader As StreamReader = New StreamReader("c:\newTextFile.txt")
        
        'Make the textbox keep the current data while adding the new data
        txt.AppendText(sReader.ReadToEnd)</pre>]]></content:encoded>
      <snippet:downloads>20</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=db3c093b-03d0-406b-9328-f97d1ad5bfa3</guid>
      <title>Write Text to a Text File with Stream Writer Class</title>
      <link>/PreviewSnippet.aspx?SnippetID=db3c093b-03d0-406b-9328-f97d1ad5bfa3</link>
      <description>Write Text to a Text File with Stream Writer Class [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Wed, 06 Apr 2005 13:49:21 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=db3c093b-03d0-406b-9328-f97d1ad5bfa3#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>Write Text to a Text File with Stream Writer Class</dc:title>
      <dc:date>4/6/2005 1:49:21 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>        Imports System.IO
		
        'Write to text file with the Stream Writer Class
        Dim sWriter As StreamWriter = New StreamWriter("c:\newTextFile.txt")
       'This is pretty much easy to understand. No explanation
        sWriter.WriteLine("Hi")
        sWriter.WriteLine("Testing out this code")
        sWriter.WriteLine("Hopefully this code will work")
        sWriter.WriteLine("Lets flush the stream and see")
        'Put the data inside the text file
        sWriter.Flush()
</pre>]]></content:encoded>
      <snippet:downloads>10</snippet:downloads>
      <snippet:rating>1</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
    <item>
      <guid>/PreviewSnippet.aspx?SnippetID=ab3006ba-ea02-4a4e-8d62-feddbfa57898</guid>
      <title>Display the size of the hard disk using the WMI</title>
      <link>/PreviewSnippet.aspx?SnippetID=ab3006ba-ea02-4a4e-8d62-feddbfa57898</link>
      <description>Display the size of the hard disk using the WMI [VB.NET]</description>
      <author>J.Marc Piulachs</author>
      <pubDate>Sat, 09 Apr 2005 13:59:33 GMT</pubDate>
      <comments>/PreviewSnippet.aspx?SnippetID=ab3006ba-ea02-4a4e-8d62-feddbfa57898#comments</comments>
      <category>427a3023-1009-4fad-8108-77d5eea21bd1</category>
      <dc:title>Display the size of the hard disk using the WMI</dc:title>
      <dc:date>4/9/2005 1:59:33 PM</dc:date>
      <dc:creator>J.Marc Piulachs</dc:creator>
      <content:encoded><![CDATA[<pre>Private Sub Form_Load()
'add a reference to the Microsoft WMI Scripting 1.2 library
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_DiskDrive", , 48)
For Each objItem In colItems
'Form1.Print "Size: " & objItem.Size / 1024 / 1024 & " megabytes"
MsgBox ("Size: " & objItem.Size / 1024 / 1024 & " megabytes")
Next
End Sub
</pre>]]></content:encoded>
      <snippet:downloads>5</snippet:downloads>
      <snippet:rating>3</snippet:rating>
      <snippet:language>VB.NET</snippet:language>
    </item>
  </channel>
</rss>