<?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/tag/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>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>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>

