<?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>Jason Staten&#187;  &#8211; Jason Staten</title>
	<atom:link href="http://blog.jstaten.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jstaten.com</link>
	<description>Coding Tutorials, Photography, Reviews, and Interests of a Neumont Computer Science Major.</description>
	<lastBuildDate>Wed, 11 Nov 2009 16:45:03 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>In Memory Database Testing with SQLite and NHibernate</title>
		<link>http://blog.jstaten.com/memory-database-testing-sqlite-nhibernate/</link>
		<comments>http://blog.jstaten.com/memory-database-testing-sqlite-nhibernate/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 16:45:03 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Moq]]></category>
		<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[Sqlite]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=199</guid>
		<description><![CDATA[A few weeks ago, I was faced with the challenge of testing how an application interacted with a database without mangling the data within it. What my company of employment had been doing prior was doing all database testing within a transaction and rolling back at the end. The issue with this approach was that [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago, I was faced with the challenge of testing how an application interacted with a database without mangling the data within it. What my company of employment had been doing prior was doing all database testing within a transaction and rolling back at the end. The issue with this approach was that behaviors like cascading wouldn&#8217;t occur, thus making the tests less than useful.</p>
<h1>SQLite</h1>
<p>Enter SQLite. <a href="http://www.sqlite.org/">SQLite</a> is a basic, lightweight sql database wrapped into a single library. A benefit of its use is that SQLite can create an in-memory database that cleans up after all connections are closed. Its excellent for testing. Starting with a clean slate each test run can provide for consistent, reproducible results.</p>
<h1>Prerequisites</h1>
<p><a href="http://nhforge.org/Default.aspx">NHibernate</a> comes with support for SQLite from the NHibernate.Driver.SQLite20Driver class. However, you must provide two other files for it to work. First, <a href="http://www.sqlite.org/sqlitedll-3_6_20.zip">sqlite3.dll</a>, an unmanaged library of SQLite; include it in your test project and ensure &#8220;copy to output directory&#8221; is marked. Second, <a href="http://sourceforge.net/projects/sqlite-dotnet2/files/SQLite%20for%20ADO.NET%202.0/">System.Data.SQLite</a>, a managed library that allows ADO.NET to interact with SQLite; include this as a reference in your test project.</p>
<h1>A Base Class</h1>
<p>The following is a basic example of how to set up a base class for in memory database testing. Any tests that require database interaction should inherit from this class and will have the Session object available. Sessions last as long as each test fixture. Also, <em>typeof(Plan)</em> refers to the type of any of your domain classes.</p>
<pre class="brush: c#"> 	public class InMemoryDatabaseTest
	{
		private static Configuration _configuration;
		private readonly object _baton = new object();
		private readonly ISessionFactory _sessionFactory;
		protected readonly ISession Session;

		public InMemoryDatabaseTest()
		{
			if (_configuration == null)
				lock (_baton)
					if (_configuration == null)
					{
						typeof(VersionDate2).GetField(&quot;_sqlType&quot;,BindingFlags.Static | BindingFlags.NonPublic).SetValue(null,new SqlType(DbType.DateTime));
						_configuration = new Configuration()
							.SetProperty(Environment.ReleaseConnections,&quot;on_close&quot;)
							.SetProperty(Environment.ProxyFactoryFactoryClass,
							             &quot;NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle&quot;)
							.SetProperty(Environment.TransactionStrategy, &quot;NHibernate.Transaction.AdoNetTransactionFactory&quot;)
							.SetProperty(Environment.CacheProvider, &quot;NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache&quot;)
							.SetProperty(Environment.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName)
							.SetProperty(Environment.ConnectionProvider, &quot;NHibernate.Connection.DriverConnectionProvider&quot;)
							.SetProperty(Environment.Isolation, &quot;ReadCommitted&quot;)
							.SetProperty(Environment.ConnectionString, &quot;Data Source=:memory:;Version=3;New=True;&quot;)
							.SetProperty(Environment.ShowSql,&quot;True&quot;)
							.SetProperty(Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
							.AddAssembly(Assembly.GetAssembly(typeof (Plan)));

			_sessionFactory = _configuration.BuildSessionFactory();
			Session = _sessionFactory.OpenSession();
			var schemaExport = new SchemaExport(_configuration);
			schemaExport.Execute(false, true, false, Session.Connection, null);
		}

		public void Dispose()
		{
			Session.Dispose();
		}
	}
</pre>
<h1>Additional Features</h1>
<h2>Support for Schemas</h2>
<p>SQLite doesn&#8217;t provide native support for schemas. We use SQL Server, and this led to a problem when any of our mappings pointed to tables in anything other than the dbo schema. A simple fix to this is to replace all periods with underscores prior to creating your session factory. This gives the desired behavior without requiring any modification to your mapping files.</p>
<pre class="brush: c#">                    if (_configuration == null)
                    {
                        _configuration = new Configuration()
                        //Configuation...
                        foreach (PersistentClass classMapping in _configuration.ClassMappings)
                        {
                            if (classMapping.Table.Name.Contains(&quot;.&quot;))
                                classMapping.Table.Name = classMapping.Table.Name.Replace(&quot;.&quot;, &quot;_&quot;);
                        }
                    }
</pre>
<h2>Working with AutoMockContainer</h2>
<p>If you&#8217;re a user of <a href="http://code.google.com/p/moq-contrib/">Moq-Contrib</a>&#8217;s AutoMockContainer (it <a href="http://blog.jstaten.com/moq-contrib-compatability-patch/">must be patched</a> to work with the latest version of <a href="http://code.google.com/p/moq/">Moq</a>), you can register the Session object into the container to have it provided instead of a mocked session. It&#8217;s as simple as adding the following after creating your session object.</p>
<pre class="brush: c#">            MockContainer.Register(Session);
</pre>
<h2>Testing with NHProf</h2>
<p>If you use NHibernate Profiler (if you don&#8217;t, you should be), your SQLite database interaction can be monitored using that as well. Add an AssemblyInitialize (or your testing framework&#8217;s variant) to your InMemoryDatabaseTest class and all interactions will be profiled.</p>
<pre class="brush: c#">		[AssemblyInitialize]
		public static void AssemblyInit(TestContext testContext)
		{
			NHibernateProfiler.Initialize();
		}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/memory-database-testing-sqlite-nhibernate/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Moq-Contrib Moq 4.0 Compatability Patch</title>
		<link>http://blog.jstaten.com/moq-contrib-compatability-patch/</link>
		<comments>http://blog.jstaten.com/moq-contrib-compatability-patch/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 15:05:20 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=191</guid>
		<description><![CDATA[As a new but frequent user of the Moq mocking framework for .NET, I was disappointed to find Moq-Contrib to be out of date as I wanted the AutoMockContainer. Performing dependency injection by hand and updating my tests for every code change was a pain. I dug into some source, found a simple fix and [...]]]></description>
			<content:encoded><![CDATA[<p>As a new but frequent user of the Moq mocking framework for .NET, I was disappointed to find Moq-Contrib to be out of date as I wanted the AutoMockContainer. Performing dependency injection by hand and updating my tests for every code change was a pain. I dug into some source, found a simple fix and it is the patch that follows.</p>
<pre class="brush: patch">
Index: Source/Mvc/HttpContextMock.cs
===================================================================
--- Source/Mvc/HttpContextMock.cs	(revision 23)
+++ Source/Mvc/HttpContextMock.cs	(working copy)
@@ -58,11 +58,11 @@
 			this.HttpServerUtility = new HttpServerUtilityMock();
 			this.HttpSessionState = new HttpSessionStateMock();

-			this.ExpectGet(c =&gt; c.Application).Returns(this.HttpApplicationState.Object);
-			this.ExpectGet(c =&gt; c.Request).Returns(this.HttpRequest.Object);
-			this.ExpectGet(c =&gt; c.Response).Returns(this.HttpResponse.Object);
-			this.ExpectGet(c =&gt; c.Server).Returns(this.HttpServerUtility.Object);
-			this.ExpectGet(c =&gt; c.Session).Returns(this.HttpSessionState.Object);
+			this.SetupGet(c =&gt; c.Application).Returns(this.HttpApplicationState.Object);
+			this.SetupGet(c =&gt; c.Request).Returns(this.HttpRequest.Object);
+			this.SetupGet(c =&gt; c.Response).Returns(this.HttpResponse.Object);
+			this.SetupGet(c =&gt; c.Server).Returns(this.HttpServerUtility.Object);
+			this.SetupGet(c =&gt; c.Session).Returns(this.HttpSessionState.Object);
 		}

 		/// &lt;summary&gt;
Index: Source/Mvc/HttpRequestMock.cs
===================================================================
--- Source/Mvc/HttpRequestMock.cs	(revision 23)
+++ Source/Mvc/HttpRequestMock.cs	(working copy)
@@ -56,8 +56,8 @@
 		/// &lt;/summary&gt;
 		public HttpRequestMock()
 		{
-			this.ExpectGet(f =&gt; f.Form).Returns(form);
-			this.ExpectGet(f =&gt; f.Headers).Returns(headers);
+			this.SetupGet(f =&gt; f.Form).Returns(form);
+			this.SetupGet(f =&gt; f.Headers).Returns(headers);
 		}

 	}
Index: Source/Mvc/HttpResponseMock.cs
===================================================================
--- Source/Mvc/HttpResponseMock.cs	(revision 23)
+++ Source/Mvc/HttpResponseMock.cs	(working copy)
@@ -57,9 +57,9 @@
 			this.OutputStream = new Mock&lt;Stream&gt;();
 			this.Cache = new HttpCachePolicyBaseMock();

-			ExpectGet(m =&gt; m.Output).Returns(this.Output.Object);
-			ExpectGet(m =&gt; m.OutputStream).Returns(this.OutputStream.Object);
-			ExpectGet(m =&gt; m.Cache).Returns(this.Cache.Object);
+			SetupGet(m =&gt; m.Output).Returns(this.Output.Object);
+			SetupGet(m =&gt; m.OutputStream).Returns(this.OutputStream.Object);
+			SetupGet(m =&gt; m.Cache).Returns(this.Cache.Object);
 		}

 		// TODO: mock other properties.
</pre>
<p>Ensure that the Moq 4.0 dll is in the Lib/Moq folder before building.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/moq-contrib-compatability-patch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Yield in C#</title>
		<link>http://blog.jstaten.com/using-yield-csharp/</link>
		<comments>http://blog.jstaten.com/using-yield-csharp/#comments</comments>
		<pubDate>Fri, 22 May 2009 19:54:19 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Papers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Iterating]]></category>
		<category><![CDATA[Yield]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=186</guid>
		<description><![CDATA[The yield Statement
 yield is an overlooked, yet powerful feature.
yield basics
yield places values into an IEnumerable object.
To further understand what yield does, here’s an example with trace statements between each yield statement:

//:SimpleYield.cs
using System;
using System.Collections.Generic;

class SimpleYield
{
static IEnumerable GetValues(){
Console.WriteLine(&#34;Returning 1&#34;);
yield return 1;
Console.WriteLine(&#34;Returning 2&#34;);
yield return 2;
Console.WriteLine(&#34;Returning 3&#34;);
yield return 3;
}
static void Main(){
//Iterate over YieldMethod&#039;s IEnumerable
foreach(int i in GetValues())
Console.WriteLine(i);
}
}/*Output:
Returning 1
1
Returning [...]]]></description>
			<content:encoded><![CDATA[<h1>The yield Statement</h1>
<p><em> yield is an overlooked, yet powerful feature.</em></p>
<h2>yield basics</h2>
<p>yield places values into an IEnumerable object.<br />
To further understand what yield does, here’s an example with trace statements between each yield statement:</p>
<pre class="brush: c#">
//:SimpleYield.cs
using System;
using System.Collections.Generic;

class SimpleYield
{
static IEnumerable GetValues(){
Console.WriteLine(&quot;Returning 1&quot;);
yield return 1;
Console.WriteLine(&quot;Returning 2&quot;);
yield return 2;
Console.WriteLine(&quot;Returning 3&quot;);
yield return 3;
}
static void Main(){
//Iterate over YieldMethod&#039;s IEnumerable
foreach(int i in GetValues())
Console.WriteLine(i);
}
}/*Output:
Returning 1
1
Returning 2
2
Returning 3
3
*///:~
</pre>
<p>GetValues( )’s yield statements return hard-coded integer values. Main( ) iterates these values, printing each. Notice how GetValue( )’s trace statements interlace with Main( )’s.<br />
A yield statement comes in two different forms, yield return  and yield break. yield return  places the evaluated expression as the current value of the IEnumerable.  yield break marks the end of an iterator:</p>
<pre class="brush: c#">
//:YieldBreak.cs
using System;
using System.Collections.Generic;

class YieldBreak{
static IEnumerable GetValues(){
Console.WriteLine(&quot;Returning 1&quot;);
yield return 1;
Console.WriteLine(&quot;Returning 2&quot;);
yield return 2;
Console.WriteLine(&quot;Breaking&quot;);
yield break;                //Break Here
Console.WriteLine(&quot;Returning 3&quot;);
yield return 3;
}
static void Main(){
foreach(int i in GetValues())
Console.WriteLine(i);
}
}/*Output:
Returning 1
1
Returning 2
2
Breaking
*///:~
</pre>
<p>yield break prevents remaining code from executing. It reports back to the foreach that there are no values remaining in the IEnumerable. C#’s compiler reports a warning about any unreachable code following yield break.<br />
<strong>Exercise 1:</strong> Use Visual Studio’s debugger to step through (F11) SimpleYield.cs. Follow the code path as the foreach executes.<br />
<strong>Exercise 2: </strong>Create a GetValue( ) method that returns a random number of integer values. Use yield return and yield break.</p>
<pre class="brush: c#">
///: Exercise2.cs
using System;
using System.Collections.Generic;

class Exercise2{
public static IEnumerable GetValues(){
Random rand = new Random();
int current = 0;
while (true){
current = rand.Next(20);
if (current == 17)
yield break;
yield return current;
}
}

public static void Main(){
foreach (int i in GetValues()){
Console.WriteLine(i);
}
}
}
///:~
</pre>
<h2>yield Benefits</h2>
<p>One strong feature of yield is its ability to defer processing. It delays any calculation until absolutely necessary. Deferred processing makes more responsive programs. yield spreads wait time amongst all iterations by creating values only when necessary:</p>
<pre class="brush: c#">
///: DeferredProcessingTime.cs
using System;
using System.Collections.Generic;
using System.Threading;

class DeferredProcessingTime{
public static IEnumerable CalculateAtOnce(){
int[] intArray = new int[10];
for (int i = 0; i &amp;amp;amp;lt; 10; i++){
Thread.Sleep(1000);
intArray[i] = i;
}
return intArray;
}
public static IEnumerable DeferredCalculate(){
for (int i = 0; i &amp;amp;amp;lt; 10; i++){
Thread.Sleep(1000);
yield return i;
}
}
public static void Main(){
Console.WriteLine(&quot;Calculate at once&quot;);
foreach (int i in CalculateAtOnce()) //Ten seconds before printing
Console.Write(i);
Console.WriteLine(&quot;\nUsing Yield&quot;);
foreach (int z in DeferredCalculate())
Console.Write(z); //One second between each write
}
}/*Output:
Calculate at once
0123456789
Using Yield
0123456789
*///:~
</pre>
<p>The above example emulates an algorithm that takes a long time to process by using Thread.Sleep( ) before adding each value.<br />
Both foreachs over CalculateAtOnce( ) and DefferedCalculate( ) print the same results to the console. However the execution behavior is noticeably different. CalculateAtOnce( )’s foreach waits for 10 seconds and prints 0 through 9. DeferredCalculate( )’s foreach prints each value per second.<br />
Another benefit of yield’s deferred processing is that it does not require a collection stored in memory.  yield can iterate over a large set of data without consuming large amounts of memory. Take the following example. You iterate over a set of data with 10 million integer values. Without yield, the entire collection of values must be returned. With yield, each integer value is returned when requested.</p>
<pre class="brush: c#">
///:DeferredProcessingMemory.cs
using System;
using System.Collections.Generic;
using System.Threading;

class DeferredProcessingMemory{
public static IEnumerable CalculateAtOnce(){
int[] intArray = new int[10000000];
for (int i = 0; i &amp;amp;amp;lt; 10000000; i++)
intArray[i] = i;
return intArray;
}
public static IEnumerable DeferredCalculate(){
for (int i = 0; i &amp;amp;amp;lt; 10000000; i++)
yield return i;
}
public static void Main(){
Console.WriteLine(&quot;Using Yield&quot;);
IEnumerable deferred = DeferredCalculate();
Console.ReadLine(); //Memory usage: ~2MB
Console.WriteLine(&quot;Calculating at once&quot;);
IEnumerable atOnce = CalculateAtOnce();
Console.ReadLine(); //Memory usage: ~40MB
}
}/*Output:
Using Yield

Calculating at once

*///:~
</pre>
<p>Start the Windows Task Manager (Ctrl+Shift+Esc) before running this example. Find your process, and notice the amount of memory usage from using DeferredCalculate( ). Press enter and see the drastic increase that CalculateAtOnce( ) makes; intArray’s 10 million in-memory values are the cause.<br />
yield gives potential to handle data sets of any size without concern for memory limitations.<br />
<strong>Exercise 3</strong>: Use yield to iterate over an infinite data set of random integers.</p>
<pre class="brush: c#">
///:Exercise3.cs
using System;
using System.Collections.Generic;

class Exercise3{
public static Random rand = new Random();
public static IEnumerable GetValues(){
while(true)
yield return rand.Next();
}
public static void Main(){
foreach(int i in GetValues())
Console.WriteLine(i);
}
}
///:~
</pre>
<h2>Under the Hood</h2>
<p>Many C# keywords involve the generation of MSIL code, methods, or even classes. yield is no exception.<br />
<a title=".NET Reflector" href="http://www.red-gate.com/products/reflector/">Red Gate’s .NET Reflector</a> shows the generated C# from using the yield statement.  The disassembled assembly of SimpleYield.cs contains an extra class implementing IEnumerable.</p>
<pre class="brush: c#">
public class GeneratedClass : IEnumerable, IEnumerable,
IEnumerator, IEnumerator, IDisposable{
//...CUT...
public bool MoveNext(){
switch (this.state){
case 0:
this.state = -1;
Console.WriteLine(&quot;Returning 1&quot;);
this.current = 1;
this.state = 1;
return true;

case 1:
this.state = -1;
Console.WriteLine(&quot;Returning 2&quot;);
this.current = 2;
this.state = 2;
return true;

case 2:
this.state = -1;
Console.WriteLine(&quot;Returning 3&quot;);
this.current = 3;
this.state = 3;
return true;

case 3:
this.state = -1;
break;
}
return false;
}
//...CUT...
}
</pre>
<p>The compiler generates a switch statement to handle executing the code written in your original yielding method. Only one case statement is used for each time MoveNext( ) is called. This is how the deferred processing actually occurs.<br />
GetValues( ) is also changed to use the GeneratedClass( ) in place of the original code.</p>
<pre class="brush: c#">
private static IEnumerable GetValues(){
return new GeneratedClass(-2);
}
</pre>
<p>The -2 in the new GeneratedClass( ) call is used to set the initial state. The state’s value is changed when MoveNext( ) is called. Beginning each case, state is set to -1 to prevent further execution if an exception occurs. Just before a case returns, state is assigned the value of the next case.<br />
<strong>Exercise 4</strong>: Write an implementation of yield’s generated code and execute a foreach over it.</p>
<pre class="brush: c#">
//:Exercise4.cs
using System;
using System.Collections.Generic;
using System.Collections;

class Exercise4 : IEnumerable,IEnumerable,
IEnumerator,IEnumerator, IDisposable{
string current = &quot;&quot;;
int state;
public IEnumerator GetEnumerator(){
return this;
}
IEnumerator IEnumerable.GetEnumerator(){
return GetEnumerator();
}
public string Current{
get { return current; }
}
public void Dispose(){}
object IEnumerator.Current{
get { return Current; }
}
public bool MoveNext(){
switch(state){
case 0:
state = -1;
current = &quot;One&quot;;
state = 1;
return true;
case 1:
state = -1;
current = &quot;Two&quot;;
state = 2;
return true;
case 2:
state = -3;
current = &quot;Three&quot;;
state = 3;
return true;
}
return false;
}
public void Reset(){
throw new NotImplementedException();
}
public static void Main(){
foreach(string s in new Exercise4())
Console.WriteLine(s);
}
}/*Output:
One
Two
Three
*///:~
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/using-yield-csharp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>StatenUtil: C# String-Regex Extenstions and String Scanner</title>
		<link>http://blog.jstaten.com/statenutil-string-regex-extensions/</link>
		<comments>http://blog.jstaten.com/statenutil-string-regex-extensions/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 17:35:58 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[StatenUtil]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=180</guid>
		<description><![CDATA[Face it, C# is not as regex-friendly as it could be.  To do things like find a single regex match involves several lines or some nasty inline code. Using Extension methods, this can be simplified. In another addition to StatenUtil focused on regex, C# becomes a more coder-friendly language.
StringRegex.cs

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace StatenUtil.RegexExtensions
{
  public [...]]]></description>
			<content:encoded><![CDATA[<p>Face it, C# is not as regex-friendly as it could be.  To do things like find a single regex match involves several lines or some nasty inline code. Using Extension methods, this can be simplified. In another addition to <a title="StatenUtil" href="http://blog.jstaten.com/tag/statenutil/">StatenUtil</a> focused on regex, C# becomes a more coder-friendly language.</p>
<h3>StringRegex.cs</h3>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace StatenUtil.RegexExtensions
{
  public static class StringRegex
  {
    public static string RegexReplace(this string source, string regex, string replacement)
    {
      Regex r = new Regex(regex);
      return r.Replace(source, replacement);
    }
    public static string Match(this string source, string regex)
    {
      Regex r = new Regex(regex);
      Match m = r.Match(source);
      return m.Value;
    }
    public static string[] Matches(this string source, string regex)
    {
      Regex r = new Regex(regex);
      MatchCollection mc = r.Matches(source);
      List&lt;string&gt; matches = new List&lt;string&gt;();
      foreach(object o in mc)
        matches.Add(((Match)o).Value);
      return matches.ToArray();
    }
    public static string RegexRemove(this string source, string regex)
    {
      Regex r = new Regex(regex);
      return r.Replace(source, &quot;&quot;);
    }
  }
}
</pre>
<p>This class offers four extension methods to the string class: Replace, Remove, Match first, and Match all. Aside from <em>RegexReplace</em>, the parameters often call for a single regular expression string.</p>
<p>Another addition that C# could use is a string scanner. A string scanner moves through a string one regex at a time matching the beginning of a string. This is useful for parsing languages in the way similar to <a title="JSON Parsing in Ruby" href="http://blog.jstaten.com/json-parsing-in-ruby/">JSON Parsing in Ruby</a>.</p>
<h3>StringScanner.cs</h3>
<pre class="brush: c#">
using System;

namespace StatenUtil.RegexExtensions
{
  public class StringScanner
  {
    public string Remaining { get; set; }
    public string Match { get; set; }
    public StringScanner(string input)
    {
      Remaining = input;
    }
    public string Scan(string regex)
    {
      Match = Remaining.Match(&quot;^&quot;+regex);
      if (Match != null)
        Remaining = Remaining.Substring(Match.Length);
      return Match;
    }
  }
}
</pre>
<p>The <em>StringScanner</em> class constructor takes an input string that it will scan. Having only a <em>Scan</em> method, the class has the single use of moving through the input string as regex matches are made. As <em>Scan</em> finds a match, it returns the matching string. Also, the class has two properties: <em>Remaining</em> and <em>Match</em>. <em>Remaining</em> provides what is left in the string, useful for checking if the end of the input string has been met. <em>Match</em> provides the most recent match of the <em>Scan</em> method.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/statenutil-string-regex-extensions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Site is back up and GoDaddy-free</title>
		<link>http://blog.jstaten.com/site-back-up/</link>
		<comments>http://blog.jstaten.com/site-back-up/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 18:19:37 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[GoDaddy]]></category>
		<category><![CDATA[Rant]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=174</guid>
		<description><![CDATA[This past week has been a terrible experience for both me and my website. It was nearing time for my domain to expire, so I decided that I would transfer away from the evil that is GoDaddy (I moved the hosting several months ago). Little did I know that they would attempt one last strike [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><img class="size-full wp-image-175 alignleft" src="http://blog.jstaten.com/wp-content/uploads/nodaddy.gif" alt="NoDaddy" width="220" height="200" />This past week has been a terrible experience for both me and my website. It was nearing time for my domain to expire, so I decided that I would transfer away from the evil that is GoDaddy (I moved the hosting several months ago). Little did I know that they would attempt one last strike at me before letting me slip away for good. I initiated the domain transfer on the 23rd, and I received an email making claim that it would take approximately 3 days to complete. I could handle that.</p>
<p style="text-align: left;">On the 25th, I go to my website only to find that it has been replaced with a GoDaddy landing page. I nearly flipped. I was supposed to be moving away from them, not having them take over. I put it off for a day, hoping that it would be a very short term deal. The next day, I see that it&#8217;s still there and I want to get this squared away. So I give GoDaddy a call to wind up listening to hold music for nearly a half hour before I decide that I&#8217;m sick of wasting my cellphone minutes.</p>
<p style="text-align: left;">On Saturday, the 28th the problem still remained and since I have free weekends, I gave them another phone call. 20 minutes into hold I get an answer from some guy. I explained to him about what my situation was and asked him to check out my domain to make sure everything was okay. He checked it out, said it was all good and out of their hands.</p>
<p style="text-align: left;">Today, I found out that GoDaddy had in fact <strong>CANCELLED </strong>the transfer because the domain was &#8220;locked.&#8221; Of course, I went to GD&#8217;s site to check this out, and it was marked as &#8220;unlocked&#8221; just as I had set it before doing the transfer. I contacted my registrar to ask them to try again today, and was able to have the site up within about 2 hours. My domain&#8217;s no longer listed through GoDaddy, and I am thrilled to never have to deal with them again.</p>
<p style="text-align: left;">My recommendation to anyone reading is <strong>DO NOT</strong> do any sort of business with GoDaddy. Even if they have low prices and scantly clad women in their commercials, it&#8217;s just not worth it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/site-back-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Photography Friday XI: Sunstone Hunting</title>
		<link>http://blog.jstaten.com/photography-friday-sunstone-hunting/</link>
		<comments>http://blog.jstaten.com/photography-friday-sunstone-hunting/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 23:46:18 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Photography]]></category>
		<category><![CDATA[Photography Friday]]></category>
		<category><![CDATA[Sledgehammer]]></category>
		<category><![CDATA[Sunstones]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=169</guid>
		<description><![CDATA[Yes, I understand I missed last week. How about a four-pic-feature this week to make up for it. Sound fair?

Hunting for suntones is rough. You can work for 15 minutes on a piece of rock to find nothing. But the search for the big one is worth it.
]]></description>
			<content:encoded><![CDATA[<p><em>Yes, I understand I missed last week. How about a four-pic-feature this week to make up for it. Sound fair?</em></p>
<p style="text-align: center;"><a class="flickr-image alignnone" title="Pound" rel="flickr-mgr" href="http://www.flickr.com/photos/33716748@N06/3371666590/"><img class="flickr-large" src="http://farm4.static.flickr.com/3543/3371666590_0ce37a009b_m.jpg" alt="Pound" /></a><a class="flickr-image alignnone" title="Sunstone" rel="flickr-mgr" href="http://www.flickr.com/photos/33716748@N06/3371666410/"><img class="flickr-large" src="http://farm4.static.flickr.com/3567/3371666410_e85617d829_m.jpg" alt="Sunstone" /></a><a class="flickr-image alignnone" title="Tube of Stones" rel="flickr-mgr" href="http://www.flickr.com/photos/33716748@N06/3370845489/"><img class="flickr-large" src="http://farm4.static.flickr.com/3647/3370845489_f41f8fb28e_m.jpg" alt="Tube of Stones" /></a><a class="flickr-image alignnone" title="Hunting" rel="flickr-mgr" href="http://www.flickr.com/photos/33716748@N06/3371665608/"><img class="flickr-large" src="http://farm4.static.flickr.com/3642/3371665608_36edb18bff_m.jpg" alt="Hunting" /></a></p>
<p style="text-align: center;">Hunting for suntones is rough. You can work for 15 minutes on a piece of rock to find nothing. But the search for the big one is worth it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/photography-friday-sunstone-hunting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSON Parsing in Ruby</title>
		<link>http://blog.jstaten.com/json-parsing-in-ruby/</link>
		<comments>http://blog.jstaten.com/json-parsing-in-ruby/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 14:44:27 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=165</guid>
		<description><![CDATA[Yesterday, I spent awhile working on a RubyQuiz Challenge involving the parsing of JSON. Although I did create it with minimal viewing of the solution, I cannot take credit for the code or the idea.  I did notice that on the site there was no actual merging of their snippets, so I felt inclined to [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I spent awhile working on a <a title="Ruby Quiz - Parsing JSON" href="http://rubyquiz.com/quiz155.html">RubyQuiz Challenge</a> involving the parsing of JSON. Although I did create it with minimal viewing of the solution, I <em>cannot</em> take credit for the code or the idea.  I did notice that on the site there was no actual merging of their snippets, so I felt inclined to share.</p>
<h3>jsonParser.rb</h3>
<pre class="brush: ruby">
require &quot;strscan&quot;
class JSONParser
	AST = Struct.new(:value)
	def parse(input)
		@input = StringScanner.new(input)
		parse_value.value
	ensure
		@input.eos? or error(&quot;Unexpected data&quot;)
	end

	private

	def parse_value
		trim_space
		parse_object or
		parse_array or
		parse_string or
		parse_number or
		parse_keyword or
		error(&quot;Invalid Data&quot;)
	ensure
		trim_space
	end

	#Parses colon separated object hashes
	def parse_object
		if @input.scan(/\s*\{/)
			obj = Hash.new
			more_parts = false
			while key = parse_string
				@input.scan(/\s*:\s*/) or error(&quot;Expected : separator&quot;)
				obj[key.value] = parse_value.value
				more_parts = @input.scan(/\s*,\s*/) or break
			end
			error(&quot;Missing object pair&quot;) if more_parts
			@input.scan(/\s*}/) or error(&quot;Unclosed object&quot;)
			AST.new(obj)
		else
			false
		end
	end

	def parse_array
		if @input.scan(/\s*\[/) #Arrays start with [
			a = Array.new
			more_items = false
			while current = parse_value
			a &lt;&lt; current.value
			more_items = @input.scan(/\s*,\s*/) or break
			end
			error(&quot;Missing value&quot;) if more_items
			@input.scan(/s*\]/) or error(&quot;Unclosed array&quot;)
			AST.new(a)
		end
	end

	#Parses string objects
	def parse_string
		if @input.scan(/&quot;/)
			s = String.new
			while current = parse_string_content || parse_string_escape
				s &lt;&lt; current.value
			end
			@input.scan(/&quot;/) or error(&#039;Unclosed String&#039;)
			AST.new(s)
		else
			false
		end
	end

	def parse_string_content
		@input.scan(/[^\\&quot;]+/) and AST.new(@input.matched)
	end

	def parse_string_escape
		if @input.scan(%r{\\[&quot;\\/]}) #slashes and quotations
			AST.new(@input.matched[-1])
		elsif @input.scan(/\\[bfnrt]/) #newlines, tabs, etc
			AST.new(eval(%Q{&quot;#{@input.matched}&quot;}))
		elsif @input.scan(/\\u[0-9a-fA-F]{4}/) #Hex integers
			AST.new([Integer(&quot;0x#{@input.matched[2..-1]}&quot;)].pack(&quot;U&quot;))
		else
			false
		end
	end

	def parse_number
		@input.scan(/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\b/) and
		AST.new(eval(@input.matched))
	end

	def parse_keyword
		@input.scan(/\b(?:true|false|null)\b/) and
		AST.new(eval(@input.matched.sub(&quot;null&quot;,&quot;nil&quot;)))
	end

	def trim_space
		@input.scan(/\s+/)
	end

	def error(message)
			raise &quot;#{message}:  #{@input.peek(@input.string.length)}&quot;
	end
end
</pre>
<p>For an in depth explanation of the individual portions in this code, refer to the <a title="Ruby Quiz - Parsing JSON" href="http://rubyquiz.com/quiz155.html">RubyQuiz Site</a> . One way that I&#8217;ve tested this code is by accessing the Twitter search api. The following snippet will print the 20 most recent #neumont tweets:</p>
<pre class="brush: ruby">
require &#039;jsonParser&#039;
require &#039;cgi&#039;
require &#039;open-uri&#039;
url = &quot;http://search.twitter.com/search.json?q=%23neumont&quot;
parser = JSONParser.new
open(url) {|html| @output = html.read}
obj = parser.parse(@output)
obj[&quot;results&quot;].each {|e| puts CGI.unescapeHTML(e[&quot;text&quot;])}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/json-parsing-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Photography Friday X: Onward and Upward</title>
		<link>http://blog.jstaten.com/photography-friday-onward-upward/</link>
		<comments>http://blog.jstaten.com/photography-friday-onward-upward/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 18:49:07 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Photography]]></category>
		<category><![CDATA[Climbing]]></category>
		<category><![CDATA[Photography Friday]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=161</guid>
		<description><![CDATA[
Life seems to come at you with a seemingly endless number of footholds and slick spots.  Similar to climbing, you can plan, predict, and prepare, but what matters most is how you exectue.
]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><a class="flickr-image alignnone" title="Onward and Upward" rel="flickr-mgr" href="http://www.flickr.com/photos/33716748@N06/3332940319/"><img class="flickr-large aligncenter" src="http://farm4.static.flickr.com/3326/3332940319_6671c321cf.jpg" alt="Onward and Upward" /></a></p>
<p style="text-align: center;">Life seems to come at you with a seemingly endless number of footholds and slick spots.  Similar to climbing, you can plan, predict, and prepare, but what matters most is how you exectue.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/photography-friday-onward-upward/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>StatenUtil: Bringing a bit of Ruby looping into C#</title>
		<link>http://blog.jstaten.com/statenutil-ruby-into-csharp/</link>
		<comments>http://blog.jstaten.com/statenutil-ruby-into-csharp/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 05:22:49 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Looping]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[StatenUtil]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=152</guid>
		<description><![CDATA[For anyone who&#8217;s new to the blog, StatenUtil is a personal C# utility library. Consisting mainly of extension methods, its main objective is to simplify frequently used operations. This edition includes adding some Ruby-like looping methods into C#. I understand that Func and Action objects aren&#8217;t a real replacement for blocks. However, it&#8217;s nice to [...]]]></description>
			<content:encoded><![CDATA[<p>For anyone who&#8217;s new to the blog, <a href="/tag/statenutil" title="StatenUtil Tag">StatenUtil</a> is a personal C# utility library. Consisting mainly of extension methods, its main objective is to simplify frequently used operations. This edition includes adding some Ruby-like looping methods into C#. I understand that <em>Func</em> and <em>Action</em> objects aren&#8217;t a real replacement for blocks. However, it&#8217;s nice to have some features I miss when not using Ruby.</p>
<h2>Int32Extensions.cs</h2>
<pre class="brush: c#">
using System;

namespace StatenUtil
{
    public static class Int32Extensions
    {
        public static void Times(this int source, Action&lt;int&gt; action)
        {
            for (int i = 0; i &lt; source; i++)
            {
                action(i);
            }
        }
        public static void UpTo(this int source, int max, Action&lt;int&gt; action)
        {
            for (int i = source; i &lt;= max; i++)
            {
                action(i);
            }
        }
        public static void DownTo(this int source, int min, Action&lt;int&gt; action)
        {
            for (int i = source; i &gt;= min; i--)
            {
                action(i);
            }
        }
        public static int[] Range(this int source, int max)
        {
            int difference = max - source;
            if (difference &lt; 0) return new int[0];
            int[] ret = new int[difference + 1];
            for (int i = 0; i &lt;= difference; i++)
                ret[i] = source+i;
            return ret;
        }

    }
}
</pre>
<p>This class file revolves around adding functions to the <em>int</em> class. The <em>Times</em> method allows for a specific integer capturing lambda expression to be executed <em>source</em> times. For example, <em>6.Times(x =&gt; Console.WriteLine(x)) </em>would print lines from zero to 6.</p>
<p><em>UpTo</em> and <em>DownTo</em> are similar to the <em>Times</em> method. However, they loop over a range of integers rather than from zero. Compare these to Ruby&#8217;s <em>upto</em> and <em>downto</em> methods.</p>
<p><em>Range</em> is simply a way to create an array covering a range of integers. The source is the minimum value and max is the largest of the array.</p>
<h2>IEnumerableExtensions.cs</h2>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace StatenUtil
{
    public static class IEnumerableExtensions
    {
        public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; action)
        {
            IEnumerator&lt;T&gt; enumerator = source.GetEnumerator();
            while (enumerator.MoveNext())
                action(enumerator.Current);
        }
    }
}
</pre>
<p>Currently, this class file add inline ForEach capabilities to any generic IEnumerable object, similar to Ruby&#8217;s <em>each</em>. Although <em>List</em> has this capability, other IEnumerables like arrays do not.</p>
<p>That&#8217;s all for now. However, StatenUtil is a work in progress that&#8217;s always being amended. In each significant addition, the details will be shared once again.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/statenutil-ruby-into-csharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Photography Friday IX: Wells Fargo Bank Notes</title>
		<link>http://blog.jstaten.com/photography-friday-wells-fargo-notes/</link>
		<comments>http://blog.jstaten.com/photography-friday-wells-fargo-notes/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 18:47:45 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Photography]]></category>
		<category><![CDATA[Bank]]></category>
		<category><![CDATA[California]]></category>
		<category><![CDATA[Notes]]></category>
		<category><![CDATA[Papers]]></category>
		<category><![CDATA[Photography Friday]]></category>
		<category><![CDATA[Wells Fargo]]></category>

		<guid isPermaLink="false">http://blog.jstaten.com/?p=148</guid>
		<description><![CDATA[
These bank notes were recorded for the purpose of Wells Fargo many years ago when traveling Westward. I believe it&#8217;s just amazing to think about how far we have come since then and can hardly imagine where we&#8217;re headed. I&#8217;m sure the writers of this never expected anything like online banking, worldwide transactions, and billions [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><a class="flickr-image alignnone" title="Notes" rel="flickr-mgr" href="http://www.flickr.com/photos/33716748@N06/3144375047/"><img class="flickr-large aligncenter" src="http://farm4.static.flickr.com/3250/3144375047_7a8a4ac7f1.jpg" alt="Notes" /></a></p>
<p style="text-align: center;">These bank notes were recorded for the purpose of Wells Fargo many years ago when traveling Westward. I believe it&#8217;s just amazing to think about how far we have come since then and can hardly imagine where we&#8217;re headed. I&#8217;m sure the writers of this never expected anything like online banking, worldwide transactions, and billions of dollars under their control. It&#8217;s inspiring to know that where we are now in life does not represent what we will be always.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jstaten.com/photography-friday-wells-fargo-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
