<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Michael E. Chancey Jr. &#187; Useful Code</title>
	<atom:link href="http://michael.chanceyjr.com/category/useful-code/feed/" rel="self" type="application/rss+xml" />
	<link>http://michael.chanceyjr.com</link>
	<description></description>
	<lastBuildDate>Tue, 31 Aug 2010 22:45:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Exporting Datasets and Datatables to CSV Extension</title>
		<link>http://michael.chanceyjr.com/useful-code/exporting-datasets-and-datatables-to-csv-extension/</link>
		<comments>http://michael.chanceyjr.com/useful-code/exporting-datasets-and-datatables-to-csv-extension/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 22:30:12 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[Comma Separated Values]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Dataset]]></category>
		<category><![CDATA[Datatable]]></category>
		<category><![CDATA[Extension]]></category>
		<category><![CDATA[VB]]></category>
		<category><![CDATA[VB.NET]]></category>
		<category><![CDATA[Visual Basic]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=657</guid>
		<description><![CDATA[This is a simple VB.NET Extension for converting Datasets and Datatables into CSV formatted files. Simply call .ToCSV() and you will be returned a CSV formatted string or an array of CSV formatted strings. There is also an option to display null values as NULL or simply leave them as a blank space. //Code Imports [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple VB.NET Extension for converting Datasets and Datatables into CSV formatted files.  Simply call .ToCSV() and you will be returned a CSV formatted string or an array of CSV formatted strings.  There is also an option to display null values as NULL or simply leave them as a blank space.</p>
<h3>//Code</h3>
<hr />
<pre class="brush: vb;">
Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Data

''' &lt;summary&gt;
''' EXTENDS DATASETS AND DATATABLES TO GIVE THEM THE ABILITY TO EXPORT TO CSV FORMATTED FILES
''' &lt;/summary&gt;
Module DataExtensions

    ''' &lt;summary&gt;
    ''' EXPORTS A DATATABLE INTO A CSV FORMATTED FILE
    ''' &lt;/summary&gt;
    ''' &lt;param name=&quot;tmpTable&quot;&gt;INPUT DATATABLE TO CONVERT TO CSV&lt;/param&gt;
    ''' &lt;param name=&quot;showNull&quot;&gt;DISPLAY NULL IN EVENT OF NULL OR BLANK LINE&lt;/param&gt;
    ''' &lt;returns&gt;RETURNS A CSV FORMATTED STRING WHICH CAN BE WRITTEN TO A FILE&lt;/returns&gt;
    &lt;Extension()&gt; _
    Public Function ToCSV(ByVal tmpTable As DataTable, ByVal showNull As Boolean) As String
        Dim tmpResult As New StringBuilder()

        'INSERT THE COLUMN HEADERS INTO THE RETURN
        For Each tmpCcol As DataColumn In tmpTable.Columns
            tmpResult.Append(String.Format(&quot;&quot;&quot;{0}&quot;&quot;,&quot;, tmpCcol.ColumnName))
        Next
        tmpResult.AppendLine()

        'INSERT EACH ROWS LINE INTO THE RETURN
        For Each tmpRow As DataRow In tmpTable.Rows
            Dim tmpLine As New StringBuilder()
            For Each tmpCcol As DataColumn In tmpTable.Columns
                If (Not IsDBNull(tmpRow(tmpCcol.ColumnName))) Then
                    tmpLine.Append(String.Format(&quot;&quot;&quot;{0}&quot;&quot;,&quot;, tmpRow(tmpCcol.ColumnName)))
                Else
                    'IF THE USER WANTS TO SEE NULL THEN DISPLAY IT, OTHERWISE JUST A BLANK SPOT
                    If showNull Then
                        tmpLine.Append(&quot;&quot;&quot;NULL&quot;&quot;,&quot;)
                    Else
                        tmpLine.Append(&quot;,&quot;)
                    End If
                End If
            Next

            'APPEND THE ROW TO THE OVERALL RESULT TABLE
            tmpResult.AppendLine(tmpLine.ToString().Substring(0, tmpLine.Length - 1))
        Next

        'RETURN THE TABLE STRING
        Return tmpResult.ToString()
    End Function

    ''' &lt;summary&gt;
    ''' EXPORTS A DATASET INTO AN ARRAY OF CSV FORMATTED FILES
    ''' &lt;/summary&gt;
    ''' &lt;param name=&quot;tmpData&quot;&gt;INPUT DATASET TO BE CONVERTED INTO CSV FILES&lt;/param&gt;
    ''' &lt;param name=&quot;showNull&quot;&gt;DISPLAY NULL IN EVENT OF NULL OR BLANK LINE&lt;/param&gt;
    ''' &lt;returns&gt;RETURNS A CSV FORMATTED STRING ARRAY WHICH CAN BE WRITTEN TO A SERIES OF FILES&lt;/returns&gt;
    &lt;Extension()&gt; _
    Public Function ToCSV(ByVal tmpData As DataSet, ByVal showNull As Boolean) As String()
        Dim result(tmpData.Tables.Count - 1) As String

        For I As Integer = 0 To tmpData.Tables.Count - 1
            'STORE THE RETURN OF EACH TABLE INTO THE ARRAY
            result(I) = tmpData.Tables(I).ToCSV(showNull)
        Next

        'RETURN THE FULL RESULT
        Return result
    End Function

End Module
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Exporting%20Datasets%20and%20Datatables%20to%20CSV%20Extension%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fexporting-datasets-and-datatables-to-csv-extension%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fexporting-datasets-and-datatables-to-csv-extension%2F&amp;title=Exporting%20Datasets%20and%20Datatables%20to%20CSV%20Extension&amp;bodytext=This%20is%20a%20simple%20VB.NET%20Extension%20for%20converting%20Datasets%20and%20Datatables%20into%20CSV%20formatted%20files.%20%20Simply%20call%20.ToCSV%28%29%20and%20you%20will%20be%20returned%20a%20CSV%20formatted%20string%20or%20an%20array%20of%20CSV%20formatted%20strings.%20%20There%20is%20also%20an%20option%20to%20display%20null%20va" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fexporting-datasets-and-datatables-to-csv-extension%2F&amp;title=Exporting%20Datasets%20and%20Datatables%20to%20CSV%20Extension" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fexporting-datasets-and-datatables-to-csv-extension%2F&amp;title=Exporting%20Datasets%20and%20Datatables%20to%20CSV%20Extension&amp;notes=This%20is%20a%20simple%20VB.NET%20Extension%20for%20converting%20Datasets%20and%20Datatables%20into%20CSV%20formatted%20files.%20%20Simply%20call%20.ToCSV%28%29%20and%20you%20will%20be%20returned%20a%20CSV%20formatted%20string%20or%20an%20array%20of%20CSV%20formatted%20strings.%20%20There%20is%20also%20an%20option%20to%20display%20null%20va" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/exporting-datasets-and-datatables-to-csv-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>List Of Objects To XMLNodes</title>
		<link>http://michael.chanceyjr.com/useful-code/list-of-objects-to-xmlnodes/</link>
		<comments>http://michael.chanceyjr.com/useful-code/list-of-objects-to-xmlnodes/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 15:11:31 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Collections]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Extension]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[Serialize]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=627</guid>
		<description><![CDATA[This is an extension to create an XML representation of an array of classes or structures. Currently it only supports basic types which are not nested. This could be adapted to accomodate nested classes with fairly minimal changes. //Code /// &#60;summary&#62; /// RETURNS AN XML NODE WHICH CONTAINS ALL THE PROPERTIES FOR A LIST OF [...]]]></description>
			<content:encoded><![CDATA[<p>This is an extension to create an XML representation of an array of classes or structures.  Currently it only supports basic types which are not nested.  This could be adapted to accomodate nested classes with fairly minimal changes.</p>
<h3>//Code</h3>
<hr />
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// RETURNS AN XML NODE WHICH CONTAINS ALL THE PROPERTIES FOR A LIST OF BASIC TYPES
/// &lt;/summary&gt;
/// &lt;typeparam name=&quot;t&quot;&gt;PARAMETER TYPE WITHIN THE LIST&lt;/typeparam&gt;
/// &lt;param name=&quot;obj&quot;&gt;INCOMING LIST TO ITERATE THROUGH&lt;/param&gt;
/// &lt;param name=&quot;ElementName&quot;&gt;ROOT ELEMENT NAME TO CREATE&lt;/param&gt;
/// &lt;returns&gt;AN XML NODE WHICH CONTAINS ALL THE PROPERTIES FOR A LIST OF BASIC TYPES&lt;/returns&gt;
public static XElement CreateXMLNode&lt;t&gt;(this IEnumerable&lt;t&gt; obj, string ElementName)
{
    //NODE WHICH WILL BE RETURNED TO THE CALLING FUNCTION
    XElement tmpReturn = new XElement(ElementName);

    //LOOP THROUGH ALL THE INTERNAL OBJECTS TO ADD NODES TO THE ROOT
    foreach (object tmpObj in obj)
    {
        //TEMP NODE REPRESENTING THE PROPERTY ELEMENT
        XElement tmpNode = new XElement(tmpObj.GetType().Name.ToString());

        //LOOP THROUGH ALL THE FIELDS WHICH ARE PUBLIC
        foreach (FieldInfo tmpField in tmpObj.GetType().GetFields())
        {
            XElement tmpElement = new XElement(tmpField.Name);

            //IF THE FIELD IS PUBLIC THEN ADD THE FIELD TO THE NODE
            if (tmpField.IsPublic)
            {
                tmpElement.Value = tmpField.GetValue(tmpObj).ToString();
                tmpNode.Add(tmpElement);
            }
        }

        //LOOP THROUGH ALL THE PROPERTIES WHICH ARE PUBLIC
        foreach (PropertyInfo tmpProp in tmpObj.GetType().GetProperties())
        {
            XElement tmpElement = new XElement(tmpProp.Name);

            //ADD THE ELEMENT TO THE NODE
            tmpElement.Value = tmpProp.GetValue(tmpObj, null).ToString();
            tmpNode.Add(tmpElement);
        }

        //RETURN THE ROOT NODE TO THE CALLING FUNCTION
        tmpReturn.Add(tmpNode);
    }

    return tmpReturn;
}
</pre>
<h3>//Usage</h3>
<hr />
<pre class="brush: csharp;">
class Program
{
    static void Main(string[] args)
    {
        //CREATE A LIST OF CLASSES
        List&lt;MyClass&gt; tmpList1 = new List&lt;MyClass&gt;();
        tmpList1.Add(new MyClass() { EmployeeName = &quot;Emp 1&quot;, Address = &quot;Add 1&quot;, Salary = 100000 });
        tmpList1.Add(new MyClass() { EmployeeName = &quot;Emp 2&quot;, Address = &quot;Add 2&quot;, Salary = 50000 });
        tmpList1.Add(new MyClass() { EmployeeName = &quot;Emp 3&quot;, Address = &quot;Add 3&quot;, Salary = 65000 });
        tmpList1.Add(new MyClass() { EmployeeName = &quot;Emp 4&quot;, Address = &quot;Add 4&quot;, Salary = 80000 });

        //CREATE A LIST OF STRUCTS
        List&lt;MyStruct&gt; tmpList2 = new List&lt;MyStruct&gt;();
        tmpList2.Add(new MyStruct() { EmployeeName = &quot;Emp 1&quot;, Address = &quot;Add 1&quot;, Salary = 100000 });
        tmpList2.Add(new MyStruct() { EmployeeName = &quot;Emp 2&quot;, Address = &quot;Add 2&quot;, Salary = 50000 });
        tmpList2.Add(new MyStruct() { EmployeeName = &quot;Emp 3&quot;, Address = &quot;Add 3&quot;, Salary = 65000 });
        tmpList2.Add(new MyStruct() { EmployeeName = &quot;Emp 4&quot;, Address = &quot;Add 4&quot;, Salary = 80000 });

        //CREATE XML NODE CONTAINING THE LIST OF OBJECTS CREATED ABOVE
        XElement root1 = tmpList1.CreateXMLNode(&quot;MyList_Of_Classes&quot;);
        XElement root2 = tmpList2.CreateXMLNode(&quot;MyList_Of_Structs&quot;);
    }
}

//BASIC CLASS CONTAINING PUBLIC PROPERTIES
class MyClass
{
    public string EmployeeName { get; set; }
    public string Address { get; set; }
    public double Salary { get; set; }
}

//BASIC STRUCTURE CONTAINING PUBLIC FIELDS
struct MyStruct
{
    public string EmployeeName;
    public string Address;
    public double Salary;
}
</pre>
<h3>//Output</h3>
<hr />
<pre class="brush: xml;">
&lt;MyList_Of_Classes&gt;
  &lt;MyClass&gt;
    &lt;EmployeeName&gt;Emp 1&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 1&lt;/Address&gt;
    &lt;Salary&gt;100000&lt;/Salary&gt;
  &lt;/MyClass&gt;
  &lt;MyClass&gt;
    &lt;EmployeeName&gt;Emp 2&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 2&lt;/Address&gt;
    &lt;Salary&gt;50000&lt;/Salary&gt;
  &lt;/MyClass&gt;
  &lt;MyClass&gt;
    &lt;EmployeeName&gt;Emp 3&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 3&lt;/Address&gt;
    &lt;Salary&gt;65000&lt;/Salary&gt;
  &lt;/MyClass&gt;
  &lt;MyClass&gt;
    &lt;EmployeeName&gt;Emp 4&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 4&lt;/Address&gt;
    &lt;Salary&gt;80000&lt;/Salary&gt;
  &lt;/MyClass&gt;
&lt;/MyList_Of_Classes&gt;

&lt;MyList_Of_Structs&gt;
  &lt;MyStruct&gt;
    &lt;EmployeeName&gt;Emp 1&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 1&lt;/Address&gt;
    &lt;Salary&gt;100000&lt;/Salary&gt;
  &lt;/MyStruct&gt;
  &lt;MyStruct&gt;
    &lt;EmployeeName&gt;Emp 2&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 2&lt;/Address&gt;
    &lt;Salary&gt;50000&lt;/Salary&gt;
  &lt;/MyStruct&gt;
  &lt;MyStruct&gt;
    &lt;EmployeeName&gt;Emp 3&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 3&lt;/Address&gt;
    &lt;Salary&gt;65000&lt;/Salary&gt;
  &lt;/MyStruct&gt;
  &lt;MyStruct&gt;
    &lt;EmployeeName&gt;Emp 4&lt;/EmployeeName&gt;
    &lt;Address&gt;Add 4&lt;/Address&gt;
    &lt;Salary&gt;80000&lt;/Salary&gt;
  &lt;/MyStruct&gt;
&lt;/MyList_Of_Structs&gt;
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=List%20Of%20Objects%20To%20XMLNodes%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Flist-of-objects-to-xmlnodes%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Flist-of-objects-to-xmlnodes%2F&amp;title=List%20Of%20Objects%20To%20XMLNodes&amp;bodytext=This%20is%20an%20extension%20to%20create%20an%20XML%20representation%20of%20an%20array%20of%20classes%20or%20structures.%20%20Currently%20it%20only%20supports%20basic%20types%20which%20are%20not%20nested.%20%20This%20could%20be%20adapted%20to%20accomodate%20nested%20classes%20with%20fairly%20minimal%20changes.%0D%0A%0D%0A%2F%2FCode%0D%0A%0D%0A%5Bcs" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Flist-of-objects-to-xmlnodes%2F&amp;title=List%20Of%20Objects%20To%20XMLNodes" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Flist-of-objects-to-xmlnodes%2F&amp;title=List%20Of%20Objects%20To%20XMLNodes&amp;notes=This%20is%20an%20extension%20to%20create%20an%20XML%20representation%20of%20an%20array%20of%20classes%20or%20structures.%20%20Currently%20it%20only%20supports%20basic%20types%20which%20are%20not%20nested.%20%20This%20could%20be%20adapted%20to%20accomodate%20nested%20classes%20with%20fairly%20minimal%20changes.%0D%0A%0D%0A%2F%2FCode%0D%0A%0D%0A%5Bcs" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/list-of-objects-to-xmlnodes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Read File From FTP Using C#</title>
		<link>http://michael.chanceyjr.com/useful-code/read-file-from-ftp-using-c/</link>
		<comments>http://michael.chanceyjr.com/useful-code/read-file-from-ftp-using-c/#comments</comments>
		<pubDate>Tue, 18 May 2010 15:30:36 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[FTP]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Stream]]></category>
		<category><![CDATA[TCP/IP]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=624</guid>
		<description><![CDATA[Here is a small snippet on reading a text file from an FTP server. This could be replaced with a binary file or any other type; I just used a text file to keep it simple. Code //CREATE AN FTP REQUEST WITH THE DOMAIN AND CREDENTIALS System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(&#34;ftp://domain.com/file.txt&#34;); tmpReq.Credentials = new System.Net.NetworkCredential(&#34;userName&#34;, &#34;Password&#34;); [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a small snippet on reading a text file from an FTP server.  This could be replaced with a binary file or any other type; I just used a text file to keep it simple.</p>
<h3>Code</h3>
<hr/>
<pre class="brush: csharp;">
            //CREATE AN FTP REQUEST WITH THE DOMAIN AND CREDENTIALS
            System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(&quot;ftp://domain.com/file.txt&quot;);
            tmpReq.Credentials = new System.Net.NetworkCredential(&quot;userName&quot;, &quot;Password&quot;);

            //GET THE FTP RESPONSE
            using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
            {
                //GET THE STREAM TO READ THE RESPONSE FROM
                using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
                {
                    //CREATE A TXT READER (COULD BE BINARY OR ANY OTHER TYPE YOU NEED)
                    using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
                    {
                        //STORE THE FILE CONTENTS INTO A STRING
                        string fileContents = tmpReader.ReadToEnd();

                        //DO SOMETHING WITH SAID FILE CONTENTS
                    }
                }
            }
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Read%20File%20From%20FTP%20Using%20C%23%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fread-file-from-ftp-using-c%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fread-file-from-ftp-using-c%2F&amp;title=Read%20File%20From%20FTP%20Using%20C%23&amp;bodytext=Here%20is%20a%20small%20snippet%20on%20reading%20a%20text%20file%20from%20an%20FTP%20server.%20%20This%20could%20be%20replaced%20with%20a%20binary%20file%20or%20any%20other%20type%3B%20I%20just%20used%20a%20text%20file%20to%20keep%20it%20simple.%0D%0A%0D%0ACode%0D%0A%0D%0A%5Bcsharp%5D%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2FCREATE%20AN%20FTP%20REQUEST%20WITH%20THE%20DOMAIN%20AND%20C" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fread-file-from-ftp-using-c%2F&amp;title=Read%20File%20From%20FTP%20Using%20C%23" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fread-file-from-ftp-using-c%2F&amp;title=Read%20File%20From%20FTP%20Using%20C%23&amp;notes=Here%20is%20a%20small%20snippet%20on%20reading%20a%20text%20file%20from%20an%20FTP%20server.%20%20This%20could%20be%20replaced%20with%20a%20binary%20file%20or%20any%20other%20type%3B%20I%20just%20used%20a%20text%20file%20to%20keep%20it%20simple.%0D%0A%0D%0ACode%0D%0A%0D%0A%5Bcsharp%5D%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2FCREATE%20AN%20FTP%20REQUEST%20WITH%20THE%20DOMAIN%20AND%20C" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/read-file-from-ftp-using-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ini File Processing</title>
		<link>http://michael.chanceyjr.com/useful-code/ini-file-processing/</link>
		<comments>http://michael.chanceyjr.com/useful-code/ini-file-processing/#comments</comments>
		<pubDate>Thu, 13 May 2010 16:38:40 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[.ini]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Ini File]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=611</guid>
		<description><![CDATA[This is a class which will allow you to read old style .ini files. Sometimes you have an app which uses .ini and you need to read it in for whatever reason. Or perhaps you are looking to store your own apps settings in a .ini file because its what people are used to. In [...]]]></description>
			<content:encoded><![CDATA[<p>This is a class which will allow you to read old style .ini files.  Sometimes you have an app which uses .ini and you need to read it in for whatever reason.  Or perhaps you are looking to store your own apps settings in a .ini file because its what people are used to.  In any event here is a sample .ini file this class will process.</p>
<h3>Ini File</h3>
<hr/>
<blockquote><p>
[Section 1]<br />
Test = 1<br />
Test2 = 1</p>
<p>[Section 2]<br />
blah = foo<br />
foo = blah</p>
<p>[Section 3]<br />
var = more settings<br />
test = this will handle = signs as part of the value also
</p></blockquote>
<h3>Sample Code</h3>
<hr/>
<pre class="brush: csharp;">
            IniFileReaderLib.IniFile tmpIni = new IniFileReaderLib.IniFile(&quot;Settings.ini&quot;);
            Console.WriteLine(tmpIni.Section[&quot;Section 1&quot;][&quot;test&quot;]);
</pre>
<h3>Code</h3>
<hr/>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;

namespace IniFileReaderLib
{
    /// &lt;summary&gt;
    /// PROVIDES ROUTINES FOR READING AND PROCESSING A .INI FILE
    /// &lt;/summary&gt;
    public class IniFile
    {
        /// &lt;summary&gt;
        /// HOLDS ALL THE VARIABLES LISTED IN THE INI FILE BASED ON obj[&quot;Section&quot;][&quot;Setting&quot;]
        /// &lt;/summary&gt;
        public Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; Section { get; set; }

        /// &lt;summary&gt;
        /// DID THE FILE CONTAIN ERRORS WHEN ATTEMPTING TO LOAD
        /// &lt;/summary&gt;
        public bool HasErrors { get; set; }

        /// &lt;summary&gt;
        /// WHAT WERE THE ERRORS CONTAINED IN THE FILE
        /// &lt;/summary&gt;
        public List&lt;string&gt; Errors { get; set; }

        /// &lt;summary&gt;
        /// FILENAME OF THE INI FILE WE ARE PROCESSING
        /// &lt;/summary&gt;
        public string FileName { get; set; }

        /// &lt;summary&gt;
        /// CLASS INITIALIZER
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;FileName&quot;&gt;FILENAME TO PROCESS&lt;/param&gt;
        public IniFile(string FileName)
        {
            //STORE THE NAME OF THE FILE WE ARE TO PROCESS
            this.FileName = FileName;

            //PROCESS THE FILE
            ReloadFile();
        }

        /// &lt;summary&gt;
        /// RELOAD THE INI FILE INCASE IT HAS CHANGED SINCE THIS CLASS WAS CREATED
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;FileName&quot;&gt;FILENAME OF THE INIFILE TO PROCESS&lt;/param&gt;
        public void ReloadFile()
        {
            //CLEAR OUT ALL THE VALUES BY RELEASING THE OBJECT
            Section = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;(StringComparer.CurrentCultureIgnoreCase);
            Errors = new List&lt;string&gt;();

            //CREATE A TEXT READER TO READ THE INI FILE
            using (TextReader tmpReader = (TextReader)File.OpenText(FileName))
            {
                string tmpLine = null;
                string curSection = null;

                //LOOP THROUGH THE ENTIRE FILE ADDING VARIABLES TO THE SECTION
                while ((tmpLine = tmpReader.ReadLine()) != null)
                {
                    //IF THE LINE IS A SECTION THEN ADD IT TO THE SECTIONS AND START ADDING VARIABLES TO THE SECTION
                    if (Regex.Match(tmpLine, @&quot;[[].*[]]&quot;).Success)
                    {
                        //PARSE THE SECTION OUT OF THE STRING AND APPEND IT TO THE LIST OF SECTIONS
                        curSection = Regex.Match(tmpLine, @&quot;[[](?&lt;Section&gt;.*)[]]&quot;).Groups[&quot;Section&quot;].Value;
                        Section[curSection] = new Dictionary&lt;string, string&gt;(StringComparer.CurrentCultureIgnoreCase);
                    }
                    else
                    {
                        try
                        {
                            //IF THERE IS DATA ON THE LINE THEN TRY TO PROCESS IT
                            if (!string.IsNullOrEmpty(tmpLine) &amp;&amp; tmpLine.Contains(&quot;=&quot;))
                            {
                                //SPLIT THE STRING UP SO WE CAN GET THE VAR TO THE LEFT OF THE = SIGN
                                string[] curPair = tmpLine.Split('=');

                                //ADD THE ITEM TO THE COLLECTION AND MAKE SURE TO PIECE ANYTHING BACK TOGETHER ON THE RIGHT OF THE FIRST = SIGN
                                Section[curSection].Add(curPair[0].Trim(), string.Join(&quot;=&quot;, curPair.Skip(1).ToArray()).Trim());
                            }
                        }
                        catch(Exception e)
                        {
                            //TRACK THAT AN ERROR WAS THROWN
                            HasErrors = true;

                            //ADD THE MESSAGE TO THE ERROR LIST
                            Errors.Add(e.Message);
                        }
                    }
                }
            }
        }
    }
}
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Ini%20File%20Processing%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fini-file-processing%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fini-file-processing%2F&amp;title=Ini%20File%20Processing&amp;bodytext=This%20is%20a%20class%20which%20will%20allow%20you%20to%20read%20old%20style%20.ini%20files.%20%20Sometimes%20you%20have%20an%20app%20which%20uses%20.ini%20and%20you%20need%20to%20read%20it%20in%20for%20whatever%20reason.%20%20Or%20perhaps%20you%20are%20looking%20to%20store%20your%20own%20apps%20settings%20in%20a%20.ini%20file%20because%20its%20what%20" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fini-file-processing%2F&amp;title=Ini%20File%20Processing" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fini-file-processing%2F&amp;title=Ini%20File%20Processing&amp;notes=This%20is%20a%20class%20which%20will%20allow%20you%20to%20read%20old%20style%20.ini%20files.%20%20Sometimes%20you%20have%20an%20app%20which%20uses%20.ini%20and%20you%20need%20to%20read%20it%20in%20for%20whatever%20reason.%20%20Or%20perhaps%20you%20are%20looking%20to%20store%20your%20own%20apps%20settings%20in%20a%20.ini%20file%20because%20its%20what%20" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/ini-file-processing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress Keywords and Description Meta Tags</title>
		<link>http://michael.chanceyjr.com/useful-code/wordpress-keywords-and-description-meta-tags/</link>
		<comments>http://michael.chanceyjr.com/useful-code/wordpress-keywords-and-description-meta-tags/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 15:15:20 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=550</guid>
		<description><![CDATA[The code below allows you to add keywoards and description meta tags to any wordpress theme. Simple copy the below code and insert it into the header.php of your theme somewhere inside of the &#60;head&#62;&#60;/head&#62; tag. You could also simply download the plugin I wrote for this as well. Although I have submitted it to [...]]]></description>
			<content:encoded><![CDATA[<p>The code below allows you to add keywoards and description meta tags to any wordpress theme.  Simple copy the below code and insert it into the header.php of your theme somewhere inside of the &lt;head&gt;&lt;/head&gt; tag.</p>
<p>You could also simply download the plugin I wrote for this as well.  Although I have submitted it to WordPress.org they have not posted it yet so here is a link in the mean time.  Please note the plugin is a little more customizable then the code below.</p>
<p><a href="http://michael.chanceyjr.com/free-stuff/auto-keywords-and-description-generator/">-Auto Keywords and Description Generator-</a></p>
<h3>//Code</h3>
<hr/>
<pre class="brush: php;">
&lt;?php
$keywords = &quot;&quot;;
$description = &quot;&quot;;

if(is_home() || is_front_page())
{
	//LOAD KEYWORDS FROM USER SPECIFIED STRING
	$keywords = &quot;Insert your homepage keywords here&quot;;

	//LOAD DESCRIPTION FROM BLOGINFO
	$description = bloginfo('description');
}
elseif(is_single())
{
	//LOAD POST TITLE AS DESCRIPTION
	$description = $post-&gt;post_title;

	//BUILD LIST OF KEYWORDS FROM TAGS
	$tags = wp_get_post_tags($post-&gt;ID);
	foreach($tags as $tag)
		$keywords = $keywords . $tag-&gt;name . &quot;, &quot;;
}
elseif(is_category())
{
	//LOAD CATEGORY DESCRIPTION
	$keywords = single_cat_title('', false);
	$description = category_description();
}
?&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;&lt;?php echo $keywords ?&gt;&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;&lt;?php echo $description ?&gt;&quot; /&gt;
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Wordpress%20Keywords%20and%20Description%20Meta%20Tags%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fwordpress-keywords-and-description-meta-tags%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fwordpress-keywords-and-description-meta-tags%2F&amp;title=Wordpress%20Keywords%20and%20Description%20Meta%20Tags&amp;bodytext=The%20code%20below%20allows%20you%20to%20add%20keywoards%20and%20description%20meta%20tags%20to%20any%20wordpress%20theme.%20%20Simple%20copy%20the%20below%20code%20and%20insert%20it%20into%20the%20header.php%20of%20your%20theme%20somewhere%20inside%20of%20the%20%26lt%3Bhead%26gt%3B%26lt%3B%2Fhead%26gt%3B%20tag.%0D%0A%0D%0AYou%20could%20also%20simply%20d" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fwordpress-keywords-and-description-meta-tags%2F&amp;title=Wordpress%20Keywords%20and%20Description%20Meta%20Tags" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fwordpress-keywords-and-description-meta-tags%2F&amp;title=Wordpress%20Keywords%20and%20Description%20Meta%20Tags&amp;notes=The%20code%20below%20allows%20you%20to%20add%20keywoards%20and%20description%20meta%20tags%20to%20any%20wordpress%20theme.%20%20Simple%20copy%20the%20below%20code%20and%20insert%20it%20into%20the%20header.php%20of%20your%20theme%20somewhere%20inside%20of%20the%20%26lt%3Bhead%26gt%3B%26lt%3B%2Fhead%26gt%3B%20tag.%0D%0A%0D%0AYou%20could%20also%20simply%20d" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/wordpress-keywords-and-description-meta-tags/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String Truncating Extension</title>
		<link>http://michael.chanceyjr.com/useful-code/string-truncating-extension/</link>
		<comments>http://michael.chanceyjr.com/useful-code/string-truncating-extension/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 10:12:00 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Extension]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Truncate]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=539</guid>
		<description><![CDATA[This is a simple extension to truncate strings on whole words. If it can not find a whole word to truncate on then it will fall back to breaking a word up. You can also pass a string to append to the end of the truncated string. Other then that there is not a whole [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple extension to truncate strings on whole words.  If it can not find a whole word to truncate on then it will fall back to breaking a word up.  You can also pass a string to append to the end of the truncated string.  Other then that there is not a whole lot to say about this one.</p>
<h3>//Code</h3>
<hr/>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// TRUNCATES A STRING PREFERRING WHOLE WORD OVER NON WHOLE WORD
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;s&quot;&gt;INCOMING STRING TO TRUNCATE&lt;/param&gt;
        /// &lt;param name=&quot;len&quot;&gt;LENGTH IN WHICH TO TRUNCATE TO&lt;/param&gt;
        /// &lt;param name=&quot;postTruncate&quot;&gt;ANYTHING TO ADD TO A TRUNCATED STRING SUCH AS ...&lt;/param&gt;
        /// &lt;returns&gt;TRUNCATED STRING WITH POST TRUNCATE ADDED TO IT&lt;/returns&gt;
        public static string Truncate(this string s, int len, string postTruncate)
        {
            //IF THE STRING IS SMALLER THEN THE LENGTH JUST RETURN THE STRING
            if (s == null || s.Length &lt; len)
                return s;
            else
            {
                //INCASE NULL HAS BEEN PASSED IN CHANGE IT TO EMPTY STRING SO IT HAS A COUNT
                if (postTruncate == null)
                    postTruncate = string.Empty;

                //RETURN THE TRUNCATED STRING BACK TO CALLING FUNCTION
                string tmpReturn = string.Concat(Regex.Match(String.Concat(s, &quot; &quot;), string.Format(&quot;^(?&lt;tmpMatch&gt;.{{0,{0}}})\\s&quot;, len)).Groups[&quot;tmpMatch&quot;].Value, postTruncate);

                //IF THE WHOLE WORD TRUNCATE WORKED THEN USE IT OTHERWISE USE NON WHOLE WORD TRUNCATE
                if (tmpReturn != postTruncate)
                    return tmpReturn;
                else
                    return string.Concat(Regex.Match(String.Concat(s, &quot; &quot;), string.Format(&quot;^(?&lt;tmpMatch&gt;.{{0,{0}}})&quot;, len)).Groups[&quot;tmpMatch&quot;].Value, postTruncate);
            }
        }
</pre>
<h3>//Usage</h3>
<hr/>
<pre class="brush: csharp;">
    class Program
    {
        static void Main(string[] args)
        {
            //OUTPUT WILL BE &quot;Hello, World...&quot;
            Console.WriteLine(&quot;Hello, World this is some long text to truncate&quot;.Truncate(15, &quot;...&quot;));
            Console.ReadLine();
        }
    }
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=String%20Truncating%20Extension%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fstring-truncating-extension%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fstring-truncating-extension%2F&amp;title=String%20Truncating%20Extension&amp;bodytext=This%20is%20a%20simple%20extension%20to%20truncate%20strings%20on%20whole%20words.%20%20If%20it%20can%20not%20find%20a%20whole%20word%20to%20truncate%20on%20then%20it%20will%20fall%20back%20to%20breaking%20a%20word%20up.%20%20You%20can%20also%20pass%20a%20string%20to%20append%20to%20the%20end%20of%20the%20truncated%20string.%20%20Other%20then%20that%20th" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fstring-truncating-extension%2F&amp;title=String%20Truncating%20Extension" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fstring-truncating-extension%2F&amp;title=String%20Truncating%20Extension&amp;notes=This%20is%20a%20simple%20extension%20to%20truncate%20strings%20on%20whole%20words.%20%20If%20it%20can%20not%20find%20a%20whole%20word%20to%20truncate%20on%20then%20it%20will%20fall%20back%20to%20breaking%20a%20word%20up.%20%20You%20can%20also%20pass%20a%20string%20to%20append%20to%20the%20end%20of%20the%20truncated%20string.%20%20Other%20then%20that%20th" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/string-truncating-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Password Complexity</title>
		<link>http://michael.chanceyjr.com/useful-code/testing-password-complexity/</link>
		<comments>http://michael.chanceyjr.com/useful-code/testing-password-complexity/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 05:15:17 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Password Complexity]]></category>
		<category><![CDATA[RegEx]]></category>
		<category><![CDATA[Regular Expressions]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=534</guid>
		<description><![CDATA[Password complexity is a huge deal when a company is applying for its compliance so below is a simple function to test for password complexity based on a rule set passed in. The following code allows for any of the following rules to be applied to a password. You can elect to require any or [...]]]></description>
			<content:encoded><![CDATA[<p>Password complexity is a huge deal when a company is applying for its compliance so below is a simple function to test for password complexity based on a rule set passed in.  The following code allows for any of the following rules to be applied to a password.  You can elect to require any or all of the following 1 upper case character, 1 lower case character, 1 numeric character and 1 special character.</p>
<h3>//Function</h3>
<hr/>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// FUNCTION FOR TESTING PASSWORD COMPLEXITY
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;s&quot;&gt;INCOMING PASSWORD TO TEST&lt;/param&gt;
        /// &lt;param name=&quot;minLength&quot;&gt;MIN LENGTH OF PASSWORD&lt;/param&gt;
        /// &lt;param name=&quot;maxLength&quot;&gt;MAX LENGTH OF PASSWORD&lt;/param&gt;
        /// &lt;param name=&quot;rule&quot;&gt;COMPARISON FLAGS CAN BE ANY COMBINATION OF THE FOLLOWING - UPPER, LOWER, NUMERIC, SPECIAL&lt;/param&gt;
        /// &lt;returns&gt;TRUE OR FALSE IF THE PASSWORD PASSES OR NOT&lt;/returns&gt;
        static bool ValidatePasswordComplexity(string s, int minLength, int maxLength, PasswordRules rule)
        {
            //CONSTANTS FOR COMPARISON GROUPS
            const string UPPER = &quot;(?=.*[A-Z])&quot;;
            const string LOWER = &quot;(?=.*[a-z])&quot;;
            const string NUMERIC = &quot;(?=.*[0-9])&quot;;
            const string SPECIAL = &quot;(?=.*[!@#$%^&amp;*()&lt;&gt;])&quot;;

            //CREATE A NEW VAR TO HOLD THE COMPARE STRING WHILE ITS ASSEMBLED
            StringBuilder tmpCompare = new StringBuilder(&quot;^&quot;);

            //CHECK IF UPPER IS A REQUIREMENT
            if ((rule &amp; PasswordRules.Upper) == PasswordRules.Upper)
                tmpCompare.Append(UPPER);

            //CHECK IF LOWER IS A REQUIREMENT
            if ((rule &amp; PasswordRules.Lower) == PasswordRules.Lower)
                tmpCompare.Append(LOWER);

            //CHECK IF NUMERIC IS A REQUIREMENT
            if ((rule &amp; PasswordRules.Numeric) == PasswordRules.Numeric)
                tmpCompare.Append(NUMERIC);

            //CHECK IF SPECIAL IS A REQUIREMENT
            if ((rule &amp; PasswordRules.Special) == PasswordRules.Special)
                tmpCompare.Append(SPECIAL);

            //APPEND THE LENGTH REQUIREMENTS
            tmpCompare.Append(string.Format(&quot;.{{{0},{1}}}&quot;, minLength, maxLength));

            //RETURN THE RESULT OF THE COMPARISON
            return Regex.Match(s, tmpCompare.ToString()).Success;
        }

        /// &lt;summary&gt;
        /// ERNUMERATIONS FOR PASSWORD COMPLEXITY TESTING
        /// &lt;/summary&gt;
        [Flags]
        public enum PasswordRules
        {
            Upper = 1,
            Lower = 2,
            Numeric = 4,
            Special = 8,
        }
</pre>
<h3>//Usage</h3>
<hr/>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// MAIN APPLICATION ENTRY POINT
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;args&quot;&gt;&lt;/param&gt;
        static void Main(string[] args)
        {
            //SOMETHING TO COMPARE
            string pwd = &quot;Password1&quot;;

            //TWO DIFFERENT SAMPLES TO SHOW THE PASSWORD MEETS THE REQUIREMENTS IF YOU ARE NOT LOOKING FOR A SPECIAL CHARACTER
            //BUT FAILS ONCE THE SPECIAL REQUIREMENT IS ADDED TO THE PARAMETER
            Console.WriteLine(&quot;{0}: {1}&quot;, pwd, ValidatePasswordComplexity(pwd, 6, 15, PasswordRules.Upper | PasswordRules.Lower | PasswordRules.Numeric));
            Console.WriteLine(&quot;{0}: {1}&quot;, pwd, ValidatePasswordComplexity(pwd, 6, 15, PasswordRules.Upper | PasswordRules.Lower | PasswordRules.Numeric | PasswordRules.Special));

            //WAIT FOR USER INPUT
            Console.ReadLine();
        }
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Testing%20Password%20Complexity%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Ftesting-password-complexity%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Ftesting-password-complexity%2F&amp;title=Testing%20Password%20Complexity&amp;bodytext=Password%20complexity%20is%20a%20huge%20deal%20when%20a%20company%20is%20applying%20for%20its%20compliance%20so%20below%20is%20a%20simple%20function%20to%20test%20for%20password%20complexity%20based%20on%20a%20rule%20set%20passed%20in.%20%20The%20following%20code%20allows%20for%20any%20of%20the%20following%20rules%20to%20be%20applied%20to%20a" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Ftesting-password-complexity%2F&amp;title=Testing%20Password%20Complexity" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Ftesting-password-complexity%2F&amp;title=Testing%20Password%20Complexity&amp;notes=Password%20complexity%20is%20a%20huge%20deal%20when%20a%20company%20is%20applying%20for%20its%20compliance%20so%20below%20is%20a%20simple%20function%20to%20test%20for%20password%20complexity%20based%20on%20a%20rule%20set%20passed%20in.%20%20The%20following%20code%20allows%20for%20any%20of%20the%20following%20rules%20to%20be%20applied%20to%20a" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/testing-password-complexity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Human Readable Size Formatting Extension</title>
		<link>http://michael.chanceyjr.com/useful-code/human-readable-size-formatting-extension/</link>
		<comments>http://michael.chanceyjr.com/useful-code/human-readable-size-formatting-extension/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 09:34:17 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Extension]]></category>
		<category><![CDATA[Numeric]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=521</guid>
		<description><![CDATA[This is a simple extension to turn unreadable sizes into something that makes more sense to the human eye. This will convert 1024 into 1KB or 1099511627776 into 1GB. This is by no means perfect, some additions could be made such as adding ,&#8217;s to separate the digits into proper grouping. Having said that most [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple extension to turn unreadable sizes into something that makes more sense to the human eye.  This will convert 1024 into 1KB or 1099511627776 into 1GB.  This is by no means perfect, some additions could be made such as adding ,&#8217;s to separate the digits into proper grouping.  Having said that most of the time grouping will be removed because numbers which should be grouped soon fall into the next sizing segment, meaning 1,000B becomes 1KB after only 24 more bytes.</p>
<h3>//Code</h3>
<hr/>
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// MAIN TO HUMAN READABLE FUNCTION TO CONVERT DOUBLES INTO XB, XKB, XMB, XGB
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;x&quot;&gt;INCOMING NUMBER TO MAKE READABLE&lt;/param&gt;
        /// &lt;returns&gt;HUMAN READABLE SIZE FORMAT SUCH AS 1MB&lt;/returns&gt;
        public static string ToHumanReadable(this double x)
        {
            //CONSTANTS FOR SIZING
            double KB = 1024;
            double MB = 1024 * KB;
            double GB = 1024 * MB;

            if (x &lt; KB)
                return string.Format(&quot;{0}B&quot;, x);
            else if (x &lt; MB)
            {
                return string.Format(&quot;{0:0.##}KB&quot;, x / KB);
            }
            else if (x &lt; GB)
            {
                return string.Format(&quot;{0:0.##}MB&quot;, x / MB);
            }
            else if (x &gt;= GB)
            {
                return string.Format(&quot;{0:0.##}GB&quot;, x / GB);
            }
            else
            {
                //HACK: GET RID OF COMPILER ERROR BECAUSE IT BELEIVES NOT ALL PATHS RETURN A VALUE
                return null;
            }
        }

        /// &lt;summary&gt;
        /// EXTENSION FOR LONG TO MAKE HUMAN READABLE
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;x&quot;&gt;INCOMING NUMBER TO MAKE READABLE&lt;/param&gt;
        /// &lt;returns&gt;HUMAN READABLE SIZE FORMAT SUCH AS 1MB&lt;/returns&gt;
        public static string ToHumanReadable(this long x)
        {
            return ToHumanReadable((double)x);
        }

        /// &lt;summary&gt;
        /// EXTENSION FOR INT TO MAKE HUMAN READABLE
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;x&quot;&gt;INCOMING NUMBER TO MAKE READABLE&lt;/param&gt;
        /// &lt;returns&gt;HUMAN READABLE SIZE FORMAT SUCH AS 1MB&lt;/returns&gt;
        public static string ToHumanReadable(this int x)
        {
            return ToHumanReadable((double)x);
        }

        /// &lt;summary&gt;
        /// EXTENSION FOR SINGLE TO MAKE HUMAN READABLE
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;x&quot;&gt;INCOMING NUMBER TO MAKE READABLE&lt;/param&gt;
        /// &lt;returns&gt;HUMAN READABLE SIZE FORMAT SUCH AS 1MB&lt;/returns&gt;
        public static string ToHumanReadable(this Single x)
        {
            return ToHumanReadable((double)x);
        }
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Human%20Readable%20Size%20Formatting%20Extension%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fhuman-readable-size-formatting-extension%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fhuman-readable-size-formatting-extension%2F&amp;title=Human%20Readable%20Size%20Formatting%20Extension&amp;bodytext=This%20is%20a%20simple%20extension%20to%20turn%20unreadable%20sizes%20into%20something%20that%20makes%20more%20sense%20to%20the%20human%20eye.%20%20This%20will%20convert%201024%20into%201KB%20or%201099511627776%20into%201GB.%20%20This%20is%20by%20no%20means%20perfect%2C%20some%20additions%20could%20be%20made%20such%20as%20adding%20%2C%27s%20to%20se" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fhuman-readable-size-formatting-extension%2F&amp;title=Human%20Readable%20Size%20Formatting%20Extension" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fhuman-readable-size-formatting-extension%2F&amp;title=Human%20Readable%20Size%20Formatting%20Extension&amp;notes=This%20is%20a%20simple%20extension%20to%20turn%20unreadable%20sizes%20into%20something%20that%20makes%20more%20sense%20to%20the%20human%20eye.%20%20This%20will%20convert%201024%20into%201KB%20or%201099511627776%20into%201GB.%20%20This%20is%20by%20no%20means%20perfect%2C%20some%20additions%20could%20be%20made%20such%20as%20adding%20%2C%27s%20to%20se" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/human-readable-size-formatting-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interapplication Communication with Named Pipes</title>
		<link>http://michael.chanceyjr.com/useful-code/interapplication-communication-with-named-pipes/</link>
		<comments>http://michael.chanceyjr.com/useful-code/interapplication-communication-with-named-pipes/#comments</comments>
		<pubDate>Sun, 13 Dec 2009 16:30:00 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[Application Communication]]></category>
		<category><![CDATA[Background Communication]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Named Pipes]]></category>
		<category><![CDATA[Stream]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=506</guid>
		<description><![CDATA[Ever make two separate applications but need them to be able to send information back and forth. Say an Instant Messenger and a Business app which need direct integration between one another. Named pipes is a pretty simple solution to achieve this. .NET 3.5 has made this much simpler by including Named Pipes in its [...]]]></description>
			<content:encoded><![CDATA[<p>Ever make two separate applications but need them to be able to send information back and forth.  Say an Instant Messenger and a Business app which need direct integration between one another.  Named pipes is a pretty simple solution to achieve this.  .NET 3.5 has made this much simpler by including Named Pipes in its release, this used to be real nasty when trying to achieve this in any other language then C++.</p>
<h3>//Application</h3>
<hr/>
<pre class="brush: csharp;">
using System;
using System.IO;
using System.IO.Pipes;

class Program
{
    /// &lt;summary&gt;
    /// MAIN APPLICATION THREAD
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;args&quot;&gt;NOTHING IS ACCEPTED HERE&lt;/param&gt;
    static void Main(string[] args)
    {
        //HOLDS THE SECLECTION A USER MAKES AS TO WHAT THEY WANT TO RUN
        string tmpSelection = string.Empty;

        //ASK THE USER WHAT THEY WANT TO DO
        Console.Write(&quot;Please Enter A Selection 1(Server) or 2(Client): &quot;);
        tmpSelection = Console.ReadLine();

        //CLEAR THE SCREEN AND BEGIN RUNNING THE USERS SELECTION
        Console.Clear();
        if (tmpSelection == &quot;1&quot;)
        {
            //START A PIPE SERVER
            pipeServer();
        }
        else if (tmpSelection == &quot;2&quot;)
        {
            //START A PIPE CLIENT
            pipeClient();
        }
        else
        {
            //LET THE USER KNOW THEY HAVE MADE AN INVALID SELECTION
            Console.WriteLine(&quot;Invalid selection made.  This app will now close.&quot;);
            Console.ReadLine();
        }
    }

    /// &lt;summary&gt;
    /// RUNS A PIPE CLIENT FOR SENDING MESSAGES
    /// &lt;/summary&gt;
    private static void pipeClient()
    {
        //LET THE USER KNOW WHAT IS GOING ON
        Console.WriteLine(&quot;Starting Client!&quot;);

        //LOOP FOREVER FOR TESTING PURPOSES
        while (true)
        {
            //CREATE A CONNECTION TO A NAMED PIPE ON THE LOCAL MACHINE NAMED testPipe
            using (NamedPipeClientStream tmpPipe = new NamedPipeClientStream(&quot;.&quot;, &quot;testPipe&quot;, PipeDirection.Out))
            {
                string tmpSendMessage;

                //GET SOME TEXT TO SEND THROUGH THE PIPE
                Console.Write(&quot;Enter Some Text To Send: &quot;);
                tmpSendMessage = Console.ReadLine();

                //SEND THE MESSAGE THROUGH THE PIPE
                tmpPipe.Connect();
                using (TextWriter tmpWriter = new StreamWriter(tmpPipe))
                {
                    tmpWriter.WriteLine(tmpSendMessage);
                }
            }
        }
    }

    /// &lt;summary&gt;
    /// RUNS A PIPE SERVER FOR ACCEPTING MESSAGES
    /// &lt;/summary&gt;
    private static void pipeServer()
    {
        //LET THE USER KNOW WHAT IS GOING ON
        Console.WriteLine(&quot;Starting Server!&quot;);

        //LOOP FOREVER FOR TESTING PURPOSES
        while (true)
        {
            //CREATE A NAMED PIPE ON THE LOCAL MACHINE NAMED testPipe
            using (NamedPipeServerStream tmpPipe = new NamedPipeServerStream(&quot;testPipe&quot;, PipeDirection.In))
            {
                //READ THE DATA ON THE PIPE
                tmpPipe.WaitForConnection();
                using (TextReader tmpReader = new StreamReader(tmpPipe))
                {
                    Console.WriteLine(tmpReader.ReadLine());
                }
            }
        }
    }
}
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Interapplication%20Communication%20with%20Named%20Pipes%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Finterapplication-communication-with-named-pipes%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Finterapplication-communication-with-named-pipes%2F&amp;title=Interapplication%20Communication%20with%20Named%20Pipes&amp;bodytext=Ever%20make%20two%20separate%20applications%20but%20need%20them%20to%20be%20able%20to%20send%20information%20back%20and%20forth.%20%20Say%20an%20Instant%20Messenger%20and%20a%20Business%20app%20which%20need%20direct%20integration%20between%20one%20another.%20%20Named%20pipes%20is%20a%20pretty%20simple%20solution%20to%20achieve%20this." title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Finterapplication-communication-with-named-pipes%2F&amp;title=Interapplication%20Communication%20with%20Named%20Pipes" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Finterapplication-communication-with-named-pipes%2F&amp;title=Interapplication%20Communication%20with%20Named%20Pipes&amp;notes=Ever%20make%20two%20separate%20applications%20but%20need%20them%20to%20be%20able%20to%20send%20information%20back%20and%20forth.%20%20Say%20an%20Instant%20Messenger%20and%20a%20Business%20app%20which%20need%20direct%20integration%20between%20one%20another.%20%20Named%20pipes%20is%20a%20pretty%20simple%20solution%20to%20achieve%20this." title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/interapplication-communication-with-named-pipes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compiling Code at Runtime</title>
		<link>http://michael.chanceyjr.com/useful-code/compiling-code-at-runtime/</link>
		<comments>http://michael.chanceyjr.com/useful-code/compiling-code-at-runtime/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 17:37:52 +0000</pubDate>
		<dc:creator>Michael E. Chancey Jr.</dc:creator>
				<category><![CDATA[Useful Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C-Sharp]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Compiling Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Runtime]]></category>

		<guid isPermaLink="false">http://michael.chanceyjr.com/?p=492</guid>
		<description><![CDATA[This little snippit has only ever been used once by me in an attempt to give the end user the ability to make adjustments to processing scripts. It turned out to be a little bit of a headache because hoping your end user has the skill and ability to code in C# or any language [...]]]></description>
			<content:encoded><![CDATA[<p>This little snippit has only ever been used once by me in an attempt to give the end user the ability to make adjustments to processing scripts.  It turned out to be a little bit of a headache because hoping your end user has the skill and ability to code in C# or any language for that matter is a bit troublesome.  Who knows though you might be able to use this as part of a Visual Studio addin which allows the user to customize the functionality to their likings.  In any event on to some code.</p>
<h3>//Class</h3>
<hr/>
<pre class="brush: csharp;">
    public static class AssemblyBuilder
    {
        /// &lt;summary&gt;
        /// COMPILE CODE INTO A MEMORY DLL
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Code&quot;&gt;PLAIN TEXT OF THE CODE TO BE EXECUTED&lt;/param&gt;
        /// &lt;returns&gt;MEMORY DLL OF COMPILED CODE&lt;/returns&gt;
        static Assembly BuildAssembly(string Code)
        {
            CSharpCodeProvider tmpProvider = new CSharpCodeProvider();
            CompilerParameters tmpParams = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true };

            //ADD ANY ADDITIONAL REFERENCES YOU MAY NEED HERE
            tmpParams.ReferencedAssemblies.Add(&quot;System.dll&quot;);
            tmpParams.ReferencedAssemblies.Add(&quot;System.Windows.Forms.dll&quot;);

            //ATTEMPT TO COMPILE THE CODE INTO A MEMORY DLL
            CompilerResults tmpResults = tmpProvider.CompileAssemblyFromSource(tmpParams, Code);

            //IF IT WORKED THEN RETURN THE COMPILED ASSEMBLY ELSE RETURN NOTHING
            if (!tmpResults.Errors.HasErrors)
                return tmpResults.CompiledAssembly;
            else
                return null;
        }

        /// &lt;summary&gt;
        /// COMPILE AND EXECUTE PLAIN TEXT AS THOUGH IT WERE A LOADED LIBRARY
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;code&quot;&gt;CODE TO COMPILE&lt;/param&gt;
        /// &lt;param name=&quot;namespacename&quot;&gt;NAMESPACE INSIDE THE CODE FROM WHICH TO EXECUTE&lt;/param&gt;
        /// &lt;param name=&quot;classname&quot;&gt;CLASS NAME INSIDE THE NAMESPACE FROM WHICH TO EXECUTE&lt;/param&gt;
        /// &lt;param name=&quot;functionname&quot;&gt;FUNCTION TO EXECUTE INSIDE OF THE CLASS&lt;/param&gt;
        /// &lt;param name=&quot;isstatic&quot;&gt;IS THE METHOD A STATIC METHOD OR AN INSTANCED METHOD&lt;/param&gt;
        /// &lt;param name=&quot;args&quot;&gt;ARRAY OF ARGUMENTS TO BE PASSED INTO THE FUNCTION WE ARE CALLING&lt;/param&gt;
        /// &lt;returns&gt;RETURNS ANY VALUE RETURNED BY THE FUNCTION THAT WAS CALLED&lt;/returns&gt;
        public static object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args)
        {
            Type tmpType = null;
            object tmpInstance = null;
            Assembly tmpAsm = BuildAssembly(code);

            //CHECK TO VERIFY THE BUILDASSEMBLY WORKED
            if (tmpAsm != null)
            {
                //IF THIS IS A STATIC METHOD WE CAN CALL IT DIRECTLY OTHERWISE WE NEED TO CREATE AN INSTANCE OF THE LIBRARY FIRST
                if (isstatic)
                {
                    tmpType = tmpAsm.GetType(namespacename + &quot;.&quot; + classname);
                }
                else
                {
                    tmpInstance = tmpAsm.CreateInstance(namespacename + &quot;.&quot; + classname);
                    tmpType = tmpInstance.GetType();
                }

                //FIND THE METHOD WE WISH TO EXECUTE
                MethodInfo method = tmpType.GetMethod(functionname);

                //RETURN WHATEVER VALUE COMES BACK FROM THE FUNCTION CALL
                return method.Invoke(tmpInstance, args);
            }
            else
            {
                return null;
            }
        }
    }
</pre>
<h3>//Usage</h3>
<hr/>
<pre class="brush: csharp;">
            string plainTextCode = &quot;using System.Windows.Forms;namespace Test{public class Test	{public void Main(){MessageBox.Show(\&quot;Testing!\&quot;, \&quot;Test Title\&quot;);	}}}&quot;;
            AssemblyBuilder.ExecuteCode(plainTextCode, &quot;Test&quot;, &quot;Test&quot;, &quot;Main&quot;, false, new object[]{});
</pre>



Share


	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Compiling%20Code%20at%20Runtime%20-%20http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fcompiling-code-at-runtime%2F" title="Twitter"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fcompiling-code-at-runtime%2F&amp;title=Compiling%20Code%20at%20Runtime&amp;bodytext=This%20little%20snippit%20has%20only%20ever%20been%20used%20once%20by%20me%20in%20an%20attempt%20to%20give%20the%20end%20user%20the%20ability%20to%20make%20adjustments%20to%20processing%20scripts.%20%20It%20turned%20out%20to%20be%20a%20little%20bit%20of%20a%20headache%20because%20hoping%20your%20end%20user%20has%20the%20skill%20and%20ability%20to" title="Digg"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fcompiling-code-at-runtime%2F&amp;title=Compiling%20Code%20at%20Runtime" title="StumbleUpon"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fmichael.chanceyjr.com%2Fuseful-code%2Fcompiling-code-at-runtime%2F&amp;title=Compiling%20Code%20at%20Runtime&amp;notes=This%20little%20snippit%20has%20only%20ever%20been%20used%20once%20by%20me%20in%20an%20attempt%20to%20give%20the%20end%20user%20the%20ability%20to%20make%20adjustments%20to%20processing%20scripts.%20%20It%20turned%20out%20to%20be%20a%20little%20bit%20of%20a%20headache%20because%20hoping%20your%20end%20user%20has%20the%20skill%20and%20ability%20to" title="del.icio.us"><img src="http://michael.chanceyjr.com/site/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://michael.chanceyjr.com/useful-code/compiling-code-at-runtime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
