<?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>DataBatrix &#187; Code Snippets</title>
	<atom:link href="http://www.databatrix.com/category/code-snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.databatrix.com</link>
	<description>The workings of Eric Bridges</description>
	<lastBuildDate>Thu, 01 Dec 2011 23:47:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>.NET Serialization: Binary, SOAP, and XML (VB)</title>
		<link>http://www.databatrix.com/2009/10/net-serialization-binary-soap-and-xml-vb/</link>
		<comments>http://www.databatrix.com/2009/10/net-serialization-binary-soap-and-xml-vb/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 23:43:50 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[.NET 2.0]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[ASP]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Binary]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[SOAP]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.databatrix.com/?p=227</guid>
		<description><![CDATA[In .NET when you need to shrink an object into a more portable format you have 3 choices.  Binary, SOAP, or XML.  The process of shrinking and expanding the object is called serialization and deserialization.  Each option has it&#8217;s own advantages which I will explain. Binary You can serialize an object into binary format quite [...]]]></description>
			<content:encoded><![CDATA[<p>In .NET when you need to shrink an object into a more portable format you have 3 choices.  Binary, SOAP, or XML.  The process of shrinking and expanding the object is called serialization and deserialization.  Each option has it&#8217;s own advantages which I will explain.</p>
<h2>Binary</h2>
<p>You can serialize an object into binary format quite easily using the .NET Framework.  This is the quickest and smallest way to serialize; however, the binary format can only be deserialized using the same .NET Framework.  This may be a problem for interoperability.  It must be noted that this format will serialize Public and Private members (unlike XML serialization).</p>
<p>The example below shows how to serialize an object called &#8220;newCustomer&#8221;:</p>
<pre class="brush:vb">        Dim newCustomer As Contact = GetSampleContact()

        Using fs As New IO.FileStream(filePathandName &amp; ".bin", IO.FileMode.Create)
            Dim binFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
            binFormatter.Serialize(fs, newCustomer)
        End Using</pre>
<p>And here is the reverse to deserialize:</p>
<pre class="brush:vb">        Dim readCustomer As Contact

        Using fs As New IO.FileStream(filePathandName &amp; ".bin", IO.FileMode.Open, IO.FileAccess.Read)
            Dim binFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
            readCustomer = CType(binFormatter.Deserialize(fs), Contact)
        End Using</pre>
<h2>SOAP</h2>
<p>SOAP is another method.  This is similar to the binary method except the serialized data is stored in a standardized form (SOAP) which will easily allow interoperability.  Public and Private members are serialized using this method as well.<br />
To serialize:</p>
<pre class="brush:vb">        Dim newCustomer As Contact = GetSampleContact()
        Using fs As New IO.FileStream(filePathandName &amp; "SOAP.xml", IO.FileMode.Create)
            Dim soapFormattter As New Runtime.Serialization.Formatters.Soap.SoapFormatter()
            soapFormattter.Serialize(fs, newCustomer)
        End Using</pre>
<p>And to deserialize:</p>
<pre class="brush:vb">        Dim readCustomer As Contact
        Using fs As New IO.FileStream(filePathandName &amp; "SOAP.xml", IO.FileMode.Open, IO.FileAccess.Read)
            Dim soapFormattter As New Runtime.Serialization.Formatters.Soap.SoapFormatter()
            readCustomer = CType(soapFormattter.Deserialize(fs), Contact)
        End Using</pre>
<h2>XML</h2>
<p>A third choice is using the XMLSerializer class.  This method will only serialize Public properties and members and the object must be marked with the Serializable attribute and contain an empty constructor.  This method of serialization will be smaller in size than the SOAP method since less information is serialized.  Here is an example of such class:</p>
<pre class="brush:vb">     &lt;Serializable()&gt; Class Contact

        Private _FirstName As String
        Public Property FirstName() As String
            Get
                Return _FirstName
            End Get
            Set(ByVal value As String)
                _FirstName = value
            End Set
        End Property

        Private _LastName As String
        Public Property LastName() As String
            Get
                Return _LastName
            End Get
            Set(ByVal value As String)
                _LastName = value
            End Set
        End Property

        Private _MiddleI As String
        Public Property MiddleI() As String
            Get
                Return _MiddleI
            End Get
            Set(ByVal value As String)
                _MiddleI = value
            End Set
        End Property

        Private _PIN As String
        Public WriteOnly Property PIN() As String
            Set(ByVal value As String)
                _PIN = value
            End Set
        End Property

        Sub New()

        End Sub

        Sub New(ByVal fName As String, ByVal middleI As String, ByVal lName As String, ByVal p As String)
            _FirstName = fName
            _MiddleI = middleI
            _LastName = lName
            _PIN = p
        End Sub
    End Class</pre>
<p>Here is how you would serialize using the XMLSerializer:</p>
<pre class="brush:vb">        Dim newCustomer As Contact = GetSampleContact()
        Using fs As New IO.FileStream(filePathandName &amp; ".xml", IO.FileMode.Create)
            Dim xmlFormatter As New Xml.Serialization.XmlSerializer(GetType(Contact))
            xmlFormatter.Serialize(fs, newCustomer)
        End Using</pre>
<p>And to deserialize:</p>
<pre class="brush:vb">        Dim readCustomer As Contact
        Using fs As New IO.FileStream(filePathandName &amp; ".xml", IO.FileMode.Open, IO.FileAccess.Read)
            Dim xmlFormatter As New Xml.Serialization.XmlSerializer(GetType(Contact))
            readCustomer = CType(xmlFormatter.Deserialize(fs), Contact)
        End Using</pre>
<p><img class="alignnone size-full wp-image-232" title="Serialization Demo" src="http://www.databatrix.com/wp-content/uploads/2009/10/Serialization.JPG" alt="Serialization Demo" width="505" height="336" /></p>
<p>You can download a sample serialization demo project that I created to demonstrate: <a title="Serialization Demo Project.zip" href="http://www.databatrix.com/wp-content/uploads/2009/10/SerializationDemo.zip">SerializationDemoProject.zip</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databatrix.com/2009/10/net-serialization-binary-soap-and-xml-vb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cross-thread operation not valid: .NET Cross Threading To Update Form Control</title>
		<link>http://www.databatrix.com/2009/09/cross-thread-operation-not-valid-net-cross-threading-to-update-form-control/</link>
		<comments>http://www.databatrix.com/2009/09/cross-thread-operation-not-valid-net-cross-threading-to-update-form-control/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 13:18:45 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[.NET 2.0]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Cross-thread]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://www.databatrix.com/?p=204</guid>
		<description><![CDATA[So you get the &#8220;Cross-thread operation not valid&#8221; error because you are trying to update an object on your form from a thread. I am not going to try to &#8220;glamor&#8221; you (True Blood reference) with fundamentals of delegates, threading, etc. If that is what you are looking for, search Google and you will find [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_206" class="wp-caption alignleft" style="width: 466px"><a href="http://www.databatrix.com/wp-content/uploads/2009/09/CrossThread.JPG"><img class="size-full wp-image-206" title="Cross-thread operation not valid" src="http://www.databatrix.com/wp-content/uploads/2009/09/CrossThread.JPG" alt="Cross-thread operation not valid" width="456" height="256" /></a><p class="wp-caption-text">Cross-thread operation not valid</p></div>
<p>So you get the &#8220;Cross-thread operation not valid&#8221; error because you are trying to update an object on your form from a thread.  I am not going to try to &#8220;glamor&#8221; you (True Blood reference) with fundamentals of delegates, threading, etc.  If that is what you are looking for, search Google and you will find tons of references that are overly complicated using all of the proper terminology that typically makes my head hurt.  I WILL show you the few bits of code in Visual Basic that are needed to get around the error.  Or perhaps you just need to update a form control from a background process so the application does not hang.</p>
<p>In the example below, I am needing to update a ListBox control from a separate thread.  I need 2 items: a method to update the ListBox which takes a string as a parameter and a Delegate with a matching parameter signature.</p>
<p>Here is the Delegate:</p>
<pre class="brush: vb">Private Delegate Sub UpdateListboxDelegate(ByVal s As String)</pre>
<p>And here is the method that actually updates the ListBox:</p>
<pre class="brush: vb">Private Sub UpdateListbox(ByVal s As String)
   If Me.InvokeRequired Then
      Me.BeginInvoke(New UpdateListboxDelegate(AddressOf UpdateListbox), New Object() {s})
      Return
   End If
   ListBox1.Items.Add(s)
End Sub</pre>
<p>Here would be a sample of the main sub that is slow to process:</p>
<pre class="brush: vb">Public Sub LongProcess()
   For i As Integer = 0 To 100
      System.Threading.Thread.Sleep(5000)
      UpdateListbox("Currently on count: " &amp; i)
   Next
End Sub</pre>
<p>Now to kick off the thread:</p>
<pre class="brush: vb">ListBox1.Items.Clear()
Dim thread As New Threading.Thread(AddressOf LongProcess)
thread.Start()</pre>
<p>That&#8217;s it!  The easiest solution without getting overly complicated.</p>
<p><b>&#8230;and in case you are looking for C# (it&#8217;s growing on me too):</b></p>
<pre class="brush:csharp">
        private delegate void UpdateListboxDelegate(string s);

        private void UpdateListbox(string s)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new UpdateListboxDelegate(UpdateListbox), new object[] { s });
                return;
            }
            listBox1.Items.Add(s);
        }

        public void LongProcess()
        {
            for (int i = 0; i < 10; i++)
            {
                System.Threading.Thread.Sleep(1000);
                UpdateListbox("Currently on count: " + i.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Threading.Thread thread = new System.Threading.Thread(LongProcess);
            thread.Start();
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.databatrix.com/2009/09/cross-thread-operation-not-valid-net-cross-threading-to-update-form-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A .NET Bit.ly API Helper Class (Visual Basic.NET)</title>
		<link>http://www.databatrix.com/2009/08/a-net-bit-ly-api-helper-class-visual-basic-net/</link>
		<comments>http://www.databatrix.com/2009/08/a-net-bit-ly-api-helper-class-visual-basic-net/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 21:19:19 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[.NET 2.0]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Web Services]]></category>
		<category><![CDATA[bit.ly]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Twitter]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.databatrix.com/?p=162</guid>
		<description><![CDATA[I decided to write a helper class for using the Bit.ly API for creating short urls.  You know, those tiny links that you see all over Facebook, Twitter, etc.  The snippet below shows how you would use the helper class.  Not only can you shorten an url, you can shorted multiple urls in a single [...]]]></description>
			<content:encoded><![CDATA[<p>I decided to write a helper class for using the Bit.ly API for creating short urls.  You know, those tiny links that you see all over Facebook, Twitter, etc.  The snippet below shows how you would use the helper class.  Not only can you shorten an url, you can shorted multiple urls in a single call as well as get stats and info about a bit.ly url.  If you are looking to incorporate bit.ly short urls in your application using their API access, this will save you some time.  The class uses the XmlSerializer for reading bit.ly&#8217;s response.</p>
<pre class="brush: vb">        ' Pass username and API key to instantiate
        Dim newbitlyAPI As New DataBatrix.bitlyAPI.bitlyAPI("bitlyapidemo", "R_0da49e0a9118ff35f52f629d2d71bf07")

        ' Sample of creating 1 short URL
        Dim shortenResponse As DataBatrix.bitlyAPI.bitlyShortenResponse = newbitlyAPI.Shorten("http://www.databatrix.com")
        Dim shortURL As String = ""
        If shortenResponse.results.Count &gt; 0 Then
            shortURL = shortenResponse.results(0).shortUrl
        End If

        ' Sample of creating multiple short URLs
        Dim longUrls() As String = {"http://www.databatrix.com", "http://www.google.com"}
        Dim shortenResponses As DataBatrix.bitlyAPI.bitlyShortenResponse = newbitlyAPI.Shorten(longUrls)
        Dim shortURLs(1) As String
        For i As Integer = 0 To shortenResponses.results.Count - 1
            shortURLs(i) = shortenResponses.results(i).shortUrl

        Next

        ' Sample of getting bit.ly info...
        Dim info As DataBatrix.bitlyAPI.bitlyInfoResponse = newbitlyAPI.Info("2bYgqR")

        ' Sample of getting bit.ly stats...
        Dim stats As DataBatrix.bitlyAPI.bitlyStatsResponse = newbitlyAPI.Stats("http://bit.ly/1RmnUT")</pre>
<p>Below is the helper class that I created.  You can download the VB file <a href="http://www.databatrix.com/wp-content/uploads/2009/08/bitlyAPI.vb">bitlyAPI.vb</a> or a sample project <a href="http://www.databatrix.com/wp-content/uploads/2009/08/TestBitly.zip">TestBitly Project Files</a>.</p>
<pre class="brush: vb">Imports System.Web
Imports System.Xml
Imports System.Xml.Serialization

Namespace DataBatrix.bitlyAPI
    Public Class bitlyAPI
        Const BaseAPIUrl As String = "http://api.bit.ly/"
        Const version As String = "2.0.1"
        Const format As String = "xml"

        Public login As String = String.Empty
        Public apiKey As String = String.Empty

        Sub New(ByVal login As String, ByVal apiKey As String)
            Me.login = login
            Me.apiKey = apiKey

        End Sub

        Private Function BuildBaseRequestURL(ByVal applicationName As String) As System.Text.StringBuilder
            Dim RequestUrl As New System.Text.StringBuilder()
            With RequestUrl
                .Append(BaseAPIUrl &amp; HttpUtility.UrlEncode(applicationName) &amp; "?")
                .Append("version=" &amp; HttpUtility.UrlEncode(version) &amp; "&amp;")
                .Append("format=" &amp; HttpUtility.UrlEncode(format) &amp; "&amp;")
                .Append("login=" &amp; HttpUtility.UrlEncode(login) &amp; "&amp;")
                .Append("apiKey=" &amp; HttpUtility.UrlEncode(apiKey) &amp; "&amp;")
            End With
            Return RequestUrl
        End Function

        Public Function Shorten(ByVal longUrl As String) As bitlyShortenResponse
            Dim logUrls() As String = {longUrl}
            Return Shorten(logUrls)
        End Function

        Public Function Shorten(ByVal longUrl() As String) As bitlyShortenResponse
            Dim RequestUrl As System.Text.StringBuilder = BuildBaseRequestURL("shorten")
            For Each s As String In longUrl
                RequestUrl.Append("&amp;longUrl=" &amp; HttpUtility.UrlEncode(s))

            Next
            Dim responseObj As DataBatrix.bitlyAPI.bitlyShortenResponse = Nothing
            Try
                Dim serializer = New XmlSerializer(GetType(DataBatrix.bitlyAPI.bitlyShortenResponse))
                Using reader As XmlTextReader = New XmlTextReader(RequestUrl.ToString())
                    responseObj = CType(serializer.Deserialize(reader), DataBatrix.bitlyAPI.bitlyShortenResponse)
                End Using

            Catch ex As Exception

            End Try

            If responseObj.errorCode &gt; 0 Then
                Throw New ApplicationException("Error from bit.ly: " &amp; responseObj.errorMessage)
            End If
            Return responseObj
        End Function
        Public Function Info(ByVal hash As String) As bitlyInfoResponse
            Dim RequestUrl As System.Text.StringBuilder = BuildBaseRequestURL("info")
            With RequestUrl
                .Append("hash=" &amp; HttpUtility.UrlEncode(hash))
            End With

            Dim responseObj As DataBatrix.bitlyAPI.bitlyInfoResponse = Nothing
            Try
                Dim serializer = New XmlSerializer(GetType(DataBatrix.bitlyAPI.bitlyInfoResponse))
                Using reader As XmlTextReader = New XmlTextReader(RequestUrl.ToString())
                    responseObj = CType(serializer.Deserialize(reader), DataBatrix.bitlyAPI.bitlyInfoResponse)
                End Using

            Catch ex As Exception
                Throw New ApplicationException("API Error: " &amp; ex.Message)
            End Try
            If responseObj.errorCode &gt; 0 Then
                Throw New ApplicationException("Error from bit.ly: " &amp; responseObj.errorMessage)
            End If
            Return responseObj
        End Function

        Public Function Stats(ByVal shortUrl As String) As bitlyStatsResponse
            Dim RequestUrl As System.Text.StringBuilder = BuildBaseRequestURL("stats")
            With RequestUrl
                .Append("shortUrl=" &amp; HttpUtility.UrlEncode(shortUrl))

            End With

            Dim responseObj As DataBatrix.bitlyAPI.bitlyStatsResponse = Nothing
            Try
                Dim serializer = New XmlSerializer(GetType(DataBatrix.bitlyAPI.bitlyStatsResponse))
                Using reader As XmlTextReader = New XmlTextReader(RequestUrl.ToString())
                    responseObj = CType(serializer.Deserialize(reader), DataBatrix.bitlyAPI.bitlyStatsResponse)
                End Using

            Catch ex As Exception
                Throw New ApplicationException("API Error: " &amp; ex.Message)
            End Try
            If responseObj.errorCode &gt; 0 Then
                Throw New ApplicationException("Error from bit.ly: " &amp; responseObj.errorMessage)
            End If
            Return responseObj
        End Function

    End Class

    Public MustInherit Class bitlyResponseBase
        &lt;Xml.Serialization.XmlElement("errorCode")&gt; _
        Public errorCode As Integer = 0

        &lt;Xml.Serialization.XmlElement("errorMessage")&gt; _
        Public errorMessage As String = String.Empty

        &lt;Xml.Serialization.XmlElement("statusCode")&gt; _
        Public statusCode As String = String.Empty

    End Class

    &lt;System.Serializable(), Xml.Serialization.XmlRoot("bitly")&gt; _
    Public Class bitlyShortenResponse
        Inherits bitlyResponseBase

        &lt;Xml.Serialization.XmlArray("results"), Xml.Serialization.XmlArrayItem("nodeKeyVal")&gt; _
        Public results As New List(Of KeyVal)

        Public Class KeyVal
            &lt;Xml.Serialization.XmlElement("userHash")&gt; _
             Public userHash As String

            &lt;Xml.Serialization.XmlElement("shortKeywordUrl")&gt; _
             Public shortKeywordUrl As String

            &lt;Xml.Serialization.XmlElement("hash")&gt; _
             Public hash As String

            &lt;Xml.Serialization.XmlElement("nodeKey")&gt; _
             Public longUrl As String

            &lt;Xml.Serialization.XmlElement("shortUrl")&gt; _
             Public shortUrl As String

        End Class
    End Class

    &lt;System.Serializable(), Xml.Serialization.XmlRoot("bitly")&gt; _
    Public Class bitlyInfoResponse
        Inherits bitlyResponseBase

        &lt;Xml.Serialization.XmlArray("results"), Xml.Serialization.XmlArrayItem("doc")&gt; _
        Public results As New List(Of bitlyInfoResultItem)

        Public Class bitlyInfoResultItem
            &lt;Xml.Serialization.XmlElement("shortenedByUser")&gt; _
            Public shortenedByUser As String
            &lt;Xml.Serialization.XmlElement("keywords")&gt; _
            Public keywords As String
            &lt;Xml.Serialization.XmlElement("hash")&gt; _
            Public hash As String
            &lt;Xml.Serialization.XmlElement("exif")&gt; _
            Public exif As String
            &lt;Xml.Serialization.XmlElement("surbl")&gt; _
            Public surbl As String
            &lt;Xml.Serialization.XmlElement("contentLength")&gt; _
            Public contentLength As String
            &lt;Xml.Serialization.XmlElement("id3")&gt; _
            Public id3 As String
            &lt;Xml.Serialization.XmlElement("calais")&gt; _
            Public calais As String
            &lt;Xml.Serialization.XmlElement("longUrl")&gt; _
            Public longUrl As String
            &lt;Xml.Serialization.XmlElement("version")&gt; _
            Public version As String
            &lt;Xml.Serialization.XmlElement("htmlMetaDescription")&gt; _
            Public htmlMetaDescription As String
            &lt;Xml.Serialization.XmlElement("htmlMetaKeywords")&gt; _
            Public htmlMetaKeywords As String
            &lt;Xml.Serialization.XmlElement("calaisId")&gt; _
            Public calaisId As String
            &lt;Xml.Serialization.XmlElement("thumbnail")&gt; _
            Public thumbnail As thumbnailObj
            &lt;Xml.Serialization.XmlElement("contentType")&gt; _
            Public contentType As String
            &lt;Xml.Serialization.XmlArray("users"), Xml.Serialization.XmlArrayItem("item")&gt; _
            Public users As List(Of String)
            &lt;Xml.Serialization.XmlElement("globalHash")&gt; _
            Public globalHash As String
            &lt;Xml.Serialization.XmlElement("htmlTitle")&gt; _
            Public htmlTitle As String
            &lt;Xml.Serialization.XmlElement("metacarta")&gt; _
            Public metacarta As String
            &lt;Xml.Serialization.XmlElement("mirrorUrl")&gt; _
            Public mirrorUrl As String
            &lt;Xml.Serialization.XmlElement("keyword")&gt; _
            Public keyword As String
            &lt;Xml.Serialization.XmlElement("calaisResolutions")&gt; _
            Public calaisResolutions As String
            &lt;Xml.Serialization.XmlElement("userHash")&gt; _
            Public userHash As String

            Public Class thumbnailObj
                &lt;Xml.Serialization.XmlElement("large")&gt; _
                Public large As String
                &lt;Xml.Serialization.XmlElement("small")&gt; _
                Public small As String
                &lt;Xml.Serialization.XmlElement("medium")&gt; _
                Public medium As String
            End Class

        End Class
    End Class

    &lt;System.Serializable(), Xml.Serialization.XmlRoot("bitly")&gt; _
Public Class bitlyStatsResponse
        Inherits bitlyResponseBase

        &lt;Xml.Serialization.XmlElement("hash")&gt; _
        Public hash As String
        &lt;Xml.Serialization.XmlElement("clicks")&gt; _
        Public clicks As String

        Public Class bitlyStatsResultItem
            &lt;Xml.Serialization.XmlElement("None")&gt; _
            Public None As String
            &lt;Xml.Serialization.XmlElement("direct")&gt; _
            Public direct As String
            &lt;Xml.Serialization.XmlArray("nodeKeyVal"), XmlArrayItem("nodeKeyVal")&gt; _
            Public nodeKeyValue As List(Of KeyValue)
            &lt;Xml.Serialization.XmlElement("nodeKey")&gt; _
            Public nodeKey As String

            Public Class KeyValue
                &lt;Xml.Serialization.XmlElement("nodeValue")&gt; _
            Public nodeValue As String
                &lt;Xml.Serialization.XmlElement("nodeKey")&gt; _
                Public nodeKey As String
            End Class
        End Class
    End Class

End Namespace</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.databatrix.com/2009/08/a-net-bit-ly-api-helper-class-visual-basic-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom Replace with Regular Expressions in .NET</title>
		<link>http://www.databatrix.com/2009/08/custom-replace-with-regular-expressions-in-net/</link>
		<comments>http://www.databatrix.com/2009/08/custom-replace-with-regular-expressions-in-net/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 19:05:34 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[.NET 2.0]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[Delegates]]></category>

		<guid isPermaLink="false">http://www.databatrix.com/?p=149</guid>
		<description><![CDATA[This is the second time I have had to do something like this.  So this time I am posting it for my reference.  Regular expressions are amazing and amazingly difficult to understand sometimes, but they come in very handy.  I was in a situation where I was going to need to  feed in a custom [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second time I have had to do something like this.  So this time I am posting it for my reference.  Regular expressions are amazing and amazingly difficult to understand sometimes, but they come in very handy.  I was in a situation where I was going to need to  feed in a custom template to be used similar to a &#8220;mail merge&#8221; situation.  I would query a database, then for each record I would fill out an email using an email template.  I decided to go with &lt;:FieldName:&gt; as the nomenclature of how a field would be inserted.  For example, here are the query results:</p>
<table border="0">
<tbody>
<tr>
<td>FirstName</td>
<td>LastName</td>
<td>Company</td>
</tr>
<tr>
<td>Eric</td>
<td>Bridges</td>
<td>DataBatrix</td>
</tr>
</tbody>
</table>
<p>My email template may look something like this:</p>
<pre>Dear &lt;:FirstName:&gt; &lt;:LastName:&gt;,</pre>
<pre>You work for &lt;:Company:&gt;!</pre>
<p>For the purpose of my project, I did not know what fields were going to be returned or what the email template looked like.  I needed a simple way to replace all of the field placeholders with actual data.  Regular expressions to the rescue!  You can use a delegate to run your own replace function.  I called my method MatchHandler which is passed a Match variable (the match that is found).  In my example below, I replaced it with the corresponding item from _reader (my sqldatareader row).</p>
<pre class="brush: vb">    Private Function MatchHandler(ByVal m As Match) As String
        Dim fieldName As String = m.Groups("fieldName").ToString()
        If HasField(fieldName) Then
            Return _reader(fieldName)
        Else
            Return m.ToString()
        End If
    End Function</pre>
<p>Next we have to create our delegate.  Delegates are basically pointers for methods (functions/subs).  I called my delegate &#8220;MatchDelegate&#8221; and pass it the address of my function I created above.</p>
<pre class="brush: vb">    Dim MatchDelegate As New MatchEvaluator(AddressOf MatchHandler)</pre>
<p>Now to make it work!  Define your regular expression pattern and instantiate a new RegularExpression object.  Use the Replace method and pass the string to search and the delegate that we created.</p>
<pre class="brush: vb">    Private Function MergeFields(ByVal body As String) As String
        Dim returnValue As String = ""
        Dim pattern As String = "&lt;:(?&lt;fieldName:&gt;(.+?)):&gt;"
        Dim regex As New Text.RegularExpressions.Regex(pattern)
        returnValue = regex.Replace(body, MatchDelegate)
        Return returnValue
    End Function</pre>
<p>That&#8217;s it!  Now you can do whatever you like when a match is found in your Replace method.</p>
<p>In case you were wondering what &#8220;(?&lt;fieldName:&gt;(.+?))&#8221; in the pattern was all about, check out <a href="http://www.regular-expressions.info/named.html" target="_blank">this link talking about regular expression groups</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databatrix.com/2009/08/custom-replace-with-regular-expressions-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

