<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Procbits</title>
	<atom:link href="http://procbits.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://procbits.com</link>
	<description>source code snippets and other random musings about software</description>
	<lastBuildDate>Fri, 03 Sep 2010 04:14:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='procbits.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/6dad4ae480a90a3903741f18af1ec27f?s=96&#038;d=http://s2.wp.com/i/buttonw-com.png</url>
		<title>Procbits</title>
		<link>http://procbits.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://procbits.com/osd.xml" title="Procbits" />
	<atom:link rel='hub' href='http://procbits.com/?pushpress=hub'/>
		<item>
		<title>C# yield</title>
		<link>http://procbits.com/2010/09/02/c-yield/</link>
		<comments>http://procbits.com/2010/09/02/c-yield/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 04:14:38 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=62</guid>
		<description><![CDATA[I&#8217;ve seen the &#8220;yield&#8221; keyword here and there&#8230; but I&#8217;ve never really cared to learn what it does. Until now. Actually, it&#8217;s my understanding that it&#8217;s more or less a convenience keyword like &#8220;var.&#8221; In short, &#8220;yield&#8221; allows you to return an IEnumerable without creating a List. Example: (old way) IEnumerable&#60;Car&#62; FindBlueCars(){ var blueCars = [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=62&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve seen the &#8220;yield&#8221; keyword here and there&#8230; but I&#8217;ve never really cared to learn what it does. Until now. Actually, it&#8217;s my understanding that it&#8217;s more or less a convenience keyword like &#8220;var.&#8221;</p>
<p>In short, &#8220;yield&#8221; allows you to return an IEnumerable without creating a List.</p>
<p>Example: (old way)</p>
<pre class="brush: csharp;">
IEnumerable&lt;Car&gt; FindBlueCars(){
	var blueCars = new List&lt;Car&gt;();
	foreach (var c in _allCars)
		if (c.IsBlue())
			blueCars.Add(c);
	return blueCars;
}
</pre>
<p>Example: (new way)</p>
<pre class="brush: csharp;">
IEnumerable&lt;Car&gt; FindBlueCars(){
	foreach (var c in _allCars)
		if (c.IsBlue())
			yield return c;
}
</pre>
<p>Saves some typing.  <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=VS.100).aspx">MSDN reference for yield.</a></p>
<p>Read me blog on entrepreneurship: <a href="http://techneur.com">Techneur</a><br />
Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a></p>
<p>-JP </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/62/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=62&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/09/02/c-yield/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Benchmarking C# Apps &amp; Algorithms</title>
		<link>http://procbits.com/2010/08/25/benchmarking-c-apps-algorithms/</link>
		<comments>http://procbits.com/2010/08/25/benchmarking-c-apps-algorithms/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 16:38:39 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=59</guid>
		<description><![CDATA[I created a class to help me benchmark my C# algorithms. Here&#8217;s how you can use it: BenchmarkTimer.Start(&#34;Long running algorithm&#34;); for (int x = 0; x &#60; 3; ++x) { BenchmarkTimer.Start(&#34;Small running algorithm&#34;); Thread.Sleep(1000); BenchmarkTimer.StopAndOutput(); } BenchmarkTimer.StopAndOutput(); Output: Small running algorithm: 1000.3712 ms Small running algorithm: 1000.3712 ms Small running algorithm: 1000.3712 ms Long running [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=59&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I created a class to help me benchmark my C# algorithms.</p>
<p>Here&#8217;s how you can use it:</p>
<pre class="brush: csharp;">
BenchmarkTimer.Start(&quot;Long running algorithm&quot;);
for (int x = 0; x &lt; 3; ++x) {
	BenchmarkTimer.Start(&quot;Small running algorithm&quot;);
	Thread.Sleep(1000);
	BenchmarkTimer.StopAndOutput();
}
BenchmarkTimer.StopAndOutput();
</pre>
<p>Output:<br />
Small running algorithm: 1000.3712 ms<br />
Small running algorithm: 1000.3712 ms<br />
Small running algorithm: 1000.3712 ms<br />
Long running algorithm: 3001.1136 ms</p>
<p>You can find my entire C# CommonLib library here: <a href="http://github.com/jprichardson/CommonLib">http://github.com/jprichardson/CommonLib</a></p>
<p>Here is the relevant class:</p>
<pre class="brush: csharp;">
public static class BenchmarkTimer
	{
		private static Stack&lt;BenchmarkData&gt; _startStack = new Stack&lt;BenchmarkData&gt;();

		public static void Start() {
			_startStack.Push(new BenchmarkData());
		}

		public static void Start(string label) {
			var bd = new BenchmarkData() { Label = label };
			_startStack.Push(bd);
		}

		public static TimeSpan Stop() {
			var stop = DateTime.Now;
			var startBD = _startStack.Pop();
			return stop - startBD.DateTime;
		}

		public static void StopAndOutput() {
			var stop = DateTime.Now;
			var startBD = _startStack.Pop();

			var delta = stop - startBD.DateTime;

			var lbl = &quot;{0}: {1} ms&quot;;
			Console.WriteLine(String.Format(lbl, startBD.Label, delta.TotalMilliseconds));
		}

		private class BenchmarkData
		{
			public DateTime DateTime { get; set; }
			public string Label { get; set; }

			public BenchmarkData(){
				this.DateTime = DateTime.Now;
				this.Label = &quot;&quot;;
			}
		}
	}
</pre>
<p>Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a><br />
Read my blog entrepreneurship: <a href="http://techneur.com">Techneur</a></p>
<p>-JP</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=59&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/08/25/benchmarking-c-apps-algorithms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>StoryBoard: Animations in WPF</title>
		<link>http://procbits.com/2010/08/10/storyboard-animations-in-wpf/</link>
		<comments>http://procbits.com/2010/08/10/storyboard-animations-in-wpf/#comments</comments>
		<pubDate>Tue, 10 Aug 2010 22:18:11 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=57</guid>
		<description><![CDATA[I recently discovered how to do animations in WPF. It&#8217;s super simple! So what if you want to create a mouse over animation on a StackPanel? You use the StoryBoard XAML element. Snippet: &#60;Storyboard x:Key=&#34;mouseFadeIn&#34;&#62; &#60;DoubleAnimation Duration=&#34;0:0:5&#34; Storyboard.TargetName=&#34;myStackPanel&#34; Storyboard.TargetProperty=&#34;(UIElement.Opacity)&#34; From=&#34;0.25&#34; To=&#34;1.0&#34;/&#62; &#60;/StoryBoard&#62; This will cause a the Opacity of the element to change from 0.25 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=57&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently discovered how to do animations in WPF. It&#8217;s super simple! So what if you want to create a mouse over animation on a StackPanel? You use the StoryBoard XAML element.<br />
Snippet:</p>
<pre class="brush: xml;">
 &lt;Storyboard x:Key=&quot;mouseFadeIn&quot;&gt;
    &lt;DoubleAnimation
	Duration=&quot;0:0:5&quot;
	Storyboard.TargetName=&quot;myStackPanel&quot;
	Storyboard.TargetProperty=&quot;(UIElement.Opacity)&quot;
	From=&quot;0.25&quot;
	To=&quot;1.0&quot;/&gt;
&lt;/StoryBoard&gt;
</pre>
<p>This will cause a the Opacity of the element to change from 0.25 to 1.0 over a period of 5 seconds. Note: this should be put in the &#8220;Resources&#8221; tag. So, if it&#8217;s a Window it would be &#8220;Window.Resources&#8221; or if it&#8217;s a UserControl it would be &#8220;UserControl.Resources&#8221;&#8230;<br />
Snippet:</p>
<pre class="brush: xml;">
&lt;UserControl.Resources&gt;
  &lt;StoryBoard key=&quot;blah&quot;&gt;...
</pre>
<p>So how do we get this to trigger on a mouse over? By using Triggers of course!<br />
Snippet:</p>
<pre class="brush: xml;">
&lt;UserControl.Triggers&gt;
	&lt;EventTrigger RoutedEvent=&quot;Mouse.MouseEnter&quot; SourceName=&quot;myStackPanel&quot;&gt;
		&lt;BeginStoryboard Storyboard=&quot;{StaticResource mouseFadeIn}&quot; /&gt;
	&lt;/EventTrigger&gt;
&lt;/UserControl.Triggers&gt;
</pre>
<p>If you want to create a Fade Out effect, just use the &#8220;Mouse.MouseLeave&#8221; event and reverse the animation. You can even have multiple animations in a StoryBoard. They can run simultaneously or sequentially. If you have multiple animations in a StoryBoard and you want them to run sequentially, you need to add a &#8220;BeginTime&#8221; attribute. This ensures that the animation is executed after the previous animation(s).</p>
<p>Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a></p>
<p>-JP</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/57/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=57&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/08/10/storyboard-animations-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Traversal of GWT Tree</title>
		<link>http://procbits.com/2010/08/09/traversal-of-gwt-tree/</link>
		<comments>http://procbits.com/2010/08/09/traversal-of-gwt-tree/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 15:14:19 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=54</guid>
		<description><![CDATA[Recently, an app I&#8217;m working on needed two trees. I just so happened that I needed to deep copy part of one of the trees to the other tree. The copied tree will then have checkboxes as nodes instead of just Strings. So how would you do this? The first solution that came to mine [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=54&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, an app I&#8217;m working on needed two trees. I just so happened that I needed to deep copy part of one of the trees to the other tree. The copied tree will then have checkboxes as nodes instead of just Strings.</p>
<p>So how would you do this? The first solution that came to mine is depth-first traversal of the tree. This method could be adapted to any tree structure in just about any language.</p>
<p>We need a callback function for everytime we &#8216;hit&#8217; a tree node. Let&#8217;s create an interface called &#8216;Action&#8217;:<br />
Action.java:</p>
<pre class="brush: java;">
public interface Action&lt;T&gt; {
	public void execute(T object);
}
</pre>
<p>Now, we need to create a file called TreeItemUtil.java. This will include the algorithm. The algorithm is really straightforward, it just uses a stack for each node and iterates the stack. If a node has children, they are pushed onto the stack.<br />
TreeItemUtil.java:</p>
<pre class="brush: java;">
public class TreeItemUtil {

	public static Collection&lt;TreeItem&gt; fetchChildren(TreeItem ti){
		List&lt;TreeItem&gt; children = new ArrayList&lt;TreeItem&gt;();

		for (int i = 0; i &lt; ti.getChildCount(); ++i)
			children.add(ti.getChild(i));
		return children;
	}

	public static void traverseDfs(TreeItem root, Action&lt;TreeItem&gt; onNode){
		if (onNode == null)
			throw new IllegalArgumentException(&quot;Must pass an action.&quot;);

		Stack&lt;TreeItem&gt; children = new Stack&lt;TreeItem&gt;();
		children.add(root);

		while (!children.isEmpty()){
			TreeItem current = children.pop();
			onNode.execute(current);
			List&lt;TreeItem&gt; currentChildren = fetchChildren(current);
			children.addAll(currentChildren);
		}
	}
}
</pre>
<p>Here is our TreeItemUtilTest.java that uses Mockito:</p>
<pre class="brush: java;">
public void testTraverseDfs(){
		final StringBuffer sb = new StringBuffer();

		TreeItem a = createMockedTI(&quot;a&quot;);
		TreeItem b = createMockedTI(&quot;b&quot;);
		TreeItem c = createMockedTI(&quot;c&quot;);
		TreeItem d = createMockedTI(&quot;d&quot;);
		TreeItem e = createMockedTI(&quot;e&quot;);
		TreeItem f = createMockedTI(&quot;f&quot;);
		TreeItem g = createMockedTI(&quot;g&quot;);
		TreeItem h = createMockedTI(&quot;h&quot;);
		TreeItem i = createMockedTI(&quot;i&quot;);
		TreeItem j = createMockedTI(&quot;j&quot;);
		TreeItem k = createMockedTI(&quot;k&quot;);
		TreeItem l = createMockedTI(&quot;l&quot;);
		TreeItem m = createMockedTI(&quot;m&quot;);
		TreeItem n = createMockedTI(&quot;n&quot;);
		TreeItem o = createMockedTI(&quot;o&quot;);
		TreeItem p = createMockedTI(&quot;p&quot;);

		addMockedChildren(a, b, o);
		addMockedChildren(b, c, i);
		addMockedChildren(o, n, p);
		addMockedChildren(c, d);
		addMockedChildren(i, j, m);
		addMockedChildren(d, e);
		addMockedChildren(j, k, l);
		addMockedChildren(e, f, g);
		addMockedChildren(g, h);

		TreeItemUtil.traverseDfs(a, new Action&lt;TreeItem&gt;(){
			public void execute(TreeItem current){
				sb.append(current.getText());
			}
		});

		//I was assuming it would be leftmost child first, if so, it would be in alphabetical order
		//but it starts with rightmost node first.
		assertEquals(&quot;aopnbimjlkcdeghf&quot;, sb.toString());
	}

	private TreeItem createMockedTI(String text){
		TreeItem ti = mock(TreeItem.class);
		when(ti.getText()).thenReturn(text);
		return ti;
	}

	private void addMockedChildren(TreeItem parent, TreeItem... children){
		for (int x = 0; x &lt; children.length; ++x){
			when(parent.getChild(x)).thenReturn(children[x]);
			when(children[x].getParentItem()).thenReturn(parent);
		}

		when(parent.getChildCount()).thenReturn(children.length);
	}
</pre>
<p>Now for the actual algorithm that clones the TreeItem into a TreeItem with checkboxes:</p>
<pre class="brush: java;">
private TreeItem cloneTreeItemsWithCheckboxes(TreeItem root){
		final HashMap&lt;TreeItem, TreeItem&gt; oldNew = new HashMap&lt;TreeItem, TreeItem&gt;();

		TreeItemUtil.traverseDfs(root, new Action&lt;TreeItem&gt;(){
			public void execute(TreeItem current){
				TreeItem newTi = new TreeItem(new CheckBox(current.getText()));
				newTi.setUserObject(current.getUserObject());
				oldNew.put(current, newTi);

				if (current.getParentItem() != null &amp;&amp; oldNew.containsKey(current.getParentItem())){
					TreeItem newParent = oldNew.get(current.getParentItem());
					newParent.addItem(newTi);
				}
			}
		});

		return oldNew.get(root);
	}
</pre>
<p>Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a></p>
<p>-JP</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/54/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=54&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/08/09/traversal-of-gwt-tree/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Levenshtein in Ruby 1.9</title>
		<link>http://procbits.com/2010/08/07/levenshtein-in-ruby-1-9/</link>
		<comments>http://procbits.com/2010/08/07/levenshtein-in-ruby-1-9/#comments</comments>
		<pubDate>Sat, 07 Aug 2010 06:59:53 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=49</guid>
		<description><![CDATA[In Ruby 1.8, I would use the gem &#8216;levenshtein&#8217;&#8230; well that doesn&#8217;t work in 1.9. So you need to install the gem &#8216;text&#8217;. Then the call is as simple as: Text::Levenshtein.distance('hello', 'hell') Follow me on Twitter: @jprichardson -JP<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=49&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In Ruby 1.8, I would use the gem &#8216;levenshtein&#8217;&#8230; well that doesn&#8217;t work in 1.9. So you need to install the gem &#8216;text&#8217;.</p>
<p>Then the call is as simple as:</p>
<pre class="brush: ruby;">
Text::Levenshtein.distance('hello', 'hell')
</pre>
<p>Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a></p>
<p>-JP</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/49/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/49/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/49/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/49/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/49/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/49/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/49/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=49&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/08/07/levenshtein-in-ruby-1-9/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Adding a Close Event When the User Closes the Browser in GWT</title>
		<link>http://procbits.com/2010/08/06/adding-a-close-event-when-the-user-closes-the-browser-in-gwt/</link>
		<comments>http://procbits.com/2010/08/06/adding-a-close-event-when-the-user-closes-the-browser-in-gwt/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 23:23:28 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=45</guid>
		<description><![CDATA[Often times your GWT app will queue up client side RPC events. What if the user clicks close on the browser window or tries to navigate to a new page? The solution is very simple. Window.addWindowClosingHandler(new ClosingHandler(){ @Override public void onWindowClosing(ClosingEvent event) { event.setMessage(&#34;If you leave, you may lose data. Continue?&#34;); } }); Simple as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=45&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Often times your GWT app will queue up client side RPC events. What if the user clicks close on the browser window or tries to navigate to a new page? The solution is very simple.</p>
<pre class="brush: java;">
Window.addWindowClosingHandler(new ClosingHandler(){
	@Override public void onWindowClosing(ClosingEvent event) {
		event.setMessage(&quot;If you leave, you may lose data. Continue?&quot;);
	}
});
</pre>
<p>Simple as pie. If event.setMessage is called, a prompt will be displayed for you.</p>
<p>Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a></p>
<p>-JP</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=45&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/08/06/adding-a-close-event-when-the-user-closes-the-browser-in-gwt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Hosted WordPress Syntax Highlighting</title>
		<link>http://procbits.com/2010/08/06/hosted-wordpress-syntax-highlighting/</link>
		<comments>http://procbits.com/2010/08/06/hosted-wordpress-syntax-highlighting/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 23:10:13 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[Misc]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=43</guid>
		<description><![CDATA[Dear 2 RSS subscribers: I&#8217;m pleased that you find my snippet blog cool enough to subscribe. I know that you&#8217;re use to me posting about once every six months and if you wanted to read my daily writings you would subscribe over at Techneur. But now that I&#8217;ve discovered that Hosted WordPress (blogs hosted by [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=43&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Dear 2 RSS subscribers:</p>
<p>I&#8217;m pleased that you find my snippet blog cool enough to subscribe. I know that you&#8217;re use to me posting about once every six months and if you wanted to read my daily writings you would subscribe over at <a href="http://techneur.com">Techneur</a>. But now that I&#8217;ve discovered that Hosted WordPress (blogs hosted by wordpress.com) <a href="http://en.support.wordpress.com/code/posting-source-code/">supports syntax highlighting</a>, you&#8217;ll probably see a lot more posts. Prepare for the incoming barrage of posts.</p>
<p>Yours truly,</p>
<p>JP</p>
<p>No, but seriously&#8230; I didn&#8217;t know about this! I&#8217;m stoked, I got tired of looking at the crappy background of my code!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/43/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=43&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/08/06/hosted-wordpress-syntax-highlighting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Handy C# XML Serialization Methods</title>
		<link>http://procbits.com/2010/01/15/handy-c-xml-serialization-methods/</link>
		<comments>http://procbits.com/2010/01/15/handy-c-xml-serialization-methods/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 21:59:56 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=35</guid>
		<description><![CDATA[I have been hacking away on WPF/MVVM, GWT/MVP, and Rails for the last six months and haven&#8217;t found much time to update. But I wrote some handy C# XML serialization methods. They are very straightforward. Deserialize: public static T ReadFromFile(string file) { XmlSerializer xs = new XmlSerializer(typeof(T)); StreamReader sr = new StreamReader(file); T ret = [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=35&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been hacking away on WPF/MVVM, GWT/MVP, and Rails for the last six months and haven&#8217;t found much time to update. But I wrote some handy C# XML serialization methods. They are very straightforward.</p>
<p>Deserialize:</p>
<pre class="brush: csharp;">
public static T ReadFromFile(string file) {
	XmlSerializer xs = new XmlSerializer(typeof(T));
	StreamReader sr = new StreamReader(file);
	T ret = (T)xs.Deserialize(sr);
	sr.Close();
	return ret;
}
</pre>
<p>Serialize:</p>
<pre class="brush: csharp;">
public static void WriteToFile(T obj, string file) {
	XmlSerializer xs = new XmlSerializer(typeof(T));
	StreamWriter sw = new StreamWriter(file);
	xs.Serialize(sw, obj);
	sw.Close();
}
</pre>
<p>Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=35&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2010/01/15/handy-c-xml-serialization-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>SQLite Bulk Insert In C#/.NET</title>
		<link>http://procbits.com/2009/09/08/sqlite-bulk-insert/</link>
		<comments>http://procbits.com/2009/09/08/sqlite-bulk-insert/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 19:39:44 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=30</guid>
		<description><![CDATA[Recently, I had a project where I needed to load 1 million+ records into a SQLite database. I downloaded the SQLite ADO.NET adapter and setup the Entity framework to map to my SQLite database. All was simple and all was well! I started inserting the data into my database; lo and behold, it was taking [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=30&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, I had a project where I needed to load 1 million+ records into a SQLite database. I downloaded the <a href="http://sqlite.phxsoftware.com/">SQLite ADO.NET adapter</a> and setup the Entity framework to map to my SQLite database. All was simple and all was well!</p>
<p>I started inserting the data into my database; lo and behold, it was taking forever! In fact, it took most of a full working day to insert my data. I knew something wasn&#8217;t right. A simple Google search pointed me to the <a href="http://www.sqlite.org/faq.html#q19">SQLite FAQ</a>. It turns out that SQLite wraps every INSERT into a transaction. Simple solution: start a transaction and perform multiple INSERTs. I needed my inserts to be fast, so I just had to write a class to encapsulate this.</p>
<p>It&#8217;s very simple to use. Make sure that your SQLite database file has been created and your table has been created as well.</p>
<p>Let&#8217;s assume your database schema looks like the following:<br />
Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,<br />
LastName VARCHAR(16) NOT NULL,<br />
Height REAL NOT NULL</p>
<p>You would then use SQLiteBulkInsert as follows:</p>
<pre class="brush: csharp;">
SQLiteBulkInsert sbi = new SQLiteBulkInsert(yourDatabaseConnectionObject, &quot;yourTableName&quot;);
sbi.AddParameter(&quot;LastName&quot;, DbType.String);
sbi.AddParameter(&quot;Height&quot;, DbType.Single);
</pre>
<p>You can then insert records:</p>
<pre class="brush: csharp;">
for (int x = 0; x &amp;lt; 10000; x++)
	sbi.Insert(new object[]{someString, someFloat});
sbi.Flush();
</pre>
<p>That&#8217;s it! You should look at the file SQLiteBulkInsertTest.cs for more details.</p>
<p>SQLiteBulkInsert.cs:</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;

namespace YourProject.Data.SQLite
{
	public class SQLiteBulkInsert
	{
		private SQLiteConnection m_dbCon;
		private SQLiteCommand m_cmd;
		private SQLiteTransaction m_trans;

		private Dictionary m_parameters = new Dictionary();

		private uint m_counter = 0;

		private string m_beginInsertText;

		public SQLiteBulkInsert(SQLiteConnection dbConnection, string tableName) {
			m_dbCon = dbConnection;
			m_tableName = tableName;

			StringBuilder query = new StringBuilder(255);
			query.Append(&quot;INSERT INTO [&quot;); query.Append(tableName); query.Append(&quot;] (&quot;);
			m_beginInsertText = query.ToString();
		}

		private bool m_allowBulkInsert = true;
		public bool AllowBulkInsert { get { return m_allowBulkInsert; } set { m_allowBulkInsert = value; } }

		public string CommandText {
			get {
				if (m_parameters.Count &amp;lt; 1)
					throw new SQLiteException(&quot;You must add at least one parameter.&quot;);

				StringBuilder sb = new StringBuilder(255);
				sb.Append(m_beginInsertText);

				foreach (string param in m_parameters.Keys) {
					sb.Append('[');
					sb.Append(param);
					sb.Append(']');
					sb.Append(&quot;, &quot;);
				}
				sb.Remove(sb.Length - 2, 2);

				sb.Append(&quot;) VALUES (&quot;);

				foreach (string param in m_parameters.Keys) {
					sb.Append(m_paramDelim);
					sb.Append(param);
					sb.Append(&quot;, &quot;);
				}
				sb.Remove(sb.Length - 2, 2);

				sb.Append(&quot;)&quot;);

				return sb.ToString();
			}
		}

		private uint m_commitMax = 10000;
		public uint CommitMax { get { return m_commitMax; } set { m_commitMax = value; } }

		private string m_tableName;
		public string TableName { get { return m_tableName; } }

		private string m_paramDelim = &quot;:&quot;;
		public string ParamDelimiter { get { return m_paramDelim; } }

		public void AddParameter(string name, DbType dbType) {
			SQLiteParameter param = new SQLiteParameter(m_paramDelim + name, dbType);
			m_parameters.Add(name, param);
		}

		public void Flush() {
			try {
				if (m_trans != null)
					m_trans.Commit();
			}
			catch (Exception ex) { throw new Exception(&quot;Could not commit transaction. See InnerException for more details&quot;, ex); }
			finally {
				if (m_trans != null)
					m_trans.Dispose();

				m_trans = null;
				m_counter = 0;
			}
		}

		public void Insert(object[] paramValues) {
			if (paramValues.Length != m_parameters.Count)
				throw new Exception(&quot;The values array count must be equal to the count of the number of parameters.&quot;);

			m_counter++;

			if (m_counter == 1) {
				if (m_allowBulkInsert)
					m_trans = m_dbCon.BeginTransaction();

				m_cmd = m_dbCon.CreateCommand();
				foreach (SQLiteParameter par in m_parameters.Values)
					m_cmd.Parameters.Add(par);

				m_cmd.CommandText = this.CommandText;
			}

			int i = 0;
			foreach (SQLiteParameter par in m_parameters.Values) {
				par.Value = paramValues[i];
				i++;
			}

			m_cmd.ExecuteNonQuery();

			if (m_counter == m_commitMax) {
				try {
					if (m_trans != null)
						m_trans.Commit();
				}
				catch (Exception ex) { }
				finally {
					if (m_trans != null) {
						m_trans.Dispose();
						m_trans = null;
					}

					m_counter = 0;
				}
			}
		}
	}
}
</pre>
<p>SQLiteBulkInsertTest.cs:</p>
<pre class="brush: csharp;">
using YourProject.Data.SQLite;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.SQLite;
using System.Data;
using System.IO;
using System;

namespace TestYourProject
{
    ///
    ///This is a test class for SQLiteBulkInsertTest and is intended
    ///to contain all SQLiteBulkInsertTest Unit Tests
    ///
	[TestClass()]
	public class SQLiteBulkInsertTest
	{
		private static string m_testDir;
		private static string m_testFile;
		private static string m_testTableName = &quot;test_table&quot;;
		private static string m_connectionString;

		private static string m_deleteAllQuery = &quot;DELETE FROM [{0}]&quot;;
		private static string m_countAllQuery = &quot;SELECT COUNT(id) FROM [{0}]&quot;;
		private static string m_selectAllQuery = &quot;SELECT * FROM [{0}]&quot;;

		private static SQLiteConnection m_dbCon;
		private static SQLiteCommand m_deleteAllCmd;
		private static SQLiteCommand m_countAllCmd;
		private static SQLiteCommand m_selectAllCmd;

		private TestContext testContextInstance;

		///
		///Gets or sets the test context which provides
		///information about and functionality for the current test run.
		///
		public TestContext TestContext {
			get {
				return testContextInstance;
			}
			set {
				testContextInstance = value;
			}
		}

		#region Additional test attributes
		//
		//You can use the following additional attributes as you write your tests:
		//
		//Use ClassInitialize to run code before running the first test in the class
		[ClassInitialize()]
		public static void MyClassInitialize(TestContext testContext){
			Random rand = new Random(Environment.TickCount);
			int rn = rand.Next(0, int.MaxValue);
			m_testDir = @&quot;C:\SqliteBulkInsertTest-&quot; + rn + @&quot;\&quot;;
			m_testFile = m_testDir + &quot;db.sqlite&quot;;

			if (!Directory.Exists(m_testDir))
				Directory.CreateDirectory(m_testDir);

			if (!File.Exists(m_testFile)) {
				FileStream fs = File.Create(m_testFile);
				fs.Close();
			}

			m_connectionString = string.Format(@&quot;data source={0};datetimeformat=Ticks&quot;, m_testFile);
			m_dbCon = new SQLiteConnection(m_connectionString);
			m_dbCon.Open();

			SQLiteCommand cmd = m_dbCon.CreateCommand();
			string query = &quot;CREATE TABLE IF NOT EXISTS [{0}] (id INTEGER PRIMARY KEY AUTOINCREMENT, somestring VARCHAR(16), somereal REAL, someint INTEGER(4), somedt DATETIME)&quot;;
			query = string.Format(query, m_testTableName);
			cmd.CommandText = query;
			cmd.ExecuteNonQuery();
		}
		//
		//Use ClassCleanup to run code after all tests in a class have run
		[ClassCleanup()]
		public static void MyClassCleanup(){
			m_dbCon.Close();

			File.Delete(m_testFile);
			Directory.Delete(m_testDir);
		}
		#endregion

		private void AddParameters(SQLiteBulkInsert target) {
			target.AddParameter(&quot;somestring&quot;, DbType.String);
			target.AddParameter(&quot;somereal&quot;, DbType.String);
			target.AddParameter(&quot;someint&quot;, DbType.Int32);
			target.AddParameter(&quot;somedt&quot;, DbType.DateTime);
		}

		private long CountRecords() {
			m_countAllCmd = m_dbCon.CreateCommand();
			m_countAllCmd.CommandText = string.Format(m_countAllQuery, m_testTableName);

			long ret = (long)m_countAllCmd.ExecuteScalar();
			m_countAllCmd.Dispose();

			return ret;
		}

		private void DeleteRecords() {
			m_deleteAllCmd = m_dbCon.CreateCommand();
			m_deleteAllCmd.CommandText = string.Format(m_deleteAllQuery, m_testTableName);

			m_deleteAllCmd.ExecuteNonQuery();
			m_deleteAllCmd.Dispose();
		}

		private SQLiteDataReader SelectAllRecords() {
			m_selectAllCmd = m_dbCon.CreateCommand();
			m_selectAllCmd.CommandText = string.Format(m_selectAllQuery, m_testTableName);
			return m_selectAllCmd.ExecuteReader();
		}

		[TestMethod()]
		public void AddParameterTest() {
			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			AddParameters(target);

			string pd = target.ParamDelimiter;
			string expectedStmnt = &quot;INSERT INTO [{0}] ([somestring], [somereal], [someint], [somedt]) VALUES ({1}somestring, {2}somereal, {3}someint, {4}somedt)&quot;;
			expectedStmnt = string.Format(expectedStmnt, m_testTableName, pd, pd, pd, pd);
			Assert.AreEqual(expectedStmnt, target.CommandText);
		}

		[TestMethod()]
		public void SQLiteBulkInsertConstructorTest() {
			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			Assert.AreEqual(m_testTableName, target.TableName);

			bool wasException = false;
			try {
				string a = target.CommandText;
			}
			catch (SQLiteException ex) { wasException = true; }

			Assert.IsTrue(wasException);
		}

		[TestMethod()]
		public void CommandTextTest() {
			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			AddParameters(target);

			string pd = target.ParamDelimiter;
			string expectedStmnt = &quot;INSERT INTO [{0}] ([somestring], [somereal], [someint], [somedt]) VALUES ({1}somestring, {2}somereal, {3}someint, {4}somedt)&quot;;
			expectedStmnt = string.Format(expectedStmnt, m_testTableName, pd, pd, pd, pd);
			Assert.AreEqual(expectedStmnt, target.CommandText);
		}

		[TestMethod()]
		public void TableNameTest() {
			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			Assert.AreEqual(m_testTableName, target.TableName);
		}

		[TestMethod()]
		public void InsertTest() {
			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);

			bool didThrow = false;
			try {
				target.Insert(new object[] { &quot;hello&quot; }); //object.length must equal the number of parameters added
			}
			catch (Exception ex) { didThrow = true; }
			Assert.IsTrue(didThrow);

			AddParameters(target);

			target.CommitMax = 4;
			DateTime dt1 = DateTime.Now; DateTime dt2 = DateTime.Now; DateTime dt3 = DateTime.Now; DateTime dt4 = DateTime.Now;
			target.Insert(new object[] { &quot;john&quot;, 3.45f, 10, dt1 });
			target.Insert(new object[] { &quot;paul&quot;, -0.34f, 100, dt2 });
			target.Insert(new object[] { &quot;ringo&quot;, 1000.98f, 1000, dt3 });
			target.Insert(new object[] { &quot;george&quot;, 5.0f, 10000, dt4 });

			long count = CountRecords();
			Assert.AreEqual(4, count);

			SQLiteDataReader reader = SelectAllRecords();

			Assert.IsTrue(reader.Read());
			Assert.AreEqual(&quot;john&quot;, reader.GetString(1)); Assert.AreEqual(3.45f, reader.GetFloat(2));
			Assert.AreEqual(10, reader.GetInt32(3)); Assert.AreEqual(dt1, reader.GetDateTime(4));

			Assert.IsTrue(reader.Read());
			Assert.AreEqual(&quot;paul&quot;, reader.GetString(1)); Assert.AreEqual(-0.34f, reader.GetFloat(2));
			Assert.AreEqual(100, reader.GetInt32(3)); Assert.AreEqual(dt2, reader.GetDateTime(4));

			Assert.IsTrue(reader.Read());
			Assert.AreEqual(&quot;ringo&quot;, reader.GetString(1)); Assert.AreEqual(1000.98f, reader.GetFloat(2));
			Assert.AreEqual(1000, reader.GetInt32(3)); Assert.AreEqual(dt3, reader.GetDateTime(4));

			Assert.IsTrue(reader.Read());
			Assert.AreEqual(&quot;george&quot;, reader.GetString(1)); Assert.AreEqual(5.0f, reader.GetFloat(2));
			Assert.AreEqual(10000, reader.GetInt32(3)); Assert.AreEqual(dt4, reader.GetDateTime(4));

			Assert.IsFalse(reader.Read());

			DeleteRecords();

			count = CountRecords();
			Assert.AreEqual(0, count);
		}

		[TestMethod()]
		public void FlushTest() {
			string[] names = new string[] { &quot;metalica&quot;, &quot;beatles&quot;, &quot;coldplay&quot;, &quot;tiesto&quot;, &quot;t-pain&quot;, &quot;blink 182&quot;, &quot;plain white ts&quot;, &quot;staind&quot;, &quot;pink floyd&quot; };
			Random rand = new Random(Environment.TickCount);

			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			AddParameters(target);

			target.CommitMax = 1000;

			//Insert less records than commitmax
			for (int x = 0; x &amp;lt; 50; x++)
				target.Insert(new object[] { names[rand.Next(names.Length)], (float)rand.NextDouble(), rand.Next(50), DateTime.Now });

			//Close connect to verify records were not inserted
			m_dbCon.Close();

			m_dbCon = new SQLiteConnection(m_connectionString);
			m_dbCon.Open();

			long count = CountRecords();
			Assert.AreEqual(0, count);

			//Now actually verify flush worked
			target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			AddParameters(target);

			target.CommitMax = 1000;

			//Insert less records than commitmax
			for (int x = 0; x &amp;lt; 50; x++)
				target.Insert(new object[] { names[rand.Next(names.Length)], (float)rand.NextDouble(), rand.Next(50), DateTime.Now });

			target.Flush();

			count = CountRecords();
			Assert.AreEqual(50, count);

			//Close connect to verify flush worked
			m_dbCon.Close();

			m_dbCon = new SQLiteConnection(m_connectionString);
			m_dbCon.Open();

			count = CountRecords();
			Assert.AreEqual(50, count);

			DeleteRecords();
			count = CountRecords();
			Assert.AreEqual(0, count);
		}

		[TestMethod()]
		public void CommitMaxTest() {
			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);

			target.CommitMax = 4;
			Assert.AreEqual(4, target.CommitMax);

			target.CommitMax = 1000;
			Assert.AreEqual(1000, target.CommitMax);
		}

		//SPEED TEST
		[TestMethod()]
		public void AllowBulkInsertTest() {
			string[] names = new string[] { &quot;metalica&quot;, &quot;beatles&quot;, &quot;coldplay&quot;, &quot;tiesto&quot;, &quot;t-pain&quot;, &quot;blink 182&quot;, &quot;plain white ts&quot;, &quot;staind&quot;, &quot;pink floyd&quot;};
			Random rand = new Random(Environment.TickCount);

			SQLiteBulkInsert target = new SQLiteBulkInsert(m_dbCon, m_testTableName);
			AddParameters(target);

			const int COUNT = 100;

			target.CommitMax = COUNT;

			DateTime start1 = DateTime.Now;
			for (int x = 0; x &amp;lt; COUNT; x++)
				target.Insert(new object[] { names[rand.Next(names.Length)], (float)rand.NextDouble(), rand.Next(COUNT), DateTime.Now });

			DateTime end1 = DateTime.Now;
			TimeSpan delta1 = end1 - start1;

			DeleteRecords();

			target.AllowBulkInsert = false;
			DateTime start2 = DateTime.Now;
			for (int x = 0; x &amp;lt; COUNT; x++)
				target.Insert(new object[] { names[rand.Next(names.Length)], (float)rand.NextDouble(), rand.Next(COUNT), DateTime.Now });

			DateTime end2 = DateTime.Now;
			TimeSpan delta2 = end2 - start2;

			//THIS MAY FAIL DEPENDING UPON THE MACHINE THE TEST IS RUNNING ON.
			Assert.IsTrue(delta1.TotalSeconds &amp;lt; 0.1); //approx true for 100 recs 			Assert.IsTrue(delta2.TotalSeconds &amp;gt; 1.0); //approx true for 100 recs;

			//UNCOMMENT THIS TO MAKE IT FAIL AND SEE ACTUAL NUMBERS IN FAILED REPORT
			//Assert.AreEqual(delta1.TotalSeconds, delta2.TotalSeconds);

			DeleteRecords();
		}
	}
}
</pre>
<p>Enjoy. Drop me a line if you have any problems.</p>
<p>Follow me on Twitter: <a href="http://twitter.com/jprichardson">@jprichardson</a></p>
<p>-JP</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/30/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=30&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2009/09/08/sqlite-bulk-insert/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
		<item>
		<title>Read File Contents (Blobs) in GWT and Gears</title>
		<link>http://procbits.com/2009/07/29/read-file-contents-blobs-in-gwt-and-gears/</link>
		<comments>http://procbits.com/2009/07/29/read-file-contents-blobs-in-gwt-and-gears/#comments</comments>
		<pubDate>Wed, 29 Jul 2009 21:24:01 +0000</pubDate>
		<dc:creator>JP</dc:creator>
				<category><![CDATA[GWT]]></category>

		<guid isPermaLink="false">http://procbits.com/?p=19</guid>
		<description><![CDATA[What do you do if you want to read the contents of a file in your GWT application? One possible solution is to use Google Gears. Gears offers a method to allow a user to select file(s). You can then use the returned &#8220;getFiles&#8221; method of the &#8220;OpenFilesEvent&#8221; object to find out what file(s) the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=19&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>What do you do if you want to read the contents of a file in your GWT application? One possible solution is to use Google Gears.</p>
<p>Gears offers a method to allow a user to select file(s). You can then use the returned &#8220;getFiles&#8221; method of the &#8220;OpenFilesEvent&#8221; object to find out what file(s) the user selected. Each &#8220;File&#8221; class has a method called &#8220;getBlob&#8221; that returns a &#8220;Blob&#8221; object. However, each blob object doesn&#8217;t provide any direct way to access the blobs contents. Many <a href="http://www.arcaner.com/2008/09/14/google-gears-blob-hate/">people</a> <a href="http://groups.google.com/group/gears-users/browse_thread/thread/0b4d3933a1ef0e91?fwc=1">haven&#8217;t</a> found a way to read the blob contents.</p>
<p>I wrote a class to access the contents of the blob. The class is called &#8220;BlobReader&#8221; and is very simple to use. The trick lies in the fact that in Javascript we can access the &#8220;getBytes&#8221; method of the blob.</p>
<p>Here is an example reading line by line of a text file:</p>
<pre>try {
	Desktop dt = Factory.getInstance().createDesktop();
	dt.openFiles(new OpenFilesHandler(){
		public void onOpenFiles(OpenFilesEvent event) {
			File[] files = event.getFiles();
			File file = files[0];
			Blob data = file.getBlob();

			BlobReader br = new BlobReader(data);
			while (!br.endOfBlob())
				Window.alert(br.readLine());
			}
		}, true);
} catch (Exception ex){
	Window.alert(ex.toString());
}</pre>
<p>Here is BlobReader.java:</p>
<pre>package com.yourpackage.client;
import com.google.gwt.core.client.JsArrayInteger;
import com.google.gwt.gears.client.blob.Blob;

public class BlobReader {

	private final int CHUNK_SIZE = 1024;

	public BlobReader(Blob blob){
		this.blob = blob;
	}

	private Blob blob;
	public Blob getBlob(){ return this.blob; }

	private int blobPointer = 0;
	public int getBlobPointer(){ return this.blobPointer; }

	public boolean endOfBlob(){
		return (blobPointer &gt;= blob.getLength());
	}

	public byte[] readAllBytes(){
		return getBlobBytes(this.blob);
	}

	public String readAllText(){
		int size = this.blob.getLength();
		StringBuilder sb = new StringBuilder(size);

		JsArrayInteger bytes = getBlobBytes(this.blob, 0, size);
		for (int x = 0; x &lt; size; x++)
			sb.append((char)bytes.get(x));

		return sb.toString();
	}

	public String readLine(){
		int size = CHUNK_SIZE;
		boolean foundEndOfLine = false;

		JsArrayInteger bytes;
		StringBuilder sb = new StringBuilder(CHUNK_SIZE);

		while (!foundEndOfLine &amp;&amp; size &gt; 0){
			int dif = this.blob.getLength() - this.blobPointer; //remainder of the data
			if (dif &lt; CHUNK_SIZE)
				size = dif;
			bytes = getBlobBytes(this.blob, this.blobPointer, size);

			for (int x = 0; x &lt; size; x++){
				blobPointer++;
				int b = bytes.get(x);
				if (b == 10){ //newline
					foundEndOfLine = true;
					break;
				}
				sb.append((char)b);

				if (this.getBlobPointer() % 1000000 == 0)
					Window.alert("" + this.getBlobPointer());
			}
		}

		if (sb.substring(sb.length() - 1) == "\r")
			sb.deleteCharAt(sb.length() - 1);

		return sb.toString();
	}

       public void reset(){
		this.blobPointer = 0;
	}

	private byte[] getBlobBytes(Blob b){
		JsArrayInteger array = getBlobBytes(b, 0, b.getLength());
		byte[] bytes = new byte[array.length()];
		for (int x = 0; x &lt; bytes.length; x++)
			bytes[x] = (byte) array.get(x); //in google docs we are told these are from 0-255

		return bytes;
	}

	private native JsArrayInteger getBlobBytes(Blob b, int offset, int length) /*-{
		return b.getBytes(offset, length);
	}-*/;
}</pre>
<p>Notes:<br />
1) This hasn&#8217;t been thoroughly tested/debugged.<br />
2) At the time of this writing, I&#8217;m using Gears 0.5 with the GWT-Gears 1.2.1. In the current GWT-Gears svn trunk you can see upcoming support for the GWT methods &#8220;getNativeBytes&#8221; and &#8220;getBytes&#8221;</p>
<p>Enjoy!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/procbits.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/procbits.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/procbits.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/procbits.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/procbits.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/procbits.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/procbits.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/procbits.wordpress.com/19/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=procbits.com&amp;blog=6893023&amp;post=19&amp;subd=procbits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://procbits.com/2009/07/29/read-file-contents-blobs-in-gwt-and-gears/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4ecadec0193bc16860cf20d02204ce3d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">JP</media:title>
		</media:content>
	</item>
	</channel>
</rss>