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

<channel>
	<title>Michael De Wildt &#187; C#</title>
	<atom:link href="http://www.mikeyd.com.au/category/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mikeyd.com.au</link>
	<description>An uber nerd rambling about open source, PHP, Python and whatever I find interesting</description>
	<lastBuildDate>Wed, 04 Jan 2012 22:36:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Testing LINQ to SQL repositories with Rhino Mocks</title>
		<link>http://www.mikeyd.com.au/2009/10/13/testing-linq-to-sql-repositories-with-rhino-mocks/</link>
		<comments>http://www.mikeyd.com.au/2009/10/13/testing-linq-to-sql-repositories-with-rhino-mocks/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 00:26:46 +0000</pubDate>
		<dc:creator>Mikey</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Rhino Mocks]]></category>

		<guid isPermaLink="false">http://www.mikeyd.com.au/?p=57</guid>
		<description><![CDATA[Today I was writing some unit tests for a repository based on the Nerd Dinner example of a LNIQ to SQL class repository. I had a Customer table in the database that had a auto increment identification column. I needed to Mock the standard LINQ to SQL functionality where the newly assigned ID is set [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was writing some unit tests for a repository based on the <a href="http://nerddinner.codeplex.com/">Nerd Dinner</a> example of a LNIQ to SQL class repository. I had a Customer table in the database that had a auto increment identification column. I needed to Mock the standard LINQ to SQL functionality where the newly assigned ID is set when the SubmitChanges method has been called and the row is committed to the database.</p>
<p>This is easy to do by Mocking my CustomerRepository interface and using Rhino Mocks Callback method.</p>
<p>Based on the <a href="http://nerddinner.codeplex.com/">Nerd Dinner</a> example I have a customer repository interface below.</p>
<pre class="brush:csharp">public interface ICustomerRepository
{
    IQueryable GetAllCustomers();
    Customer GetCustomr(int id);
    void Add(Customer customer);
    void Delete(Customer customer);
    void Save();
}</pre>
<p>To Mock this interface I have used a <a href="http://aabs.wordpress.com/2007/11/21/a-generic-class-factory-for-c-30/">generic class factory</a> developed by a colleague of mine that can dispense a Mock object into my customer controller with ease.</p>
<pre class="brush:csharp">public TestCustomerController()
{
    _customerRepository = _mock.StrictMock();
    //Set up the class factory to dispense the mock objects
    GenericClassFactory.Dispenser = o =&gt; _customerRepository;
    _controller = new CustomerIdentityController();
}
</pre>
<p>Inside my controller I use the generic class factory to dispense, by default, real object or, if the dispenser is set, my mock object. This is done using the code below.</p>
<pre class="brush:csharp">ICustomerRepository _customerRepository = GenericClassFactory.Get()</pre>
<p>Finally I wrote my test method using Rhino Mocks. The create customer method creates a new customer object and adds it using the LINQ to SQL add method. I use the Rhino Mocks call back method to get and instance of the new client that was created by my CustomerController. After the client is added the client controller and LINQ to SQL verifies that there are no errors, which allows me to commit the new record using my repositories save method. This method uses the Callback method to to mimic the LINQ to SQL functionality by assigning a customer ID to the to the customer object which is then returned by my controller.</p>
<pre class="brush:csharp">
[TestMethod]
public void CreateCustomer_ValidData_ID_Expected()
{
    Customer customer = null;
    _customerRepository.Expect(o =&gt; o.Add(Arg.Is.NotNull))
                       .Callback((Customer c) =&gt;
                                      {
                                          customer = c;
                                          return true;
                                      });
    _customerRepository.Expect(o =&gt; o.Save())
                       .Callback(() =&gt;
                                      {
                                          customer.ID = 1;
                                          return true;
                                      });
    _mock.ReplayAll();
    var customerId = _controller.CreateCustomer("FirstName", "Surname");
    Assert.AreEqual(1, customerId);
}
</pre>
<p>This is nothing new but is a great way of mocking a method that does more then just return a value.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikeyd.com.au/2009/10/13/testing-linq-to-sql-repositories-with-rhino-mocks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Custom Helper &#8211; A HttpRequest extension method</title>
		<link>http://www.mikeyd.com.au/2009/08/31/asp-net-mvc-httprequest-helper/</link>
		<comments>http://www.mikeyd.com.au/2009/08/31/asp-net-mvc-httprequest-helper/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 06:54:04 +0000</pubDate>
		<dc:creator>Mikey</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.mikeyd.com.au/?p=46</guid>
		<description><![CDATA[Recently I ran into an issue using JQuery’s AJAX library and ASP.NET MVC. Refer to my last post about using JQuery’s AJAX with ASP.NET MVC. After deploying a solution to my web server I had a major issue where my JQuery $.post method was not working and was not giving me any errors. I immediately [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I ran into an issue using JQuery’s AJAX library and ASP.NET MVC. Refer to my <a href="http://www.mikeyd.com.au/?p=39">last post</a> about using JQuery’s AJAX with ASP.NET MVC.</p>
<p>After deploying a solution to my web server I had a major issue where my JQuery $.post method was not working and was not giving me any errors. I immediately thought that there was an error in my server settings or something other then my code because I had no issues in my development environment.</p>
<p>It turned out to be an issue with routing! In my development environment the application was installed under the root directory (‘\’) where as on my server it was installed under a subfolder of the root directory (For example: ‘\test\’) thus the value I coded inside my $.post method was incorrect when deployed to my server.</p>
<p>In order to make it easy for me to deploy to any environment without changing my JQuery method each time I created this simple extension method for the HttpRequest class.</p>
<pre class="brush:csharp">public static class HttpRequestHelper
{
    public static string AppendServerPath(this HttpRequest request, string path)
    {
        return request.ApplicationPath.EndsWith("/")
                   ? request.ApplicationPath + path
                   : request.ApplicationPath + "/" + path;
    }
}</pre>
<p>So now inside my JQuery method all I have to do is call this method and append the exact path I wish to invoke.\</p>
<pre class="brush:javascript">$.post("&lt;%=Request.AppendServerPath("Test/Controller/DoSomething") %&gt;", null, doSomeThing());</pre>
<p>This also worked well inside my Site.Master where I ran into similar issues linking images, style sheets, JavaScript files, etc.</p>
<p>Wherever there is a link in my code I now call this extension method and know it will deploy almost everywhere.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikeyd.com.au/2009/08/31/asp-net-mvc-httprequest-helper/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dynamically Populate a Select/Drop Down List using ASP.NET MVC, JQuery and Json</title>
		<link>http://www.mikeyd.com.au/2009/08/22/dynamically-populate-a-selectdrop-down-list-using-aspnet-mvc-jquery-and-json/</link>
		<comments>http://www.mikeyd.com.au/2009/08/22/dynamically-populate-a-selectdrop-down-list-using-aspnet-mvc-jquery-and-json/#comments</comments>
		<pubDate>Sat, 22 Aug 2009 07:10:13 +0000</pubDate>
		<dc:creator>Mikey</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Json]]></category>

		<guid isPermaLink="false">http://www.mikeyd.com.au/?p=39</guid>
		<description><![CDATA[It has been a while since my last blog due to me being flat out at work during the week and snowboarding on the weekends! Today the weather is terrible up in the alps and I managed to catch the flu so it was a good time to catch up on some personal projects. I [...]]]></description>
			<content:encoded><![CDATA[<p>It has been a while since my last blog due to me being flat out at work during the week and snowboarding on the weekends!</p>
<p>Today the weather is terrible up in the alps and I managed to catch the flu so it was a good time to catch up on some personal projects. I was working on an ASP.NET MVC website for my sister and decided to use AJAX to populate a select list based on a selection in another select list. The ASP.NET MVC framework and JQuery makes it very easy to use AJAX to do this.</p>
<p>This is nothing new but very powerful if you want to create a nice fluent forms user interface. For the most part the process was very easy. However I ran into an issue where JQuery was treating the Json returned from the server as a string instead of an object. Thus making if difficult to retrieve the data I wanted. I will explain how I got around this later in the post.</p>
<p>The first thing you need to do create the server side method. This is very easy using ASP.NET MVC! Of course you would probably get your data from a database of some sort, however this is just a nice way of showing how its done. The method below gets a list of Foo objects based on the FooId parameter using LINQ&#8217;s Where method.</p>
<pre class="brush:csharp">public class Foo
{
    public int FooId { get; set; }
    public string Name { get; set; }
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetFooList(int FooId)
{
    var fooList = new List();
    fooList.Add(new Foo { FooId = 1, Name = "One" } );
    fooList.Add(new Foo { FooId = 1, Name = "Two" } );
    fooList.Add(new Foo { FooId = 2, Name = "Three" });
    fooList.Add(new Foo { FooId = 2, Name = "Four" });
    return Json(fooList.Where(foo =&gt; foo.FooId == FooId).ToList());
}</pre>
<p>Now for the client side code. On my page I have two select lists. One is a list of Id’s and the other is a list of names. When a user selects an id from the first select list the second is populated with the names relating to that id. The lists can be created easily using using the ASP.NET MVC Helpers or writing the HTML yourself.</p>
<pre class="brush:xml">
<select id="IdList">
<option>1</option>
<option>2</option>
</select>
</pre>
<p>Finally the JQuery code in order to add the functionality to the page. JQuery makes it easy to execute server side methods and receive Json. The code below binds the AJAX post method to the change event of the IdList select list. The post function has three variables; The sever method to execute, the parameters to pass as Json and the function to execute with the data returned from the server. You can either execute a named or a anonymous function. I chose the latter because I am not doing too much inside the function.</p>
<pre class="brush:javascript"> $(function() {
        $("#IdList").change(function() {
            $.getJSON("/Controller/GetFooList", { FooId: $("#IdList").val() },
            function(fooList) {
                $("#NameList").empty();
                $.each(fooList, function(i, foo) {
                    $("#NameList").append(""+ foo.Name+ "");
                });
            });
        });
    });</pre>
<p>The biggest issue I came across was, originally, the FooList Json was being represented as a string therefore the JQuery each method was iterating through each character of the string rather then each object. After a bit reading I came across the JSON.parse method in the JQuery library. This method parses the string to Json which means that the JQuery each method functions as I expected.</p>
<p>There we have it. Like I said nothing new here but interesting never the less.</p>
<p>The only thing I don’t like about this code is the append method in my JQuery. Surly there is a better way of adding options to a select element?</p>
<p><strong>UPDATE 120/01/2011:  I have recently realised that using eval is bad! This is because it will evaluate ANY javascript returned from the server. Therefore there is a chance that someone with malicious intent could insert their own javascript into your request. So instead you should use jQuery&#8217;s getJSON method instead. The above code has been modified to use this function.</strong></p>
<p></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikeyd.com.au/2009/08/22/dynamically-populate-a-selectdrop-down-list-using-aspnet-mvc-jquery-and-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# string to object model using method attributes, reflection, anonymous types and LINQ.</title>
		<link>http://www.mikeyd.com.au/2009/05/19/c-string-to-object-model-using-method-attributes-reflection-anonymous-types-and-linq/</link>
		<comments>http://www.mikeyd.com.au/2009/05/19/c-string-to-object-model-using-method-attributes-reflection-anonymous-types-and-linq/#comments</comments>
		<pubDate>Tue, 19 May 2009 04:37:48 +0000</pubDate>
		<dc:creator>Mikey</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Anonymous Types]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Method Attributes]]></category>
		<category><![CDATA[object model]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://www.mikeyd.com.au/?p=15</guid>
		<description><![CDATA[I came across a problem the other day where I needed to create a solution that accessed an old school string based transactional interface. The problem was a relatively simple one: Convert an object model into a string in order to be sent Receive a string and build an object model The solution had to [...]]]></description>
			<content:encoded><![CDATA[<p>I came across a problem the other day where I needed to create a solution that accessed an old school string based transactional interface. The problem was a relatively simple one:</p>
<ol>
<li>Convert an object model into a string in order to be sent</li>
<li>Receive a string and build an object model</li>
</ol>
<p>The solution had to be robust because the transactional interface was very nit picky and the strings had to be 100% formed or it will throw all sorts of errors. It also had to be extensible allowing for more transactions to be added in the future.</p>
<p>I’m sure there are many ways to solve this problem however I wanted to make it scalable and declarative. So, along with a few pointers from my colleague <a href="http://aabs.wordpress.com/">Andrew</a>, I decided to utilise method attributes, reflection and LINQ to solve the problem.</p>
<p>The following code is development code to prove a concept. Use at own risk <img src='http://www.mikeyd.com.au/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><strong>Building a string from an object model</strong></p>
<p>Firstly I had to define my data transfer class, the restrictions imposed on its properties and the  wrapper template required by the transactional interface.</p>
<p>In the following example my class Foo contains the property Bar which as to be a maximum of 20 characters and must conform to the Regex displayed. Foo is also to be wrapped in the input template of max size 20.</p>
<pre class="brush:csharp">[InputTemplate("Template Bar='{Bar}' End", 20)]
public class Foo
{
    [InputStringField(20, "^[a-zA-Z0-9]+$")]
    public string Bar { get; set; }
}</pre>
<p>Using this approach I can define as may data transfer classes that are needed by my application and declare how they are to represented to the transactional interface.</p>
<p>The next step was to create a string builder that will convert the a data transfer object into a string based on the restrictions defined in the attributes of its class. I did this by reflecting the attributes and applying them to the properties of the data transfer object.</p>
<pre class="brush:csharp">private static string BuildInputString(this T obj)
{
  var attrbutes = obj.GetType()
                     .GetCustomAttributes(typeof (InputTemplateAttribute), true)
                     .Cast();
    if (attrbutes.Count() != 1)
        throw new InvalidOperationException();

    string template = attrbutes.First().Template;

    foreach (var property in
      from prop in obj.GetType().GetProperties()
      let attributes = prop.GetCustomAttributes(typeof(InputStringFieldAttribute), true)
                           .Cast()
      where attributes.Count() &gt; 0
      select new
             {
               PropertyInfo = prop,
               Attribute = attributes.First()
             })
    {
      if (property.PropertyInfo.GetValue(obj, null) == null)
        throw new NullReferenceException()
      string value = property.PropertyInfo.GetValue(obj, null).ToString();
      string name = property.PropertyInfo.Name;
      int length = property.Attribute.Length;

      if (value.Length &gt; length)
        throw new InvalidOperationException();

      var regex = new Regex(property.Attribute.Format);
      if (!regex.IsMatch(value))
        throw new InvalidOperationException();

      template = template.Replace("{" + name + "}", value.PadRight(length).ToUpper());
    }
    return template;
}</pre>
<p>The method above utilises anonymous types and reflection so it can be applied to any object that’s class definition uses the attributes defined above.</p>
<p>The string is then constructed using a helper function.</p>
<pre class="brush:csharp">Foo foo = new Foo { Bar = "bar " };
string someString = foo.BuildInputString();</pre>
<p><strong>Building an object model from a string</strong></p>
<p>Now we have to go back the other way. The transaction interface returns a string that will always conform to a set standard. So the output is declared in the same way that the input class was declared. For many of my data transfer scenarios the same class was used for input and output therefore the Input and Output attributes can be added to the same class and properties.</p>
<pre class="brush:csharp">[InputTemplate("Template Bar='{Bar}' at Date='{Bar1}' End")]
[OutputTemplate(5)]
public class Foo
{
    [InputStringField(20, "^[a-zA-Z0-9]+$")]
    [OutputStringField(5, 0)]
    public string Bar { get; set; }    

    [OutputStringField(5, 1)]
    public string Bar1 { get; set; }
}</pre>
<p>Now, just like the string builder above, we construct our Foo object list based on the constraints imposed on the properties in its attributes. In this example, the output string will always contain a counter of length 5 and will contain two ordered properties of max 5 characters.</p>
<pre class="brush:csharp">public static IEnumerable BuildList(this string outputString) where T : new()
{
    if (string.IsNullOrEmpty(outputString))
        throw new InvalidOperationException();

    var obj = new T();
    var classAttrs = obj.GetType()
                        .GetCustomAttributes(typeof (OutputTemplateAttribute), true)
                        .Cast();

    if (classAttrs.Count() != 1)
        throw new InvalidOperationException();

    int count = int.Parse(outputString.Substring(0, classAttrs.First().CounterLength));

    for (int i = 0; i &lt; count; i++)
    {
        obj = new T();
        foreach (var property in
            from prop in obj.GetType().GetProperties()
                let attributes =
                    prop.GetCustomAttributes(typeof (OutputStringFieldAttribute), true)
                        .Cast()
                        .OrderBy(a =&gt; a.Ordinal)
                where attributes.Count() &gt; 0
                select new
                        {
                            PropertyInfo = prop,
                            Attribute = attributes.First()
                        })
        {
            string value = outputString.Substring(0, property.Attribute.Length);
            outputString = outputString.Remove(0, property.Attribute.Length);
            property.PropertyInfo.SetValue(obj, value.Trim(), null);
        }
        yield return obj;
    }
}
var fooList = someString.BuildList();</pre>
<p><strong>Method Attributes</strong></p>
<p>I don’t think there is a need to show the attributes here as they are very simple. What you see in the constructor is what is stored in the properties of the attribute.</p>
<p><strong>Conclusion</strong></p>
<p>The solution above is a simplified version of what I am intending to develop, however it does show the concept of what I am doing. The solution is scalable and extensible because it can add more data transfer classes for different transactions as needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikeyd.com.au/2009/05/19/c-string-to-object-model-using-method-attributes-reflection-anonymous-types-and-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

