<?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>Fairway Technologies</title>
	<atom:link href="http://www.fairwaytech.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fairwaytech.com</link>
	<description>Technology Consulting and Software Development</description>
	<lastBuildDate>Sat, 18 May 2013 00:32:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<item>
		<title>iOS Unit Testing With OCMock</title>
		<link>http://www.fairwaytech.com/2013/05/ios-unit-testing-with-ocmock/</link>
		<comments>http://www.fairwaytech.com/2013/05/ios-unit-testing-with-ocmock/#comments</comments>
		<pubDate>Sat, 18 May 2013 00:32:33 +0000</pubDate>
		<dc:creator>Greg White</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Least Common Multiple]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OCMock]]></category>
		<category><![CDATA[OCUnit]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[xCode]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=4195</guid>
		<description><![CDATA[Mock objects are an important driver of test driven development (TDD). They give developers the ability to craft unit tests involving complex objects without risking the possible complications inherent in [...]]]></description>
			<content:encoded><![CDATA[<p>Mock objects are an important driver of test driven development (TDD). They give developers the ability to craft unit tests involving complex objects without risking the possible complications inherent in instantiating those objects. They can be used to test code’s behavior when things go wrong, when infrequent things happen, or when a complex system of objects needs to be in a specific state. They are good for testing methods that return non-deterministic results (like the current time), and standing in for objects you plan to build, but haven’t built yet. In short, they’re useful, but xCode does not support them out of the box.</p>
<p>Apple’s xCode ships with OCUnit which is “a faithful implementation of xUnit patterns for Objective-C”[<a href="http://alexvollmer.com/posts/2010/06/01/cocoas-broken-tests/">Vollmer</a>]. Though useful for testing (it provides the various combinations of assertions covering nulls, exceptions, true, false, and equality), it lacks the capability to produce mock objects. That’s where <a href="http://ocmock.org/">OCMock</a> comes in. OCMock is a library that works with Objective-c and provides methods that allow you to employ mock objects throughout your own applications. In this post, I’ll be walking through the setup of OCMock in Apple’s xCode environment and running through a few basic use cases for the OCMock library.</p>
<p><span id="more-4195"></span></p>
<p style="text-align: left;" align="center"> <strong><span style="text-decoration: underline;">Setting up OCMock</span></strong></p>
<p><strong> </strong>Before we begin, here’s a rundown of my current environment:</p>
<ul>
<li>xCode Version: 4.6.2</li>
<li>OCMock Version: 2.1</li>
<li>Objective-C Version: 2.0</li>
</ul>
<div>Setting up OCMock is a subject that should be (and is) the subject of numerous blog posts. A good guide for setup purposes can be found on the OCMock website under the iOS tab at <a href="http://ocmock.org/ios/">http://ocmock.org/ios/</a>. There are a couple of gotcha’s in the setup that I ran into when I attempted it myself. First, xCode does not show all of the options for a project to you by default; you have to select the “show all files” button in the top left corner of the project screen to see them. The second is that, as <a href="http://ocmock.org/ios/">Mulle Kybernetik</a> puts it:</div>
<p><em>“The linker tries to be clever and only includes those symbols that it thinks are used. It gets this wrong with Objective-C categories, and we need to tell it that (a) we&#8217;re dealing with Objective-C and (b) that it should load all symbols for the OCMock library.”</em></p>
<p><em></em>If the path to your files is not clearly defined in at least 3(!) places, you will get errors and nothing will work correctly. A third gotcha; the default selection for the project settings is the main project. Your tests (and OCMock) are their own project by default. You have to switch the target from the main project to the test project otherwise you’ll have the right files referenced by the wrong project (and still get errors when you try to use OCMock to test).</p>
<p>OCMock comes in two flavors. There is a framework version and a static library version. In order to do iOS development, you’ll need to use the static library version NOT the framework. The difference between the static library and the framework is how they are deployed with the project. Static libraries are compiled and their binaries are integrated with the application binaries on a compile. Frameworks are linked to and then referenced. Since there’s not a great way to make sure that the end users will have a particular version of a framework installed (without installers/unnecessary complications), static libraries are the best choice for iOS development.</p>
<p style="text-align: left;"> <strong><span style="text-decoration: underline;">Setting up Unit Tests</span></strong></p>
<p align="center"><strong></strong><strong> </strong></p>
<p align="center"> <a href="http://www.fairwaytech.com/wp-content/uploads/2013/05/AppInSimulator.png"><img class="alignnone size-medium wp-image-4197" title="AppInSimulator" src="http://www.fairwaytech.com/wp-content/uploads/2013/05/AppInSimulator-159x300.png" alt="LCM app running in simulator" width="159" height="300" /></a></p>
<p> For this example, I coded up an app that will find the lowest number divisible by all integers from 1 to some arbitrary positive integer supplied by the user (restricted by the maximum value of an int). I originally solved this problem in Java with goals of efficiency and compactness. To facilitate this example, I ported it over to Objective-C following TDD practices. Here’ the original function and my thoughts on breaking it down into testable pieces:</p>
<pre class="brush:java">    public String solve(int limit) {
        int[] numbers = new int[limit+1];
        BigInteger result = new BigInteger("1");
        for(int i = 0; i &lt; numbers.length; i++) {
            numbers[i] = i;
        }
        for(int i = 2; i &lt; numbers.length; i++) {
            if(i &gt; 1) {
                result = result.multiply(new BigInteger(String.valueOf(numbers[i])));
                for(int j = i+1; j &lt; numbers.length; j++) { 
                    if(numbers[j] &gt; 1 &amp;&amp; numbers[j] % numbers[i] == 0) { 
                        numbers[j] /= numbers[i];
                    }
                }
            }
        }
        return result.toString();</pre>
<p style="text-align: left;" align="center"><strong><span style="text-decoration: underline;">The Setup Phase</span></strong></p>
<p>Here’s the first piece I considered:</p>
<pre class="brush:java">public String solve(int limit) {
        int[] numbers = new int[limit+1];
        BigInteger result = new BigInteger("1");
        for(int i = 0; i &lt; numbers.length; i++) {
            numbers[i] = i;
        }</pre>
<p>These operations result in assignment and population (note the actual size of the array is limit+1). In the context of an iOS app, the limit would be a return from user input and would define the dimensions of the numbers array. The array population can be broken out of this section and into its own function to facilitate separate unit testing. In xCode, I wrote the following tests for this piece:</p>
<pre class="brush:cpp">-(void)testInputFieldToNumberConversion {
    [[[inputField stub] andReturn:@"3"] text];
    [[[beController userLimit]expect] intValue];
    [beController convertStringFieldToInt:inputField];
    STAssertEquals(3, [[beController userLimit] intValue], @"User field to Number conversion error");
}</pre>
<p>And</p>
<pre class="brush:cpp">-(void)testArrayPopulation {
    NSNumber* testNumber = [[NSNumber alloc]initWithInt:3];
    NSMutableArray* testArray = [beController populateArrayToLimit:testNumber];
    STAssertTrue(4 == [testArray count], @"Array Population error");
}</pre>
<p>In the two tests above I used two testing libraries. The STAssertTrue in the testArrayPopulation method is a member of Apple’s built-in OCUnit testing library. Above it, in the testInputFieldToNumberConversion method, I have made use of mock objects and stubs provided by OCMock to simulate an input field object and its text method. I also used the expect method provided by OCMock. The expect method will fail if the specified function is not called on its target object. It is a good way to make sure that program control is moving in the direction you designed it to. I have included the tested Objective-C methods below:</p>
<pre class="brush:cpp">//
//  BEViewController.m
//  BlogExample
//
//  Created by Fairway on 5/3/13.
//  Copyright (c) 2013 Fairway. All rights reserved.
//

#import "BEViewController.h"

@interface BEViewController ()

@end

@implementation BEViewController

@synthesize userRange;
@synthesize userLimit;
@synthesize inputField;
@synthesize displayLabel;
@synthesize calculateButton;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self) {
        userLimit = [[NSNumber alloc]init];
        userRange = [[NSMutableArray alloc]init];
    }
    return self;
}</pre>
<p>This is the setup of the Object variables ^</p>
<pre class="brush:cpp">-(NSNumber*)convertStringFieldToInt:(UITextField *)textField {
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    userLimit = [f numberFromString: [textField text]];
    return userLimit;
}</pre>
<p>Here is the conversion tested by testInputFieldToNumberConversion ^</p>
<pre class="brush:cpp">-(NSMutableArray*)populateArrayToLimit:(NSNumber *)limit {
    int top = [limit intValue];
    for(int i = 0; i &lt;= top; i++) {
        [userRange addObject:[NSNumber numberWithInt:i]];
    }
    return userRange;
}</pre>
<p>And here is the population piece tested by testArrayPopulation ^</p>
<p>The next chunk is the meat of the algorithm and required a bit more detangling to make it testable.</p>
<p style="text-align: left;" align="center"> <strong><span style="text-decoration: underline;">The Algorithm</span></strong></p>
<pre class="brush:java">for(int i = 2; i &lt; numbers.length; i++) {
            if(i &gt; 1) {
                result = result.multiply(new BigInteger(String.valueOf(numbers[i])));
                for(int j = i+1; j &lt; numbers.length; j++) { 
                    if(numbers[j] &gt; 1 &amp;&amp; numbers[j] % numbers[i] == 0) { 
                        numbers[j] /= numbers[i];
                    }
                }
            }
        }
        return result.toString();</pre>
<p>This algorithm executes by dividing all eligible higher factors by the current value of the array as referenced by the loop variable (by eligible I mean division produces a whole number). It takes the array produced by the assignment and population phase above it as input. Starting at index 2 (all indexes contain their corresponding integer 2 =&gt; 2 and so on), it will attempt to divide all subsequent items in the array by the current number. At each loop execution, the current number advances. If it’s (the new current number) greater than 1 (Meaning a new factor), the program will enter the loop, multiply the answer by the current number, and then attempt to divide the remaining array members by the current number once more. Here’s an example of what the array will look like over successive passes:</p>
<p><a href="http://www.fairwaytech.com/wp-content/uploads/2013/05/AlgorithmChart.png"><img class="wp-image-4200 aligncenter" title="AlgorithmChart" src="http://www.fairwaytech.com/wp-content/uploads/2013/05/AlgorithmChart.png" alt="Algorithm Chart" width="873" height="440" /></a></p>
<p>(Note that ‘1’ values are not shown in the result array, but they do exist. Every composite number that does not introduce a new prime reduces to a one and is skipped when the algorithm reaches it)</p>
<p>As you can see from the diagram above, the original array is transformed from its initial form (populated with all the numbers 1…limit) into a state where it only contains prime factors common amongst all numbers in the original array. By multiplying each member, the resulting prime factor array will solve the problem by producing the least common multiple. That separation of operations between the production and aggregation of the prime array is a perfect place to separate out functionality for testing.</p>
<p style="text-align: left;" align="center"> <strong><span style="text-decoration: underline;">Separation of Concerns</span></strong></p>
<p>The aggregation and production phases of the algorithm provide a convenient breaking point from which separation of the current function is possible. I did so when I wrote the Objective-C code for this algorithm:</p>
<pre class="brush:cpp">-(void)testArrayAggregation {
    NSMutableArray* testArray = [[NSMutableArray alloc]init];
    for(int i = 0; i &lt; 4; i++) {
        [testArray addObject:[[NSNumber alloc]initWithInt:i]];
    }
    NSNumber* testNumber = [beController aggregateArray:testArray];
    STAssertEquals(6, [testNumber intValue], @"Array Aggregation error");
}</pre>
<p>The above testArrayAggregation function tests to make sure that the aggregateArray function in the BEViewController is working correctly.</p>
<pre class="brush:cpp">-(NSNumber*)aggregateArray:(NSMutableArray *)array {
    int ans = 1;
    for (int i = 2; i &lt; [array count]; i++) {
        ans *= [array[i] intValue];
    }
    return [[NSNumber alloc]initWithInt:ans];
}</pre>
<p>With the aggregation and setup pieces tested, the only remaining major component is the reduction piece that produces the array containing the answers. This piece took a bit more hardcoding to get correct, but tests the most common case the function will encounter:</p>
<pre class="brush:cpp">-(void)testPrimeFactorGeneration {
    NSMutableArray* testArray = [[NSMutableArray alloc]init];
    for(int i = 0; i &lt;= 10; i++) {
        [testArray addObject:[[NSNumber alloc]initWithInt:i]];
    }
    testArray[4] = [[NSNumber alloc]initWithInt:2];
    testArray[6] = [[NSNumber alloc]initWithInt:1];
    testArray[8] = [[NSNumber alloc]initWithInt:2];
    testArray[9] = [[NSNumber alloc]initWithInt:3];
    testArray[10] = [[NSNumber alloc]initWithInt:1];
    NSMutableArray* temp = [beController determinePrimeFactors: [beController populateArrayToLimit:[[NSNumber alloc]initWithInt:10]]];
    STAssertTrue([temp isEqualToArray:testArray], @"Prime factor generation method not working");
}</pre>
<p>And its corresponding function:</p>
<pre class="brush:cpp">-(NSMutableArray*)determinePrimeFactors:(NSMutableArray *)list {
    for(int i = 2; i &lt; [list count]; i++) {
        if(i &gt; 1 ) {
            for(int j = i+1; j &lt; [list count]; j++) {
                if([list[j] intValue] &gt; 1 &amp;&amp; [list[j] intValue] % [list[i] intValue] == 0) {
                    int x = [list[j] intValue] / [list[i] intValue];
                    NSNumber *n = [[NSNumber alloc]initWithInt:x];
                    list[j] = n;
                }
            }
        }
    }
    return list;
}</pre>
<p>This leaves only two pieces; showAnser and restoreBeginningState. The showAnswer function’s only purpose is to execute the other class functions in the correct order to produce the answer. In essence, it&#8217;s a type of miniature integration test; with all of the pieces tested individually, showAnswer tests their cooperation as a unit:</p>
<pre class="brush:cpp">-(void)showAnswer:(id)sender {
    userLimit = [self convertStringFieldToInt: inputField];
    userRange = [self populateArrayToLimit: userLimit];
    NSNumber* number = [self aggregateArray: [self determinePrimeFactors: userRange]];
    if([number intValue] == 1) {
        number = 0;
    }
    [displayLabel setText:[number stringValue]];
    [self restoreBeginningState];
}</pre>
<p>Its tests run through all program logic (with the exception of restoreBeginningState):</p>
<pre class="brush:cpp">-(void)testThatAnswerThreeIsSix {
    [[[inputField stub] andReturn: @"3"] text];
    [[[beController displayLabel] expect] setText: @"6"];
    [beController showAnswer: inputField];
    [displayLabel verify];
    [inputField verify];
}

-(void)testThatAnswerTenIs2520 {
    [[[inputField stub] andReturn: @"10"] text];
    [[[beController displayLabel] expect] setText: @"2520"];
    [beController showAnswer: inputField];
    [displayLabel verify];
    [inputField verify];
}

-(void)testThatAnswerTwentyIs232792560 {
    [[[inputField stub] andReturn: @"20"] text];
    [[[beController displayLabel] expect] setText: @"232792560"];
    [beController showAnswer: inputField];
    [displayLabel verify];
    [inputField verify];
}</pre>
<p>Last (but not least), I wrote a function that restores the Object variables to their original states. This allows the user to enter a new value after a calculation is performed and receive a valid answer (otherwise old data would produce bad answers):</p>
<pre class="brush:cpp">-(void)restoreBeginningState {
    userRange = [[NSMutableArray alloc]init];
    userLimit = [[NSNumber alloc]init];
}</pre>
<p>And its test:</p>
<pre class="brush:cpp">-(void)testRestorationToOriginalState {
    [[beController userRange] addObject:[[NSNumber alloc]initWithInt:3]];
    [beController setUserLimit:[[NSNumber alloc]initWithInt:3]];
    STAssertTrue([[beController userRange]count] == 1, @"restoreBeginningState test error");
    STAssertTrue([[beController userLimit] integerValue] == 3,  @"restoreBeginningState test error");
    [beController restoreBeginningState];
    STAssertTrue([[beController userRange]count] == 0, @"userRange has not been cleared in restoreToOriginalState");
    STAssertTrue([beController userLimit] == nil,  @"userLimit has not been cleared in restoreBeginningState");
}</pre>
<p>Executing the program in the simulator yields a working app that correctly produces the LCM of the range defined by user input. That correctness was definitely helped along by TDD and OCMock. Objective-C is not a language that I know well. In unfamiliar domains (where you’re more likely to introduce bugs) TDD becomes even more crucial than normal. In addition to its utility in helping you work through the use cases, interfaces, and method signatures in advance, TDD can also help you figure out how language constructs and libraries work in a new language. If you think you’re producing a primitive int and your test case bombs out with a pointer, you know the class of issue you’re dealing with before you attempt to integrate your functionality into your application. TDD practices are great for isolating and anticipating problems before they happen and can make programming in any language much more productive.</p>
<p style="text-align: left;" align="center"> <strong><span style="text-decoration: underline;">Resources</span></strong></p>
<p>If you’re interested on learning more about this topic, here are some related resources:</p>
<p><a href="http://ocmock.org/">http://ocmock.org/</a> &#8211; Location of OCMock. Tutorials, install info, api</p>
<p><a href="http://alexvollmer.com/posts/2010/06/28/making-fun-of-things-with-ocmock/">http://alexvollmer.com/posts/2010/06/28/making-fun-of-things-with-ocmock/</a> &#8211; Insightful blog about using OCMock</p>
<p><a href="http://alexvollmer.com/posts/2010/06/01/cocoas-broken-tests/">http://alexvollmer.com/posts/2010/06/01/cocoas-broken-tests/</a> &#8211; More from Vollmer focusing on unit testing</p>
<p><a href="http://www.amazon.com/Test-Driven-iOS-Development-Developers-Library/dp/0321774183/ref=sr_1_1?ie=UTF8&amp;qid=1368203991&amp;sr=8-1&amp;keywords=tdd+objective+c">http://www.amazon.com/Test-Driven-iOS-Development-Developers-Library/dp/0321774183/ref=sr_1_1?ie=UTF8&amp;qid=1368203991&amp;sr=8-1&amp;keywords=tdd+objective+c</a> – A book specifically about TDD in Objective-C (And it’s not bad!)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/05/ios-unit-testing-with-ocmock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why Stakeholders Need To Be Involved In Scrum</title>
		<link>http://www.fairwaytech.com/2013/04/why-stakeholders-need-to-be-involved-in-scrum/</link>
		<comments>http://www.fairwaytech.com/2013/04/why-stakeholders-need-to-be-involved-in-scrum/#comments</comments>
		<pubDate>Fri, 19 Apr 2013 02:00:10 +0000</pubDate>
		<dc:creator>Greg White</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[Scrum]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=4179</guid>
		<description><![CDATA[Scrum is a procedure for producing software. It allows companies to respond quickly to change and leverage the unique skillsets of their employees to rapidly develop good solutions. While Scrum [...]]]></description>
			<content:encoded><![CDATA[<p>Scrum is a procedure for producing software. It allows companies to respond quickly to change and leverage the unique skillsets of their employees to rapidly develop good solutions. While Scrum is designed to achieve agility, its implementation requires a high degree of rigidity to execute well. In this sense it is a process like any other; a set of rules that allows everyone involved to know what happens next, who they should go to with problems, and how to communicate effectively.</p>
<p><span id="more-4179"></span></p>
<p>Companies who like the idea of being agile, but do not like the rigid process of Scrum, often cherry-pick their favorite parts out of the process and try to tack them on to whatever they’re already doing. When their projects grind to a halt and people point fingers, the process is often a convenient target. In that case it should be; writing good software is like baking. If you’re halfway through making lasagna and decide you’d like cake instead you don’t start tossing sugar on top of the cheese. The same is true in software development. It’s better to have good lasagna or good cake then a sticky inedible mess. If you’re going to follow a recipe for software development you have to fully commit to it, all of it, and support it as an organization to be successful.</p>
<p>One of the most common pitfalls for companies trying to implement an agile Scrum process is a lack of stakeholder participation. Having a customer advocate (or the customer themselves) in the room during the project is a critical driver at the heart of Scrum. When the stakeholders are too busy or disinterested to participate, the vision of what the customer wants and the actuality of what the programmers build begins to diverge.</p>
<p>The Scrum process is a collaborative one. It is built on the assumption that the stakeholders will be involved in the decisions driving the creative process. Requirements should not be thrown over the wall to the developers from the business side, or handled by the developers as needed.  Building a requirements backlog should be a process in which the business and technical tribes come together to develop a shared understanding of the needs of the client. If the business side is involved and invested in advancing and informing the process of writing good software, then everyone benefits from reduced churn and improved forecasting clarity.</p>
<p>To succeed in the modern business environment, software companies have to stay agile to respond to evolving customer requirements. The traditional business segmentation that works with blueprints and assembly lines will not work with software development. Organizations need to truly buy into the agile tenant, “customer collaboration over contract negotiation” [Agile Manifesto, <a href="http://agilemanifesto.org/">http://agilemanifesto.org/</a>], and start allowing their customers to control the work done on their behalf.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/04/why-stakeholders-need-to-be-involved-in-scrum/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NuGet Config File Transformation Causes Duplicate Entries On Update</title>
		<link>http://www.fairwaytech.com/2013/03/nuget-config-file-transformation-causes-duplicate-entries-on-update/</link>
		<comments>http://www.fairwaytech.com/2013/03/nuget-config-file-transformation-causes-duplicate-entries-on-update/#comments</comments>
		<pubDate>Sat, 30 Mar 2013 02:14:44 +0000</pubDate>
		<dc:creator>Jeff Treuting</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Jeff Treuting]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=4134</guid>
		<description><![CDATA[Problem Overview First off NuGet is great.  It has made life easier for me as a developer, and now, as an author for the open source generic repository SharpRepository.  It [...]]]></description>
			<content:encoded><![CDATA[<h2>Problem Overview</h2>
<p>First off NuGet is great.  It has made life easier for me as a developer, and now, as an author for the open source generic repository <a href="https://github.com/SharpRepository/SharpRepository" target="_blank">SharpRepository</a>.  It provides a great distribution channel, especially for providing updates.</p>
<p>The NuGet packages for SharpRepository add configuration elements to your Web.Config or App.config to make your life easier and allow for a <a title="SharpRepository: Configuration" href="http://www.fairwaytech.com/2013/02/sharprepository-configuration/" target="_blank">configuration file way of setting up your repository</a>.  NuGet provides a very simple configuration file transformation process when installing or updating a package. (For more information on it <a href="http://docs.nuget.org/docs/creating-packages/configuration-file-and-source-code-transformations" target="_blank">check here</a>.) Basically it merges in your web.config.transform data into your web.config file adding the entries that don&#8217;t already exist.</p>
<p><span id="more-4134"></span></p>
<p>Here is the issue I came across recently.  The SharpRepository.Ef5Repository NuGet package includes the following web.config.transform file:</p>
<pre class="brush:xml">&lt;configuration&gt;
	&lt;sharpRepository&gt;
	  &lt;repositories&gt;
		 &lt;repository name="ef5Repository" connectionString="DefaultConnection" factory="SharpRepository.Ef5Repository.Ef5ConfigRepositoryFactory, SharpRepository.Ef5Repository" /&gt;
	  &lt;/repositories&gt;
	&lt;/sharpRepository&gt;
&lt;/configuration&gt;</pre>
<p>After doing the initial install of this package, NuGet will add the &lt;sharpRepository&gt; section close to the bottom of your Web.config file since it didn&#8217;t exist previously.  Then as you start your development, you realize that you are using a connection string named &#8220;MyConnectionString&#8221; (because you hate naming things apparently), so you do the logical thing and change the repository connectionString value in your Web.config file like so:</p>
<pre class="brush:xml">	&lt;sharpRepository&gt;
	  &lt;repositories&gt;
		 &lt;repository name="ef5Repository" connectionString="MyConnectionString" factory="SharpRepository.Ef5Repository.Ef5ConfigRepositoryFactory, SharpRepository.Ef5Repository" /&gt;
	  &lt;/repositories&gt;
	&lt;/sharpRepository&gt;</pre>
<p>Great, everything is working.  Then sometime down the road, you notice there is a brand new shiny version of SharpRepository.Ef5Repository available (due to new amazing features of course, no way there are any bugs to fix, not possible), so you update your package via NuGet and click run to start up your project, only to be shown an exception due to a duplicate key.  So what happened?</p>
<p>When NuGet runs the configuration file transformation it merges in the &lt;repository&gt; element again because the one from the package does not match the one that is in the Web.config file exactly due to the change of the connectionString value.  So the new file looks like this after the update:</p>
<pre class="brush:xml">	&lt;sharpRepository&gt;
	  &lt;repositories&gt;
		&lt;repository name="ef5Repository" connectionString="MyConnectionString" factory="SharpRepository.Ef5Repository.Ef5ConfigRepositoryFactory, SharpRepository.Ef5Repository" /&gt;
		&lt;repository name="ef5Repository" connectionString="DefaultConnection" factory="SharpRepository.Ef5Repository.Ef5ConfigRepositoryFactory, SharpRepository.Ef5Repository" /&gt;
	  &lt;/repositories&gt;
	&lt;/sharpRepository&gt;</pre>
<h2>So what can we do about it?</h2>
<p>In order to get this fixed, I needed to hack together a workaround until NuGet does an upgrade to their XML transformations and maybe includes Visual Studio Web.config Transforms, which are more powerful.  I took advantage of the fact that during installation and upgrade of packages you can provide an Install.ps1 PowerShell script that will run after the files have been copied and the configuration file transformation is done.</p>
<p>Time to break out my non-existent PowerShell skills and put together a script to fix the problem.  When the script is run we may or may not have a duplicate element, but if we do, it will get added below the one that was edited and should be kept.  I also wanted to be able to have this work against both Web.config and App.config files since either one could have the problem depending on the type of project being used.</p>
<p>Each SharpRepository package that touches the configuration files has a version of this script, so my goal was to make it so that the majority of the code is the same from script to script and we just needed to setup which element to look for and clean up.  Here is what I came up with.</p>
<pre class="brush:plain"># Install.ps1
param($installPath, $toolsPath, $package, $project)

# Path Settings (since this script is used across multiple packages we only need to change these settings in each usually)
$parentPath = "configuration/sharpRepository/repositories"
$keyPath = "repository[@name='ef5Repository']"

Function Clean-Dups-In-Config-File ($localPath, $parentNodePath, $nodePath)
{
	$xml = New-Object xml

	# load config as XML
	$xml.Load($localPath)

	# select parent node to call the RemoveChild on later
	$parentNode = $xml.SelectSingleNode($parentNodePath)

	# select the nodes
	$nodes = $xml.SelectNodes($parentNodePath + "/" + $nodePath)

	if ($nodes.Count -gt 0) 
	{
		# if there are multiple repository names with the same key, then the NuGet update added the additional ones and they will be last
		#	so loop through those nodes, excluding the first one, and remove them
		$i = 1;
		while ($i -lt $nodes.Count) 
		{
			$parentNode.RemoveChild($nodes.Item($i))
			$i++
		}

		# save the config file
		$xml.Save($localPath)
	}
}

# find the Web.config/App.config file if there is one
$items = $project.ProjectItems | where {$_.Name -eq "Web.config" -or $_.Name -eq "App.config" }
Foreach ($item in $items)
{
	# find its path on the file system
	$localPath = $item.Properties | where {$_.Name -eq "LocalPath"}

	# clean duplicate entries
	Clean-Dups-In-Config-File $localPath.Value $parentPath $keyPath
}</pre>
<p>This works great so far and cleans up the duplicates.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/03/nuget-config-file-transformation-causes-duplicate-entries-on-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load Testing with Locust on Windows</title>
		<link>http://www.fairwaytech.com/2013/03/load-testing-with-locust-on-windows/</link>
		<comments>http://www.fairwaytech.com/2013/03/load-testing-with-locust-on-windows/#comments</comments>
		<pubDate>Thu, 21 Mar 2013 02:55:03 +0000</pubDate>
		<dc:creator>Noah Heldman</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Noah Heldman]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=3590</guid>
		<description><![CDATA[The Point Locust is, if you believe the hype, the HOLY GRAIL of obscure Python-based distributed load testing tools with real-time web-based statistics: I’ve tried a few different times to [...]]]></description>
			<content:encoded><![CDATA[<h1></h1>
<h1></h1>
<h1>The Point</h1>
<p><a href="http://locust.io" target="_blank">Locust</a> is, if you believe the hype, the HOLY GRAIL of obscure Python-based distributed load testing tools with real-time web-based statistics:</p>
<p><img src="http://locust.io/static/img/screenshot.png" alt="Screenshot of Locust UI" /></p>
<p>I’ve tried a few different times to get Locust up and running on Windows, and every time something has gone wrong enough for me to be demotivated and quit.  ‘Cause, y’know, I’m a quitter.</p>
<p><span style="color: #9b00d3;">Until now!</span></p>
<p>My goal is to help YOU get Locust setup on your Windows machine in the “recommended” way, so you can bring down your server by flooding it with thousands of requests too.  There is something awe-some about having the power to bring down a server remotely just by typing “100,000” in the “How many users?” input box…</p>
<p><span id="more-3590"></span></p>
<h1></h1>
<h1>Prerequisites</h1>
<p>As is the case with most Python and Ruby stuff on Windows, there are a bunch of things you need installed and properly configured to successfully run Locust.  In this post, I document all of the things <em>I</em> needed to make it work.  This is <em>after</em> having tried a bunch of things that didn’t work, uninstalling everything, and starting from scratch.</p>
<h2>Python 2.7</h2>
<p>Well, hey!  Locust is just a big ol’ Python script, so you need Python.  Let’s just save you a bunch of frustrating hours right now, and tell you that <strong>everything we’ll be installing is 32-bit</strong>.  That’s because Locust doesn’t support 64-bit Python!  You wouldn’t know that by searching the Locust site, docs, or even searching for “locust python 64 bit” in Google.  But trust me.  32-bit is the way to go.</p>
<ul>
<li>Go to <a href="http://www.python.org/download">http://www.python.org/download</a></li>
<li>Look for the latest Python 2.7.x Windows Installer link:</li>
<li><a href="http://www.fairwaytech.com/wp-content/uploads/2013/01/image.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.fairwaytech.com/wp-content/uploads/2013/01/image_thumb.png" alt="image" width="609" height="90" border="0" /></a></li>
<li>Download that and run the installer
<ul>
<li>You can keep all of the defaults, but take note of where it installs (probably <span style="font-family: Consolas;">C:\Python27</span>)</li>
</ul>
</li>
<li>Once complete, make sure your PATH system environment variable is set correctly (something like this):</li>
<li><img src="http://www.aaronstannard.com/image.axd?picture=image_45.png" alt="" /></li>
<li>Open a command prompt and enter “python” and see what you see.  Hopefully this:</li>
<li><a href="http://www.fairwaytech.com/wp-content/uploads/2013/01/image1.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.fairwaytech.com/wp-content/uploads/2013/01/image_thumb1.png" alt="image" width="606" height="69" border="0" /></a></li>
</ul>
<h2>curl</h2>
<p>When you need to download stuff from the command line, you need <a href="http://curl.haxx.se" target="_blank">curl</a>.  You can just download the standalone .exe (32-bit!), or you can install the full cygwin suite, if you want.</p>
<p>I got it for free when I installed git.  You may already have it!  Just type “curl” at a command prompt, and you’ll know.</p>
<h2>Python Tools</h2>
<p>Next, you’ll need either <a href="http://pypi.python.org/pypi/setuptools" target="_blank">setuptools</a> or <a href="http://pypi.python.org/pypi/distribute" target="_blank">distribute</a>.  For my money, distribute is WAY better.  Or wait, was it setuptools that was better?  Oh, right, it doesn’t matter.</p>
<p>Here is the fast and easy way to install distribute:</p>
<ul>
<ul>
<li>In a command prompt, navigate to your Python install directory (<span style="font-family: Consolas;">C:\Python27</span>)</li>
<li>Type this to download and run (install) distribute:</li>
</ul>
</ul>
<pre class="brush: bash; gutter: false;">&gt; curl http://python-distribute.org/distribute_setup.py | python</pre>
<h2>easy_install</h2>
<p>Many people like <a href="http://pypi.python.org/pypi/pip" target="_blank">pip</a> better than <a href="http://packages.python.org/distribute/easy_install.html" target="_blank">easy_install</a>, either because of its adorable name, or because it actually displays useful error messages, but easy_install can run Windows executables, and pip can’t.  So we need it.  Even more hilarious is the fact that we will be installing pip in the next step!  BWAAAHAHAHAHAHAAAA!!!!</p>
<p>What’s really cool is that we already have easy_install, since we installed distribute in the last step!</p>
<h2>virtualenv (and pip!)</h2>
<p><a href="http://www.virtualenv.org/en/latest/" target="_blank">Virtualenv</a> lets you create isolated Python environments, so there’s less of a chance you’ll screw something up.  Don’t worry, you’ll probably screw something else up, because now all of your dependencies have to be available <em>within the isolated environment</em>, but some cool kids told me that virtualenv was the bomb, so I believed them.  Run these from the same command prompt location we were using before and simmer in the coolness:</p>
<pre class="brush: bash; gutter: false;">&gt; curl -O https://raw.github.com/pypa/virtualenv/master/virtualenv.py

&gt; python virtualenv.py dev

&gt; . dev/Scripts/activate</pre>
<p>The first line grabs the Python script and drops it in the current directory.  The second line creates a new virtual Python environment called “dev” (YOU can call it whatevs you want!).  The last line “activates”, or switches you over to, the new virtual environment.</p>
<p><img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT9mw0otjptETgGMcYZ8teloY-yzddJT93Db9pkw1rnYn0Nvn4G" alt="" /></p>
<p><em>“Aw, look, it’s Pip!”</em></p>
<h2>gevent</h2>
<p>If you believe what their website says, <a href="http://pypi.python.org/pypi/gevent" target="_blank">gevent</a> is a network library that provides a fast event loop.  This is why Locust can simulate eleventy billion users on a single machine.  Or twevinity quillion if you have two machines.</p>
<p>I say, get it!  Here’s how.  From the same command prompt, run:</p>
<pre class="brush: bash; gutter: false;">&gt; easy_install http://pypi.python.org/packages/2.7/g/gevent/gevent-0.13.8.win32-py2.7.exe</pre>
<h2>greenlets</h2>
<p><a href="http://pypi.python.org/pypi/greenlet" target="_blank">greenlets</a> are wee micro-threads, or coroutines, that do little cute stuff like “tasks”.  They are best friends with gevent.</p>
<p>Do this from Senor El Command Prompt if you want them, which you do, if you ever want locust to work:</p>
<pre class="brush: bash; gutter: false;">&gt; easy_install http://pypi.python.org/packages/2.7/g/greenlet/greenlet-0.4.0.win32-py2.7.exe</pre>
<h1>Locust Installation</h1>
<p>Finally!  We can install locust, which is furiously simple now that everything else is in place.  We could do this with easy_install, but we installed pip, and haven’t used it, so let’s do that instead:</p>
<pre class="brush: bash; gutter: false;">&gt; pip install locustio</pre>
<h3></h3>
<h2>Distributed Test Army!</h2>
<p>If you’ll be running this on more than one machine, you will need to install <span style="font-family: Consolas;">pyzmq</span> and <span style="font-family: Consolas;">gevent-zeromq</span> for insano-distributed magic-action.  It should be as easy as running <span style="font-family: Consolas;">pip install</span> for those two, but since it’s Windows, it’s not!</p>
<h3>pyzmq</h3>
<p>For pyzmq, download the 32-bit version for Python 2.7 from here:  <a title="https://github.com/zeromq/pyzmq/downloads" href="https://github.com/zeromq/pyzmq/downloads">https://github.com/zeromq/pyzmq/downloads</a>.</p>
<p><a href="http://www.fairwaytech.com/wp-content/uploads/2013/01/image2.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.fairwaytech.com/wp-content/uploads/2013/01/image_thumb2.png" alt="image" width="584" height="91" border="0" /></a></p>
<p>When you install it, be sure to select a different Python installation!  You need the one you created in virtualenv, so for me, that’s:</p>
<p><span style="font-family: Consolas;">C:\Python27\dev</span></p>
<p>It only needs the root of the installation (there’s a python.exe under that dev directory, and that’s what gets run).</p>
<h3>gevent-zeromq</h3>
<p>We just need this guy so <span style="font-family: Consolas;">gevent</span> can talk to <span style="font-family: Consolas;">pyzmq</span>.  Luckily, you just need this:</p>
<pre class="brush: py; gutter: false;">&gt; pip install gevent-zeromq</pre>
<h1>Locust Scripting</h1>
<p>If I was 100% accurate in my instructions above, you should have a working install of Locust!  Applause!  Now it’s time to make it do stuff.</p>
<p>The one part of the Locust documentation that’s passable is the <a href="http://docs.locust.io/en/latest/" target="_blank">scripting stuff</a>.  Although they only have a couple examples, they list all the stuff the API can do.  I’m afraid you’re in for some trial and error if you need to do some of the more advanced stuff, however.</p>
<p>Here’s a script I wrote, which I’ve commented up For Help’s Sake:</p>
<pre class="brush: py; gutter: false;"># magick.py

from locust import Locust, TaskSet, task

class WebsiteTasks(TaskSet):
    # Do this before tasks start
    def on_start(self):
        # Set any required HTTP Headers
        self.client.headers['Accept-Language'] = "en-US,en;q=0.8"

        # POST some form data
        self.client.post("/home/login", {
            "UserName": "nheldman",
            "Password": "password"
        })

    # Run this task with weighting 2 (twice as much as the one below)
    @task(2)
    def index(self):
        # GET the home page
        self.client.get("/")

    @task(1)
    def contact(self):
        # GET the Contact page
        self.client.get("/contact/")

class WebsiteUser(Locust):
    # What task class are we running?  (the one above!)
    task_set = WebsiteTasks

    # What's the minimum wait time between requests?
    min_wait = 1000

    # And the maximum?
    max_wait = 3000

    # What is our base host for testing (prepended to GETs/POSTs above)?
    host = "http://localhost:64175"</pre>
<p>So, the scripting language is a world of its own, but it’s small, and elegant.</p>
<p>Now that I have a script, I can run it like so from Kommand Prompt:</p>
<pre class="brush: py; gutter: false;">&gt; locust -f magick.py</pre>
<p>If that works, the hard part is over.  It should show you now that it’s running:</p>
<p><a href="http://www.fairwaytech.com/wp-content/uploads/2013/01/image3.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.fairwaytech.com/wp-content/uploads/2013/01/image_thumb3.png" alt="image" width="680" height="69" border="0" /></a></p>
<h1>Running Locust</h1>
<p>Okay, fantastic!  Now we have a web monitor running!</p>
<p>Here’s the part where you’re going to think I’m really stupid.  I didn’t know what to do next.  Okay, I’ve done Rails development, node.js development, and worked with plenty of environments that ran a lightweight web server on some port.</p>
<p>So why didn’t I just open a browser and visit <a href="http://localhost:8089" class="broken_link">http://localhost:8089</a>?</p>
<p>Because it didn’t say I needed to ANYWHERE IN THE LOCUST DOCUMENTATION!</p>
<p>Yes, it should have been obvious to me.  Really obvious.</p>
<p>And yet, because I was following other instructions on the Locust site, I guess I expected it to say “open a browser”.  It didn’t, so I didn’t.</p>
<p>But then I did.</p>
<p><a href="http://www.fairwaytech.com/wp-content/uploads/2013/01/image4.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.fairwaytech.com/wp-content/uploads/2013/01/image_thumb4.png" alt="image" width="833" height="432" border="0" /></a></p>
<p>Imagine my joy when I saw this screen.  It’s the first time I realized how I can tell Locust how many users to simulate, and how fast they should ramp up.</p>
<p>Why is it the first time?  Because it’s not ANYWHERE IN THE LOCUST DOCUMENTATION, NOR IS THERE A SCREENSHOT!</p>
<p>So, now it’s easy.  Just type in “100,000” in the first box (yes, ALWAYS start with 100,000 users), and something smaller in the second box, and click “Start Swarming”.</p>
<p>In reality, I started with 100 users, with a hatch rate of 2.</p>
<p>Behold!  You will see the magical-ness that is this:</p>
<p><a href="http://www.fairwaytech.com/wp-content/uploads/2013/01/image5.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.fairwaytech.com/wp-content/uploads/2013/01/image_thumb5.png" alt="image" width="848" height="320" border="0" /></a></p>
<h1>Interpreting Results</h1>
<p>In my example above, I have a comically high number of failures, and an even more comically low number of Requests per Second (RPS).</p>
<p>That’s because after all of this effort installing and configuring, I wanted a screenshot to represent my pain.  I promise it looks better when I write the script correctly.</p>
<p>The columns are mostly self-explanatory, but it’s worth noting that the Median, Average, Min, and Max represent the number of milliseconds it took for the page to load.</p>
<p>Yes, my page load times are abysmal.  Don’t forget to start your .NET site before running load tests against it, or page compiling will invalidate your results!</p>
<h1></h1>
<h1>Conclusion:  Maybe Don&#39t?</h1>
<p>Before finding Locust, I used <a href="http://testutils.org/multi-mechanize/" target="_blank">multi-mechanize</a>.  Locust looked shinier and modern-er, and it seemed like it would be much easier to get up and running on Windows.</p>
<p>Although it was just as much of a pain to install and configure, it definitely looks nicer than multi-mechanize, and can probably handle higher simulated load on a single machine.</p>
<p>Multi-mechanize has more charts out of the box, though they can be a bit confusing.</p>
<p>Locust is worth a shot, if what you see above appeals to you.</p>
<p>However, if you have Visual Studio Ultimate, use that.  It’s just better.  It has tightly integrated load testing tools that are flexible and provide meaningful feedback:</p>
<p><img src="http://i.msdn.microsoft.com/dynimg/IC588414.png" alt="Running load test graphs view" /></p>
<p>Thank you for riding on the Windows Pain Wheel with me.  Here’s hoping Locust documentation gets better, and maybe even shows some swell charts!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/03/load-testing-with-locust-on-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing A Custom LINQ Provider With Re-linq</title>
		<link>http://www.fairwaytech.com/2013/03/writing-a-custom-linq-provider-with-re-linq/</link>
		<comments>http://www.fairwaytech.com/2013/03/writing-a-custom-linq-provider-with-re-linq/#comments</comments>
		<pubDate>Tue, 12 Mar 2013 21:20:17 +0000</pubDate>
		<dc:creator>Jeff Treuting</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Jeff Treuting]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[re-linq]]></category>
		<category><![CDATA[SharpRepository]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=4043</guid>
		<description><![CDATA[Overview When LINQ was first released in 2007, I remember thinking that I wouldn&#8217;t use it and I was very happy using SQL for querying the database.  Well, once I [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>When LINQ was first released in 2007, I remember thinking that I wouldn&#8217;t use it and I was very happy using SQL for querying the database.  Well, once I started using it I really liked the ability to query lists, XML and SQL Server or other databases all using the same query syntax (for the most part at least).  When starting the generic repository idea that became <a title="SharpRepository" href="https://github.com/SharpRepository/SharpRepository">SharpRepository</a>, it became a logical choice to use.  If a backend had a LINQ provider then it became pretty simple to add it to our list of supported systems:  Entity Framework, InMemory, Cache, RavenDB, MongoDB, and db4o all had LINQ providers that we could find, whether they were developed by the same group or a third party provider.</p>
<p>At some point I started thinking, &#8220;how can we integrate with a technology that doesn&#8217;t have a LINQ provider?&#8221;  And the answer that came to me was, &#8220;I&#8217;ll just build one, it can&#8217;t be that hard right.&#8221;  Well, turns out, it&#8217;s not the easiest thing to do.  After doing some research, I came across this great article by Ayende Rahien about creating the LINQ provider for RavenDB and, as you can tell by the title, the difficulties which he faced: <a href="http://queue.acm.org/detail.cfm?id=2001564">The Pain of Implementing LINQ Providers</a>.  In it, he refers to the <a href="http://relinq.codeplex.com/">re-linq framework</a> which takes some of the pain out of the process.</p>
<p><span id="more-4043"></span></p>
<h2>What is re-linq?</h2>
<p>Instead of dealing with the IQueryable expression tree (which is a really big pain), re-linq gives you an abstract syntax tree that is similar to the original LINQ query.  In implementing a LINQ provider, you will be coding against their QueryModel object, which is easier to consume than the LINQ Expression, and re-linq will evaluate any expressions within the query when it can.  re-linq implements the <a href="http://www.oodesign.com/visitor-pattern.html">Visitor Pattern</a> and provides a set of visitors for you to implement for your transformation.</p>
<p>One of the downsides of re-linq is that there isn&#8217;t much documentation available.  The most helpful information I found was a Codeproject article, which goes through the process and provides sample code, for creating a NHibernate LINQ provider, which translated LINE into Hibernate Query Language (HQL) that is titled <a href="http://www.codeproject.com/Articles/42059/re-linq-ishing-the-Pain-Using-re-linq-to-Implement">re-linq|ishing the Pain: Using re-linq to Implement a Powerful LINQ Provider on the Example of NHibernate</a>.</p>
<h2>My attempt at writing a LINQ Provider</h2>
<p>One day I got the strange idea to create an ODataRepository for the <a href="https://github.com/SharpRepository/SharpRepository" target="_blank">SharpRepository project</a>.  Why?  Partly for fun, partly to see if I could, and partly because it could actually come in handy with WebAPI allowing you to easily provide for OData querying.  (It also didn&#8217;t hurt that the <a href="http://www.odata.org/documentation/uri-conventions" target="_blank">OData URI Coneventions</a> are pretty simple and can only support a limited subset of LINQ syntax making it easier to implement.)  So while I could create an HttpClient object, query &#8220;http://somewebsite.net/Products?$filter=Category eq &#8216;Electronics&#8217;&#8221;, get the response and use JSON.NET to translate it to my object models, wouldn&#8217;t it be cool to be able to do this instead:</p>
<pre class="brush:csharp">var repos = new ODataRepository&lt;Product&gt;("http://somewebsite.net/");
var products = repos.FindAll(x =&gt; x.Category == "Electronics");</pre>
<p>My first attempt took me down the path of writing my own visitor class that accepts an Expression.  I got a very simple POC working but quickly realized that expanding it to handle more advanced situations was going to be very tough.  And that is when I ran across re-linq and decided to scrap my initial design and give re-linq a try.</p>
<p>While I am not done with creating this LINQ to OData provider yet, I have plugged away at it off and on for a little while and have made some good progress.  But mostly I have enjoyed the challenge of learning something new and giving it a shot. You can see the full code on the odata branch of SharpRepository on GitHub.  All of the LINQ related code is located <a href="https://github.com/SharpRepository/SharpRepository/tree/odata/SharpRepository.ODataRepository/Linq">here</a>.</p>
<h2>Some code</h2>
<p>I won&#8217;t try to go through all the code in here but will point out a few things that will hopefully give a little overview of what it is like to write a LINQ provider using re-linq.  Please keep in mind that this code is in development and not a final product (in other words, be nice!).  I&#8217;ve based the basic structure of the code on the Codeproject article mentioned above and tweaked it for my needs, which really helped getting me going.</p>
<p>When parsing the syntax tree provided by re-linq, you will want to build up an object yourself that better represents the parts of your final query language.  After the tree parsing and visiting is all done, you will use this class to actually build the final query, in my case the OData querystring.  Here is the class I&#8217;m using for this purpose:</p>
<pre class="brush:csharp">    public class QueryPartsAggregator
    {
        public QueryPartsAggregator()
        {
            FromParts = new List&lt;string&gt;();
            WhereParts = new List&lt;string&gt;();
        }

        public string SelectPart { get; set; }
        public List&lt;string&gt; FromParts { get; set; }
        public List&lt;string&gt; WhereParts { get; set; }
        public string OrderBy { get; set; }
        public int? Take { get; set; }
        public int? Skip { get; set; }
        public bool OrderByIsDescending { get; set; }
        public bool ReturnCount = false;

        public void AddFromPart(IQuerySource querySource)
        {
            FromParts.Add(querySource.ItemName);
        }

        public void AddWherePart(string formatString, params object[] args)
        {
            WhereParts.Add(string.Format(formatString, args));
        }

        public void AddOrderByPart(string orderBy, bool isDescending)
        {
            OrderBy = orderBy;
            OrderByIsDescending = isDescending;
        }
    }</pre>
<p>When I need to build the actual OData querystring to perform the query this object maps nicely as you can see in the code below that handles this part:</p>
<pre class="brush:csharp">            if (_queryParts.ReturnCount)
            {
                querystring += "/$count";
            }

            querystring += "?$format=json&amp;";

            if (_queryParts.Take.HasValue)
                querystring += "$top=" + _queryParts.Take.Value + "&amp;";

            if (_queryParts.Skip.HasValue)
                querystring += "$skip=" + _queryParts.Skip.Value + "&amp;";

            if (!String.IsNullOrEmpty(_queryParts.OrderBy))
                querystring += "$orderby=" + _queryParts.OrderBy + "&amp;";

            var filter = SeparatedStringBuilder.Build(" and ", _queryParts.WhereParts);
            if (!String.IsNullOrEmpty(filter))
                querystring += "$filter=" + filter + "&amp;";

            if (!String.IsNullOrEmpty(_queryParts.SelectPart))
                querystring += "$select=" + _queryParts.SelectPart + "&amp;";</pre>
<p>In re-linq, you define an IQueryExecutor that is in charge of running the query based on the QueryModel that re-linq gives it.  Basically this class takes the QueryModel and kicks off the Visitor that goes through it all and builds the QueryPartsAggregator.  For the OData implementation we need to give it the base URL and the name of the collection we are querying.</p>
<pre class="brush:csharp">    // Called by re-linq when a query is to be executed.
    public class ODataQueryExecutor : IQueryExecutor
    {
        private readonly string _url;
        private readonly string _databaseName;

        public ODataQueryExecutor(string url, string databaseName)
        {
            _url = url;
            _databaseName = databaseName;
        }

        // Executes a query with a scalar result, i.e. a query that ends with a result operator such as Count, Sum, or Average.
        public T ExecuteScalar&lt;T&gt; (QueryModel queryModel)
        {
          return ExecuteCollection&lt;T&gt; (queryModel).Single();
        }

        // Executes a query with a single result object, i.e. a query that ends with a result operator such as First, Last, Single, Min, or Max.
        public T ExecuteSingle&lt;T&gt; (QueryModel queryModel, bool returnDefaultWhenEmpty)
        {
          return returnDefaultWhenEmpty ? ExecuteCollection&lt;T&gt; (queryModel).SingleOrDefault () : ExecuteCollection&lt;T&gt; (queryModel).Single ();
        }

        // Executes a query with a collection result.
        public IEnumerable&lt;T&gt; ExecuteCollection&lt;T&gt; (QueryModel queryModel)
        {
          var commandData = ODataApiGeneratorQueryModelVisitor.GenerateODataApiQuery(queryModel);
          var query = commandData.CreateQuery(_url, _databaseName);
          return query.Enumerable&lt;T&gt; ();
        }
    }</pre>
<p>At this point we have defined a class structure to represent our OData query, written the logic to take that structure and translate it into the OData querystring to use when making the HTTP request, and we&#8217;ve wired up what re-linq needs to kick off the process.  So the only thing left is to write the actual Visitor that parses the QueryModel.  As you can see from the code above, I&#8217;ve called this ODataApiGeneratorQueryModelVisitor (I like to keep my class names really short as you can see).  This class inherits from re-linq&#8217;s QueryModelVisitorBase and we override the methods as needed.  I won&#8217;t show the whole class but this is where we begin to populate the QueryPartsAggregator.</p>
<p>For example, there is a VisitResultOperator method which gets passed a ResultsOperatorBase class.  There are implementations of this base class for when the First() method is called, FirstResultOperator, or when Take() is called, TakeResultOperator, etc.  So when we override this method, for my OData needs it looks like this:</p>
<pre class="brush:csharp">        public override void VisitResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, int index)
        {
            if (resultOperator is FirstResultOperator)
            {
                _queryParts.Take = 1;
                return;
            }

            if (resultOperator is CountResultOperator || resultOperator is LongCountResultOperator)
            {
                _queryParts.ReturnCount = true;
                return;
            }

            if (resultOperator is TakeResultOperator)
            {
                var exp = ((TakeResultOperator)resultOperator).Count;

                if (exp.NodeType == ExpressionType.Constant)
                {
                    _queryParts.Take = (int)((ConstantExpression)exp).Value;
                }
                else
                {
                    throw new NotSupportedException("Currently not supporting methods or variables in the Skip or Take clause.");
                }

                return;
            }

            if (resultOperator is SkipResultOperator)
            {
                var exp = ((SkipResultOperator) resultOperator).Count;

                if (exp.NodeType == ExpressionType.Constant)
                {
                    _queryParts.Skip = (int)((ConstantExpression)exp).Value;
                }
                else
                {
                    throw new NotSupportedException("Currently not supporting methods or variables in the Skip or Take clause.");
                }

                return;
            }

            base.VisitResultOperator(resultOperator, queryModel, index);
        }</pre>
<p>The more complex parts are when Expressions need to be parsed, like in the case of the WhereClause, SelectClause or OrderByClause.  Re-linq provides a base visitor class for handling the expression parsing called ThrowingExpressionTreeVisitor.  As it&#8217;s name suggests, it throws an exception if some part of the LINQ syntax is not implemented in your visitor.  That way if you don&#8217;t implement the Contains() method, it will notify the user that it&#8217;s not implemented instead of just ignoring it and moving along as if it was being used.</p>
<p>The most straight-forward example of this is in parsing a BinaryExpression.  A BinaryExpression is made up of a Left and Right side and a NodeType.  This could be something like (x.Category == &#8220;Electronics&#8221;) where the Left side is the property x.Category, the Right side is the constant &#8220;Electronics&#8221; and the NodeType is Equal  It could also be something more complex like (x.Category == &#8220;Electronics&#8221; &amp;&amp; x.Status == true) where the Left side is the BinaryExpression (x.Category == &#8220;Electronics&#8221;), the Right side is the BinaryExpression (x.Status == true), and the NodeType is AndAlso.</p>
<p>Here is the override of the VisitBinaryExpression method that I&#8217;ve made for my OData implemenation:</p>
<pre class="brush:csharp">        protected override Expression VisitBinaryExpression (BinaryExpression expression)
        {
            _expression.Append("(");

            VisitExpression (expression.Left);

            // In production code, handle this via lookup tables.
            switch (expression.NodeType)
            {
                case ExpressionType.Equal:
                    _expression.Append (" eq ");
                    break;

                case ExpressionType.NotEqual:
                    _expression.Append (" ne ");
                    break;

                case ExpressionType.GreaterThan:
                    _expression.Append (" gt ");
                    break;

                case ExpressionType.GreaterThanOrEqual:
                    _expression.Append (" ge ");
                    break;

                case ExpressionType.LessThan:
                    _expression.Append (" lt ");
                    break;

                case ExpressionType.LessThanOrEqual:
                    _expression.Append (" le ");
                    break;

                case ExpressionType.AndAlso:
                case ExpressionType.And:
                    _expression.Append (" and ");
                    break;

                case ExpressionType.OrElse:
                case ExpressionType.Or:
                    _expression.Append (" or ");
                    break;

                case ExpressionType.Not:
                    _expression.Append(" not ");
                    break;

                case ExpressionType.Add:
                    _expression.Append (" add ");
                    break;

                case ExpressionType.Subtract:
                    _expression.Append (" sub ");
                    break;

                case ExpressionType.Multiply:
                    _expression.Append (" mul ");
                    break;

                case ExpressionType.Divide:
                    _expression.Append (" div ");
                    break;

                case ExpressionType.Modulo:
                    _expression.Append(" mod ");
                    break;

                default:
                    base.VisitBinaryExpression (expression);
                    break;
            }

            VisitExpression (expression.Right);

            _expression.Append(")");

            return expression;
        }</pre>
<p>As you can see, I am translating the ExpressionType into the proper OData syntax, == becomes &#8220;eq&#8221;, &gt;= becomes &#8220;ge&#8221;, etc.  The call to VisitExpression(expression.Left) and VisitExpression(expression.Right) are both very important.  They allow you to further parse the left side of the expression if it is a complex expression itself.  So in my example above where the Left side is (x.Category == &#8220;Electronics&#8221;), this call to VisitExpression then visits that left side and again has VisitBinaryExpression called allowing that original complex expression to be turned into the following OData query: &#8220;((Category eq &#8216;Electronics&#8217;) and (Status eq true))&#8221;.</p>
<p>Another example is being able to handle method calls like Contains(&#8220;text&#8221;),  StartsWith(&#8220;text&#8221;) or ToLower() and ToUpper().  To handle these we need to override the cleverly named VisitMethodCallExpression().  Here is the code that I wrote to handle those calls:</p>
<pre class="brush:csharp">        protected override Expression VisitMethodCallExpression (MethodCallExpression expression)
        {
            // In production code, handle this via method lookup tables.
            if (expression.Method.Name == "Contains")
            {
                _expression.Append("substringof(");
                VisitExpression(expression.Arguments[0]);
                _expression.Append(",");
                VisitExpression(expression.Object);
                _expression.Append(") eq true");
                return expression;
            }

            if (expression.Method.Name == "StartsWith")
            {
                _expression.Append("startswith(");
                VisitExpression(expression.Object);
                _expression.Append(",");
                VisitExpression(expression.Arguments[0]);
                _expression.Append(") eq true");
                return expression;
            }

            if (expression.Method.Name == "EndsWith")
            {
                _expression.Append("endswith(");
                VisitExpression(expression.Object);
                _expression.Append(",");
                VisitExpression(expression.Arguments[0]);
                _expression.Append(") eq true");
                return expression;
            }

            if (expression.Method.Name == "ToLower")
            {
                _expression.Append("tolower(");
                VisitExpression(expression.Object);
                _expression.Append(")");
                return expression;
            }
            if (expression.Method.Name == "ToUpper")
            {
                _expression.Append("toupper(");
                VisitExpression(expression.Object);
                _expression.Append(")");
                return expression;
            }

            return base.VisitMethodCallExpression (expression); // throws
        }</pre>
<h2>Conclusion</h2>
<p>Hopefully this has given you a glimpse into the crazy world of writing a LINQ provider.  As <a href="http://queue.acm.org/detail.cfm?id=2001564">Ayende Rahien writes</a>, &#8220;As a consumer of LINQ, I absolutely adore it, despite some of the issues just discussed. But <em>consuming </em>LINQ is the part that is all sunshine and roses. The task of <em>implementing</em> a LINQ provider is one of Herculean proportion and involves much use of fertilizer, sweat, and hard work.&#8221;  I think that does a great job of summing it up actually.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/03/writing-a-custom-linq-provider-with-re-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AutoMapper Profile Organization</title>
		<link>http://www.fairwaytech.com/2013/02/automapper-profile-organization/</link>
		<comments>http://www.fairwaytech.com/2013/02/automapper-profile-organization/#comments</comments>
		<pubDate>Thu, 28 Feb 2013 23:55:47 +0000</pubDate>
		<dc:creator>Jeff Treuting</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[AutoMapper]]></category>
		<category><![CDATA[Jeff Treuting]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=4048</guid>
		<description><![CDATA[AutoMapper is a great tool that I use on every project I&#8217;m involved in.  Primarily I use it to map my Model to my ViewModel when doing MVC development.  If [...]]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/AutoMapper/AutoMapper">AutoMapper</a> is a great tool that I use on every project I&#8217;m involved in.  Primarily I use it to map my Model to my ViewModel when doing MVC development.  If you haven&#8217;t used it before, I highly recommend checking it out.</p>
<p>If you&#8217;ve used AutoMapper before on a larger sized project, then you&#8217;ve probably seen how long and unruly your mapping definitions can become.  This file can grow and grow and just be a pain to deal with.  Luckily, AutoMapper provides a way to separate the definitions up into more logical units.  When doing MVC development, it might be natural to group all the Model/ViewModel mappings for a single controller, but you can break it up however makes logical sense to you.  You would do this by creating a custom Profile for each where you define your mappings for those entities.</p>
<p><span id="more-4048"></span></p>
<p>To make this a little easier, let&#8217;s define a base class for all of our custom Profiles to inherit from.  This also allows us to define any formatters that we want to use across all of our mappings. In this example, we have a date formatter that will take a DateTime or DateTime? and convert it to the standard string display we want for this site.</p>
<pre class="brush:csharp">    public abstract class BaseProfile : Profile
    {
        private readonly string _profileName;
        protected BaseProfile(string profileName)
        {
            _profileName = profileName;
        }

        public override string ProfileName
        {
            get { return _profileName; }
        }

        protected override void Configure()
        {
            ForSourceType&lt;DateTime&gt;().AddFormatter&lt;StandardDateTimeFormatter&gt;();
            ForSourceType&lt;DateTime?&gt;().AddFormatter&lt;StandardDateTimeFormatter&gt;();

            CreateMaps();
        }

        protected abstract void CreateMaps();
    }</pre>
<p>Now when we want to create a new profile for AutoMapper we can create it like so:</p>
<pre class="brush:csharp">    public class EventProfile : BaseProfile
    {
        public EventProfile() : base("EventProfile")
        {
        }

        protected override void CreateMaps()
        {
            CreateMap&lt;Event, IndexViewModel.Event&gt;();
            CreateMap&lt;Event, CreateViewModel&gt;();
            CreateMap&lt;Event, DetailsViewModel&gt;();
            CreateMap&lt;Event, EditViewModel&gt;();
            CreateMap&lt;Event, DeleteViewModel&gt;();
        }
    }</pre>
<p>This is a trivial example where the properties match perfectly from our Event Model to our ViewModels, but since that isn&#8217;t the point of this article I&#8217;m not going to worry about it.</p>
<p>Now you just have to tell AutoMapper to load these profiles.  If you have some bootstrapper code you would add it there, if not then Global.asax is a common place (I didn&#8217;t say the best place, but it is common and it works).  Here is how you would do that.  You need to call AddProfile&lt;&gt;() for each custom profile we create in order to register it.</p>
<pre class="brush:csharp">            Mapper.Initialize(x =&gt;
                {
                    x.ConstructServicesUsing(ObjectFactory.GetInstance);

                    x.AddProfile&lt;EventProfile&gt;();
                    x.AddProfile&lt;NewsProfile&gt;();
                    x.AddProfile&lt;UserProfile&gt;();
                    x.AddProfile&lt;OrderProfile&gt;();

                    // etc., etc.
                });

            Mapper.AssertConfigurationIsValid();</pre>
<p>This definitely helped break up a very large AutoMapper mappings file into smaller more easily managed pieces so I like where it is going.   But after using it for a bit I noticed that I kept forgetting to add my new Profile into this initialization part and that wasted time and was just kind of annoying.  So I decided to change it so I could be lazy and not have to worry about it.</p>
<p>Using reflection we can grab all of the classes that inherit from BaseProfile and then call AddProfile with each of them.  There may or may not be a way to grab all the types and call AddProfile&lt;T&gt;() with it like is done in the code above but I couldn&#8217;t figure out how to and quickly found another way so stopped trying.  There is also an AddProflile(Profile profile) method that accepts an instantiated class of type Profile (which BaseProfile inherits from).  So the only thing left to do is code it up:</p>
<pre class="brush:csharp">            Mapper.Initialize(x =&gt;
                {
                    x.ConstructServicesUsing(ObjectFactory.GetInstance);

                    // get all the AutoMapper Profile classes using reflection
                    var profileTypes = typeof(BaseProfile).Assembly.GetTypes().Where(type =&gt; type.IsSubclassOf(typeof(BaseProfile)));

                    foreach (var type in profileTypes)
                    {
                        x.AddProfile((BaseProfile)Activator.CreateInstance(type));
                    }
                });

            Mapper.AssertConfigurationIsValid();</pre>
<p>If you haven&#8217;t seen the Activator.CreateInstance() call before, it creates a new instance of that object type using the default constructor, and that works perfectly for you custom profiles since they don&#8217;t need any parameters.  There are also versions of Activator.CreateInstance where you can pass in your parameters in case you run into that scenario.</p>
<p>The result of this is a better organized structure for AutoMapper, especially on larger projects, while making as little work for us each time we need to add a new Profile.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/02/automapper-profile-organization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rails 3.2:  A Nested-Form Demo Part 4:  Switch to Targeting Computer!</title>
		<link>http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-4-switch-to-targeting-computer/</link>
		<comments>http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-4-switch-to-targeting-computer/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 19:23:17 +0000</pubDate>
		<dc:creator>Jeff Johnson</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery form validator]]></category>
		<category><![CDATA[Rails 3.2]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=3990</guid>
		<description><![CDATA[Overview Our heroes have fought their way through the Death Star&#8217;s fighter screen and can see the trench. As they enter the trench our pilots stabilize their deflector shields, preparing [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>Our heroes have fought their way through the Death Star&#8217;s fighter screen and can see the trench. As they enter the trench our pilots stabilize their deflector shields, preparing for the torrent of incoming turbolaser fire that will no doubt be coming their way.</p>
<p>In this post, we&#8217;ll take a look at adding some validation rules to our <code>Ship</code> and <code>Pilot</code> models. Hopefully, this effort will prevent our users from&#8230; err&#8230; having their way with our meek and rather naive Starfighter Recognition Guide. Our exhaust port is small, it&#8217;d be a shame to see it damaged by some ham-fisted users.</p>
<h2>Validation</h2>
<p>In our <a href="http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-3-were-starting-our-attack-run/">last post</a> we walked away with a fully-functioning Starfighter Recognition Guide that could save a <code>Ship</code> and any changes (create/update/delete) to its associated <code>Pilots</code>. Neat, right?</p>
<p>Before we run off and save everything willy-nilly, we should probably go about checking to make sure our users provided the data we need. Let&#8217;s add some data entry requirements to our application, shall we? Here&#8217;s what we need to do:</p>
<h3>Ship Requirements</h3>
<ul>
<li>A <code>Ship</code> must have a name.</li>
<li>A <code>Ship</code>&#8216;s name must be between 3 and 50 characters.</li>
<li>A <code>Ship</code> must have a crew.</li>
<li>A <code>Ship</code>must have between 1 and 5 crew members.
<ul>
<li>Arbitrary? Sure. But I figure if a <code>Ship</code> has more than 5 crew members, it&#8217;s probably a capital ship or on a scale that isn&#8217;t appropriate for a Starfighter Recognition Guide.</li>
</ul>
</li>
<li>A <code>Ship</code> must have a speed.</li>
<li>A <code>Ship</code>&#8216;s speed must be between 50 and 200&#8230; err&#8230; thingies per&#8230; umm&#8230; unit of time.
<ul>
<li>At the risk of having my Star Wars nerd card revoked, I&#8217;m not sure how the speed of a starfighter is measured. Yes, I looked it up. Nope, I couldn&#8217;t find anything conclusive.</li>
</ul>
</li>
</ul>
<p><span id="more-3990"></span></p>
<p>Shown below is the complete <code>Ship</code> model:<br />
<strong>app/models/ship.rb</strong></p>
<pre class="brush:ruby">class Ship &lt; ActiveRecord::Base   attr_accessible :armament, :crew, :has_astromech, :name, :speed   attr_accessible :pilots_attributes   has_many :pilots   accepts_nested_attributes_for :pilots,                                 :reject_if =&gt; :all_blank,
                                :allow_destroy =&gt; true

  validates :name,
            :presence =&gt; true,
            :uniqueness =&gt; { :case_sensitive =&gt; false },
            :length =&gt; { :maximum =&gt; 50, :minimum =&gt; 3 }

  validates :crew,
            :presence =&gt; true,
            :inclusion =&gt; { :in =&gt; 1..5, :message =&gt; "must be between 1 and 5" }

  validates :speed,
            :presence =&gt; true,
            :inclusion =&gt; { :in =&gt; 50..200, :message =&gt; "must be between 50 and 200" }
end</pre>
<p><strong>REFACTOR:</strong> The code above has changed a bit from the <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-nested-form-demo-part-1-all-wings-report-in/">first post</a>. Specifically, I had to change the <code>:reject_if</code> from <code>lambda { |attrs| attrs.all? { |key, value| value.blank? }</code> to <code>:all_blank</code>. After reading up on the documentation for <code><a href="http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for">accepts_nested_attributes_for</a></code>, the <code>Proc</code> I was using wasn&#8217;t good enough. Why, you ask? Well, our <code>Pilot</code> objects have their special <code>_destroy</code> field attached to them. The <code>_destroy</code> attribute can only be <code>true</code> or <code>false</code>, so it won&#8217;t ever be blank. The <code>Proc</code> above would allow us to save &#8220;empty&#8221; <code>Pilot</code> records (i.e. <code>Pilots</code> that have <code>null</code> <code>first_name</code>, <code>last_name</code> and <code>call_sign</code> values). The <code>:all_blank</code> symbol points to an ActiveRecord <code>Proc</code> that deals with this specific issue. Using <code>:reject_if =&gt; :all_blank</code> means that any <code>Pilot</code> record with no data will be ignored during the save, which is what we want. So&#8230; yay.</p>
<h3>Pilot Requirements</h3>
<ul>
<li>A <code>Pilot</code> must have a first name.</li>
<li>A <code>Pilot</code>&#8216;s first name cannot be longer than 50 characters.</li>
<li>A <code>Pilot</code> must have a last name.</li>
<li>A <code>Pilot</code>&#8216;s last name cannot be longer than 50 characters.</li>
<li>A <code>Pilot</code> must have a call sign.</li>
<li>A <code>Pilot</code>&#8216;s call sign must be unique. Case-sensitivity doesn&#8217;t matter here &#8211; &#8220;red 5&#8243; is the same as &#8220;Red 5&#8243;, which is the same as &#8220;RED 5&#8243;, etc.
<ul>
<li>To make sure this requirement is enforced, a unique index has been added to the <code>call_sign</code> column of the <code>pilots</code> table. You can see it on line 13 of the database migration script <a href="https://github.com/jeffjohnson9046/nested-form/blob/master/db/migrate/20121212193520_create_pilots.rb">here</a>.</li>
</ul>
</li>
</ul>
<p>Here&#8217;s what the <code>Pilot</code> model looks like with the validation in place:</p>
<p><strong>app/models/pilot.rb</strong></p>
<pre class="brush:ruby">class Pilot &lt; ActiveRecord::Base   belongs_to :ship   attr_accessible :call_sign, :first_name, :last_name, :ship_id   validates :first_name,             :presence =&gt; true,
            :length =&gt; { :maximum =&gt; 50 }

  validates :last_name,
            :presence =&gt; true,
            :length =&gt; { :maximum =&gt; 50 }

  validates :call_sign,
            :presence =&gt; true,
            :uniqueness =&gt; { :case_sensitive =&gt; false },
            :length =&gt; { :maximum =&gt; 50, :minimum =&gt; 5 }
end</pre>
<p>Okey doke &#8211; now that we have our validation in place, let&#8217;s see what happens when we click the &#8220;Add Ship&#8221; button and then click &#8220;Save&#8221; without entering anything:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Screen-Shot-2013-02-24-at-8.22.12-PM.png" alt="Save Ship error message" width="677" height="215" /></p>
<p>Not too shabby. Coincidentally, we&#8217;ll get the same error message if we:</p>
<ol>
<li>Click the &#8220;Add Ship&#8221; button on the home page to create a new <code>Ship</code>.</li>
<li>Click the &#8220;Add Pilot&#8221; button on the &#8220;New Ship&#8221; page to&#8230; y&#8217;know&#8230; Add a new <code>Pilot</code>. And stuff.</li>
<li>Click the &#8220;Add&#8221; button on the &#8220;Add a Pilot&#8221; modal form.</li>
<li>We&#8217;ll see a new row added to the &#8220;Pilots&#8221; section of the &#8220;Add Ship&#8221; form, and all the fields will be empty.</li>
</ol>
<p>How come we don&#8217;t get any errors about the <code>Pilot</code> with empty fields? That&#8217;s our <code>Ship</code>&#8216;s <code>:reject_if</code> in action. ActiveRecord saw that the <code>Pilot</code> was &#8220;empty&#8221;, so it discarded the record.</p>
<p>Allowing a user to click the &#8220;Add&#8221; button on our &#8220;Add a Pilot&#8221; modal form with willful and blatant disregard for our carefully-laid requirements is an affront to our humble application. It will not stand, I tell you! &#8216;Kay &#8211; maybe that was a little harsh, but you know what I mean. If we don&#8217;t stand up for our app, who will? If we need the user to give us data for a <code>Pilot</code>, we should do what we can to make sure they give it to us. Let&#8217;s add some client-side validation to our &#8220;Add a Pilot&#8221; modal form, so we can tell the user what&#8217;s missing when they click the &#8220;Add&#8221; button.</p>
<p>I poked around on Google for a bit to find a good solution for client-side validation utilities, and there&#8217;s no shortage of them. I landed on <a href="http://webtempest.com/easy-client-side-form-validation-for-rails-3-1/">this article</a>, which uses the <a href="https://github.com/victorjonsson/jQuery-Form-Validator">jQuery-Form-Validator</a>. The implementation looks pretty straightforward, and +1 for the article because he&#8217;s using Twitter Bootstrap too.</p>
<h2>The jQuery-Form-Validator</h2>
<p>Adding the <a href="https://github.com/victorjonsson/jQuery-Form-Validator">jQuery-Form-Validator</a> is pretty straightforward. Just get the <code>jquery-form-validator.min.js</code> file to your project. There aren&#8217;t any dependencies (outside of jQuery, of course).</p>
<p>Using the <a href="https://github.com/victorjonsson/jQuery-Form-Validator">jQuery-Form-Validator</a> is also pretty simple. All you have to do is add a <code>data-validation</code> attribute to the <code>element</code> you want to validate. You can visit the <a href="https://github.com/victorjonsson/jQuery-Form-Validator">GitHub</a> page to see all the validation options that are available (there are quite a few).</p>
<p>You can also customize the error message, by adding a <code>data-validation-error-msg</code> attribute with your customized error message. There are a host of other configuration options available, such as: the position of the error messages, the name of the <code>data-*</code> attribute, the CSS classes for your error messages, etc. You can see them on the GitHub page or on the <a href="http://victorjonsson.se/51/jquery-form-validator">jQuery-Form-Validator demo page</a>.</p>
<p>Shown below is the code for our <code>Pilot</code> modal form that implements the <a href="https://github.com/victorjonsson/jQuery-Form-Validator">jQuery-Form-Validator</a>:</p>
<p><strong>app/views/ships/_pilot_fields.html.erb:</strong></p>
<pre class="brush:ruby">&lt;div id="new-pilot-fields" class="modal fade" data-backdrop="static"&gt;
  &lt;div class="modal-header"&gt;
    &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt;
    &lt;h3&gt;Add a Pilot&lt;%= " to the #{ @ship.name } Pilot Roster" unless @ship.name.nil? %&gt;&lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="modal-body"&gt;
    &lt;fieldset&gt;
      &lt;div class="control-group"&gt;
        &lt;%= f.label(:first_name, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:first_name, :class =&gt; "input-xlarge field", :data =&gt; { :validation =&gt; "required validate_max_length length50", "validation-error-msg" =&gt; "First Name is required and cannot be longer than 50 characters." }) %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:last_name, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:last_name, :class =&gt; "input-xlarge field", :data =&gt; { :validation =&gt; "required validate_max_length length50", "validation-error-msg" =&gt; "Last Name is required and cannot be longer than 50 characters." }) %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:call_sign, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:call_sign, :class =&gt; "input-xlarge field", :data =&gt; { :validation =&gt; "required validate_length length5-50", "validation-error-msg" =&gt; "Call Sign is required and cannot be must be between 5 and 50 characters." }) %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;%= f.hidden_field(:_destroy, :class =&gt; "field") %&gt;
    &lt;/fieldset&gt;
  &lt;/div&gt;
  &lt;div class="modal-footer"&gt;
    &lt;button id="addButton" type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" title="Add this Pilot to the list of Pilots that are assigned to this Ship."&gt;Add&lt;/button&gt;
    &lt;button id="cancelButton" type="button" class="btn btn-inverse" data-dismiss="modal" aria-hidden="true" title="Close this screen without adding the Pilot to the list."&gt;Cancel&lt;/button&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;
  pilotFieldsUI.init();
&lt;/script&gt;</pre>
<p>Just like this <a>fine fellow</a> did, we&#8217;ll add some CSS to our application.css file to make sure our error messages appear below the offending element:</p>
<p><strong>app/assets/stylesheets/application.css.scss:</strong></p>
<pre class="brush:css">.jquery_form_error_message{
  display: block;
  margin-top: 3px;
  color: #f00;
}</pre>
<p>Now all we have to do is wire up the <a href="https://github.com/victorjonsson/jQuery-Form-Validator">jQuery-Form-Validator</a> to our &#8220;Add a Pilot&#8221; modal form. Here&#8217;s how we do that:</p>
<p><strong>app/assets/javascripts/ships.js:</strong></p>
<pre class="brush:javascript">// Set up the UI/UX for the ships screens.  This object sets up all the functionality we need to:
//  1.  Bind to the "click" event of the "#addButton" on the modal form.
//  2.  Append data from the modal form to the Pilots table.
//  3.  Hide the modal form when the user is done entering data.
//
// If any other events need to be wired up, the init function would be the place to put them.
var pilotFieldsUI = {
    init: function() {
        // Configuration for the jQuery validator plugin:
        // Set the error messages to appear under the element that has the error.  By default, the
        // errors appear in the all-too-familiar bulleted-list.
        // Other configuration options can be seen here:  https://github.com/victorjonsson/jQuery-Form-Validator
        var validationSettings = {
            errorMessagePosition : 'element'
        };

        // Run validation on an input element when it loses focus.
        $('#new-pilot-fields').validateOnBlur();

        $('#addButton').on('click', function(e) {
            // If the form validation on our Pilots modal "form" fails, stop everything and prompt the user
            // to fix the issues.
            var isValid = $('#new-pilot-fields').validate(false, validationSettings);
            if(!isValid) {
                e.stopPropagation();

                return false;
            }

            // This is the code from previous posts...
            formHandler.appendFields();
            formHandler.hideForm();
        });
    }
};</pre>
<p>On line 13, we&#8217;re building a configuration object that contains our setting for the jQuery-Form-Validator. All we want to do is set the error messages to appear next to the <code>input element</code>, so that&#8217;s all we&#8217;re setting for now. On line 18, we&#8217;re telling the jQuery-Form-Validator to fire whenever one of our elements loses focus. Am I over-explaining? Probably. Almost certainly. But it&#8217;s too late now!</p>
<p>On line 23, things get slightly more interesting. Since the &#8220;Add a Pilot&#8221; modal form isn&#8217;t a proper form (remember, it&#8217;s a <code>&lt;div&gt;</code> on our <code>Ship form</code>), our &#8220;Add&#8221; button isn&#8217;t a <code>submit</code>. However, we&#8217;re going to call <code>.validate</code> on our <code>#new-pilot-fields</code> anyway. If our validation fails, then stop everything and let the user fix their issues.</p>
<p>Now that we&#8217;ve wired everything up, here&#8217;s what it looks like after a user click&#8217;s the &#8220;Add&#8221; button:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Screen-Shot-2013-02-24-at-9.13.03-PM.png" alt="Pilot modal form with client-side validation in effect." width="470" height="350" /></p>
<p>As an added bonus, the validation functionality is carried forward when we add the new <code>Pilot</code> to our &#8220;Pilots&#8221; section of the <code>Ship form</code>. Here&#8217;s what it looks like when a user adds a <code>Pilot</code> successfully, but then removes the Call Sign before clicking save:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Screen-Shot-2013-02-24-at-9.20.25-PM.png" alt="Validation on the Pilot fields works after adding to the Pilots table." width="682" height="258" /></p>
<h2>Caveat</h2>
<p>The trick shown above isn&#8217;t 100% bullet-proof &#8211; remember we aren&#8217;t calling jQuery-Form-Validator&#8217;s <code>validate()</code> method when we submit <code>Ship form</code>. It&#8217;d be pretty easy to implement, so I&#8217;ll leave that as an exercise for you, dear reader. However, we <em>are</em> covered by our server-side validation that we implemented in our models. See?</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Screen-Shot-2013-02-24-at-9.49.23-PM.png" alt="Pilot validation still happens on the server-side." width="677" height="261" /></p>
<p>It&#8217;s not perfect, but it&#8217;s better than nothing. We&#8217;ll try to clean this up in a later post.</p>
<h2>Conclusion</h2>
<p>We&#8217;re <em>definitely</em> closing in on the exhaust port now, ladies and gentelmen! Our Starfighter Recognition Guide&#8217;s shields have been hardened with some client-side validation. These shield upgrades will come in handy to deflect the incoming fire our users will no doubt throw at us. Our intrepid heroes aren&#8217;t quite out of the woods yet &#8211; there&#8217;s some additional validation we could add (isn&#8217;t there always?), but we&#8217;ll handle that as our pilots approach their target.</p>
<h2>Reference</h2>
<p>Here are some articles/tools that helped me out immensely with this post:</p>
<ul>
<li><a href="http://webtempest.com/easy-client-side-form-validation-for-rails-3-1/">Easy Client-Side Form Validation for Rails 3.1</a></li>
<li><a href="https://github.com/victorjonsson/jQuery-Form-Validator">jQuery-Form-Validator</a></li>
<li><a href="http://victorjonsson.se/51/jquery-form-validator">jQuery-Form-Validator Demo Page</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-4-switch-to-targeting-computer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SharpRepository: Configuration</title>
		<link>http://www.fairwaytech.com/2013/02/sharprepository-configuration/</link>
		<comments>http://www.fairwaytech.com/2013/02/sharprepository-configuration/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 18:09:56 +0000</pubDate>
		<dc:creator>Jeff Treuting</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Jeff Treuting]]></category>
		<category><![CDATA[repository]]></category>
		<category><![CDATA[SharpRepository]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=3611</guid>
		<description><![CDATA[If you haven&#8217;t read my introductory post on SharpRepository you should give it a quick read as it provides a nice overview of the basic usage of SharpRepository.  In that [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t read my <a title="SharpRepository: Getting Started" href="http://www.fairwaytech.com/2012/12/sharprepository-getting-started/">introductory post on SharpRepository</a> you should give it a quick read as it provides a nice overview of the basic usage of SharpRepository.  In that post, I use the simplest method for creating my repository, I just new it up like so:</p>
<pre class="brush:csharp">var orderRepository = new InMemoryRepository&lt;Order&gt;();</pre>
<p>While this definitely works, it isn&#8217;t the best way.  Why?  Well, if you want to switch to an Ef5Repository or want to add caching, you will need to change the code and recompile.  Plus, you are using dependency injection and inversion of control right?  Well this doesn&#8217;t work with those patterns of course.   In this post I will cover some of the various ways to create your repository.</p>
<h2>Configuration Overview</h2>
<p>Before getting into the code for loading up a repository via configuration settings it will be helpful to understand the SharpRepository hierarchy.  Each repository has a specific type of backend that it queries (e.g. InMemory, Entity Framework, RavenDb, MongoDb, Db4o,  Xml, etc.), a caching strategy (e.g. None, Standard, Timeout), and a caching provider (e.g. Memory, memcached, Azure, etc.).</p>
<p>The caching strategy tells the repository the rules for caching.  The Timeout Strategy uses a simple time based rule, for example, cache the query results for 30 seconds, while the Standard Strategy uses <a title="Write-through and Generational Caching Make a Great Team" href="http://www.fairwaytech.com/2012/09/write-through-and-generational-caching/">Generational and Write-Through caching</a> techniques to provide a more sophisticated caching logic.  And the No Caching Strategy does not do any caching at all (it&#8217;s not just a clever name).</p>
<p>The caching provider on the other hand is the specific cache technology that is used.  For simple websites the InMemory caching provider works great and uses the ASP.NET built-in System.Runtime.Caching.MemoryCache. For more advanced needs like distributed caching you would use the memcached provider or the Windows Azure provider and store the cache across multiple servers.</p>
<p>The beauty of this is that both of these can be extended by inheriting from ICachingStrategy or ICachingProvider if the need arises.</p>
<p><span id="more-3611"></span></p>
<h2>Create from Configuration Object</h2>
<p>You can create a SharpRepositoryConfiguration object and use that to create your repository.  The SharpRepositoryConfiguration object allows you to build a &#8220;profile&#8221; and then when you create a specific repository you can choose which &#8220;profile&#8221; to use.  I think that the code below will help show what I mean.</p>
<pre class="brush:csharp">            var config = new SharpRepositoryConfiguration();
            config.AddRepository(new Ef5RepositoryConfiguration("ef5", "DefaultConnection")); // EF repository named ef5 using the DefaultConnection connection string
            config.AddRepository(new InMemoryRepositoryConfiguration("inmemory", "standard", "memcached")); // InMemoryRepository named default using the none CachingStrategy

            config.AddCachingStrategy(new TimeoutCachingStrategyConfiguration("timeout", 30)); // Timeout strategy named timeout with 30 second cache time
            config.AddCachingStrategy(new StandardCachingStrategyConfiguration("standard")); // Standar d strategy named standard
            config.AddCachingStrategy(new NoCachingStrategyConfiguration("none")); // No caching named none

            config.AddCachingProvider(new InMemoryCachingProviderConfiguration("inmemory")); // InMemory provider name inmemory
            config.AddCachingProvider(new MemCachedCachingProviderConfiguration("memcached", "memcached"));  // memcached provider named memcached and using the memcached section in config file

            config.DefaultRepository = "ef5";
            config.DefaultCachingStrategy = "timeout";
            config.DefaultCachingProvider = "inmemory";

            var userRepos = RepositoryFactory.GetInstance&lt;User, int&gt;(config); // uses the Ef5Repository
            var orderRepos = RepositoryFactory.GetInstance&lt;Order, int&gt;(config, "inmemory"); // uses InMemoryRepository with Standard caching strategy and memcached</pre>
<p>As you can see above, the SharpRepositoryConfiguration gets loaded with multiple repositories that can use the various caching strategies and caching providers.  Note that everything is referred to by name.  The specific repository configuration (e.g. Ef5RepositoryConfiguration and InMemoryRepositoryConfiguration) always takes a name first, then anything specific to that type (like the connection string name for EF5), and optionally a caching strategy and provider can be provided last.  If no caching strategy or provider is used, the DefaultCachingStrategy and DefaultCachingProvider are used, and if those aren&#8217;t set then no caching is used by default.</p>
<p>This does provide the benefit of being able to setup your configuration in a single location and then pass that configuration in when loading up your repository.  You can then make changes in a single location and it will effect everywhere that you create repositories.  That being said, there may be some cases where you would need programmatic access to the configuration, but most likely this is not what you should be doing.  Well, then why did you show me this?  Good question.  It leads me into the next way of doing things &#8230; Web.config (or App.config).</p>
<h2>Configuration File</h2>
<p>The same basic structure as the configuration object can be used in your Web.config (or App.config).  Note: if you install the NuGet packages it will stub out these sections for you.  For example, if you install SharpRepository.Ef5Repository it will include the proper configSection at the top of the file and create the specific repository using the DefaultConnection connectionstring name.  You can then go in and edit this, but it allows you to not have to code out the assembly type paths, which are kind of a pain.</p>
<p>Here is an example of what the configuration used above would look like in your configuration file:</p>
<pre class="brush:xml">  &lt;sharpRepository&gt;
    &lt;repositories default="ef5"&gt;
      &lt;repository name="ef5" connectionString="DefaultConnection" factory="SharpRepository.Ef5Repository.Ef5ConfigRepositoryFactory, SharpRepository.Ef5Repository"  /&gt;
      &lt;repository name="inmemory" factory="SharpRepository.Repository.InMemoryRepositoryFactory, SharpRepository.Repository" cachingStrategy="standard" cachingProvider="memcached" /&gt;
    &lt;/repositories&gt;
    &lt;cachingProviders default="inmemory"&gt;
      &lt;cachingProvider name="inmemory" factory="SharpRepository.Repository.Caching.InMemoryConfigCachingProviderFactory, SharpRepository.Repository" /&gt;
      &lt;cachingProvider name="memcached" factory="SharpRepository.Caching.Memcached.MemCachedConfigCachingProviderFactory, SharpRepository.Caching.Memcached" /&gt;
    &lt;/cachingProviders&gt;
    &lt;cachingStrategies default="timeout"&gt;
      &lt;cachingStrategy name="standard" generational="true" writeThrough="true" factory="SharpRepository.Repository.Caching.StandardConfigCachingStrategyFactory, SharpRepository.Repository" /&gt;
      &lt;cachingStrategy name="timeout" timeout="30" factory="SharpRepository.Repository.Caching.TimeoutConfigCachingStrategyFactory, SharpRepository.Repository" /&gt;
      &lt;cachingStrategy name="none" factory="SharpRepository.Repository.Caching.NoCachingConfigCachingStrategyFactory, SharpRepository.Repository" /&gt;
    &lt;/cachingStrategies&gt;
  &lt;/sharpRepository&gt;</pre>
<p>Then in your C# code, you would load them up with the similar calls to RepositoryFactory.GetInstance like so:</p>
<pre class="brush:csharp">var userRepos = RepositoryFactory.GetInstance&lt;User, int&gt;(); // uses the Ef5Repository since it's the default
var orderRepos = RepositoryFactory.GetInstance&lt;Order, int&gt;("inmemory"); // uses InMemoryRepository with Standard caching strategy and memcached</pre>
<p>This is a much better approach than using the configuration objects because if you need to make a change, like changing your caching or changing from an InMemoryRepository during your prototyping phase to an Ef5Repository, you can just edit your Web.config file and there is no need for a recompile.</p>
<p>But what if I want to add custom methods to my repository or use constructor injection, how would I do that?  Wow, you are great at helping me move to my next section, thanks.</p>
<h2>Custom repositories</h2>
<p>There are situations where you will want to create a custom repository so you can add your own methods to it, or just because you like programming against an IUserRepository instead of IRepository&lt;User, int&gt;.  So how would you do that?</p>
<pre class="brush:csharp">    public interface IUserRepository : IRepository&lt;User, int&gt;
    {
        User GetAdminUser();
    }

    public class UserRepository : InMemoryRepository&lt;User, int&gt;, IUserRepository
    {
        public User GetAdminUser()
        {
            return Find(x =&gt; x.Email == "admin@admin.com");
        }
    }</pre>
<p>Here we create your own UserRepository that has a custom GetAdminUser() method (side note: personally I would put these kind of methods in my Service layer but not everyone would do that, especially on simpler applications).  This isn&#8217;t ideal because as mentioned before we are now hard-coding the use of an InMemoryRepository and we would need to change this and recompile if we switch to an Ef5Repository or if we want to add caching logic to this repository.  So here is a cleaner way to handle this:</p>
<pre class="brush:csharp">    public interface IUserRepository : IRepository&lt;User, int&gt;
    {
        User GetAdminUser();
    }

    public class UserRepository : ConfigurationBasedRepository&lt;User, int&gt;, IUserRepository
    {
        public User GetAdminUser()
        {
            return Find(x =&gt; x.Email == "admin@admin.com");
        }
    }</pre>
<p>Looks pretty much the same huh?  Well there is one big difference, instead of inheriting from InMemoryRepository we are inheriting from ConfigurationBasedRepository.  ConfigurationBasedRepository will use the configuration files to decide which type of repository to create .  Behind the scenes it is calling RepositoryFactory.GetInstance&lt;User, int&gt;() like we used above.</p>
<p>This setup gives you the ability code against IUserRepository while controlling the details of the repository and caching, etc. from your configuration file, allowing for easier maintenance (especially when in development and testing things).</p>
<h2>What about dependency injection?</h2>
<p>Personally my favorite Ioc container is StructureMap so that is what I&#8217;ll be using in my examples.  The same can be done in the Ioc container of your choice.</p>
<p>Let&#8217;s say you are creating an MVC application and you have a UserController that will need access to your IUserRepository (or IRepository&lt;User, int&gt; if you haven&#8217;t created a custom repository).  You will want to inject the repository into the constructor like this:</p>
<pre class="brush:csharp">        private readonly IUserRepository _repository;
        public UserController(IUserRepository repository)
        {
            _repository = repository;
        }</pre>
<p>Or like this:</p>
<pre class="brush:csharp">        private readonly IRepository&lt;User, int&gt; _repository;
        public UserController(IRepository&lt;User, int&gt; repository)
        {
            _repository = repository;
        }</pre>
<p>The only thing left to do is wire up StructureMap to be able to handle this.  Let&#8217;s just say that getting StructureMap to handle the generic arguments and use them to load the repository from the configuration file took a little Googling.  To make this easy to implement we have created some extension methods to use in your StructureMap registry (we also have equivalent methods for Ninject and Windsor).  All you need to do is install the <a href="http://nuget.org/packages/SharpRepository.Ioc.StructureMap/" target="_blank">StructureMap.Ioc.StructureMap</a> NuGet package (or the other IoC packages).  The code that wires it up looks something like this:</p>
<pre class="brush:csharp">            initialization.For(typeof(IRepository&lt;&gt;))
                                 .Use(context =&gt;
                                 {
                                     var genericArgs = context.BuildStack.Current.RequestedType.GetGenericArguments();

                                     return RepositoryFactory.GetInstance(genericArgs[0], repositoryName);
                                 }
                );

            initialization.For(typeof(IRepository&lt;,&gt;))
                                 .Use(context =&gt;
                                 {
                                     var genericArgs = context.BuildStack.Current.RequestedType.GetGenericArguments();

                                     return RepositoryFactory.GetInstance(genericArgs[0], genericArgs[1], repositoryName);
                                 }
                );</pre>
<p>Then all you have to do is include the call to ForRepositoriesUserSharpRepository() extension method in your Initialize method like so:</p>
<pre class="brush:csharp">ObjectFactory.Initialize(x =&gt;
            {
                x.Scan(scan =&gt;
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });

                x.ForRepositoriesUseSharpRepository();
            });</pre>
<p>That&#8217;s it.  Now StructureMap will load up the proper repository based on your configuration file when you request an IRepository&lt;User, int&gt; or a custom repository that inherits from it like IUserRepository in our example above.</p>
<p>For Ninject you would call kernel.BindSharpRepository() and for Windsor you can call container.RegisterSharpRepository().</p>
<h2>Entity Framework and sharing the DbContext</h2>
<p>As of SharpRepository 1.2, you can now use an IoC container to share your DbContext across multiple Ef5Repository instances.  We&#8217;ve created a RepositoryDependencyResolver that is used internally to request object instances.  The Ef5Repository uses this, if it has been configured, to get an instance of DbContext.  This allows the user to control the DbContext life-cycle.  We have created NuGet packages for <a href="http://nuget.org/packages/SharpRepository.Ioc.Autofac/" target="_blank">Autofac</a>, <a href="http://nuget.org/packages/SharpRepository.Ioc.Ninject/" target="_blank">Ninject</a>, <a href="http://nuget.org/packages/SharpRepository.Ioc.StructureMap/" target="_blank">StructureMap</a>, <a href="http://nuget.org/packages/SharpRepository.Ioc.Unity/" target="_blank">Unity</a> and <a href="http://nuget.org/packages/SharpRepository.Ioc.Windsor/" target="_blank">Windsor</a> that have custom RepositoryDependencyResolvers for each IoC container.  Just install the package that you need, or it&#8217;s really simple to create your own if you are using an IoC not listed here.  Keeping with StructureMap, here is how you would configure everything.</p>
<p>First make sure your StructureMap Registry has an entry for DbContext.  This would set the life-cycle to the ASP.NET page request, which makes the same DbContext available to all your repositories used during that request.</p>
<pre class="brush:csharp">    // Hybrid (once per thread or ASP.NET request if you’re in a web application)
    For&lt;DbContext&gt;()
        .HybridHttpOrThreadLocalScoped()
        .Use&lt;CustomEfEntities&gt;()
        .Ctor&lt;string&gt;("connectionString").Is(entityConnectionString);</pre>
<p>Find in your startup code where you are initializing your IoC and after that add the following:</p>
<pre class="brush:csharp">    RepositoryDependencyResolver.SetDependencyResolver(new StructureMapDependencyResolver(ObjectFactory.Container));</pre>
<p>This tells SharpRepository to use the StructureMap container (ObjectFactory.Container) to resolve DbContext.</p>
<h2>Conclusion</h2>
<p>Sorry for the long winding path to getting where I wanted to go, but hopefully showing the flexibility allowed is helpful and will allow you to use SharpRepository however you are most comfortable.  Personally, I like to use StructureMap to handle my dependency injections and will code against IRepository&lt;User, int&gt; unless there is a good reason to create my own custom repository.  In that case, I will have UserRepository inherit from ConfigurationBasedRepository and IUserRepository and code against the IUserRepositry interface.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/02/sharprepository-configuration/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rails 3.2: A Nested-Form Demo, Part 3:  We&#8217;re Starting Our Attack Run!</title>
		<link>http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-3-were-starting-our-attack-run/</link>
		<comments>http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-3-were-starting-our-attack-run/#comments</comments>
		<pubDate>Fri, 08 Feb 2013 02:26:35 +0000</pubDate>
		<dc:creator>Jeff Johnson</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Rails 3.2]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[TIE]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=3744</guid>
		<description><![CDATA[Overview When we last left our heroes, they fought their way through the superstructure of our application and were setting up to finish it off. Having defeated the TIE fighter [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>When <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/">we last left our heroes</a>, they fought their way through the superstructure of our application and were setting up to finish it off. Having defeated the TIE fighter screen, our intrepid fighter pilots have descended into the trench of the Starfighter Recognition Guide. Their computers are locked, they&#8217;re getting a signal&#8230;</p>
<p>In this post, we&#8217;ll capitalize on the code and plumbing we implemented <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-nested-form-demo-part-1-all-wings-report-in/">here</a> and <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/">here</a>. We&#8217;ll take a look at the views we put in place and some javascript to make our Starfighter Recognition Guide a bit fancy-pants.</p>
<p>Stabilize your rear deflectors and watch for enemy fighters &#8211; there&#8217;s gonna be a tubolaser battery&#8217;s worth of code in this one.</p>
<p><span id="more-3744"></span></p>
<h2>The <code>Index</code> View</h2>
<p>There isn&#8217;t a whole lot of interesting stuff going on in the home/landing page of the Starfighter Recognition Guide, (i.e. our <code>index.html.erb</code>). It&#8217;s basically a table that shows all of the <code>Ships</code> that have been entered so far. Here&#8217;s a pretty picture of what the home page looks like:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Nested_Form_Index.png" alt="Home page of the Starfighter Recognition Guide" width="576" height="333" /></p>
<p>I know &#8211; neat-o, right?  If you want to see the source code for the <code>index.html.erb</code> view, you can check it out <a href="https://github.com/jeffjohnson9046/nested-form/blob/master/app/views/ships/index.html.erb">here</a>.</p>
<h2>The <code>_form</code> Partial View</h2>
<p>Because functionality for adding a new <code>Ship</code> or editing an existing <code>Ship</code> is largely the same, I&#8217;ve created a <code>_form.html.erb</code> partial view that encapsulates all the data entry fields and extra goodies that we&#8217;ll need to persist our <code>Ships</code> and <code>Pilots</code>. Here&#8217;s what it looks like:</p>
<p><code><strong>app/views/ships/_form.html.erb:</strong></code></p>
<pre class="brush:ruby">&lt;%= form_for(@ship, :html =&gt; {:class =&gt; "form form-horizontal"}) do |f| %&gt;
    &lt;fieldset&gt;
      &lt;legend&gt;&lt;%= "#{ @ship.name } " unless @ship.name.nil?  %&gt;Ship Information&lt;/legend&gt;
      &lt;%= render('error_messages', <img src='http://www.fairwaytech.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> bject =&gt; f.object) %&gt;
      &lt;div class="control-group"&gt;
        &lt;%= f.label(:name, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:name, :class =&gt; "input-xlarge") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:crew, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:crew, :class =&gt; "input-xlarge") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:has_astromech, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.check_box(:has_astromech, :class =&gt; "checkbox") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:speed, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:speed, :class =&gt; "input-xlarge") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:armament, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_area(:armament, :class =&gt; "input-xlarge", :rows =&gt; "3") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/fieldset&gt;

    &lt;fieldset&gt;
      &lt;legend&gt;Pilots &lt;%= "That Fly the  #{ @ship.name }" unless @ship.name.nil? %&gt;&lt;/legend&gt;
      &lt;%= render('pilots_table', :f =&gt; f) %&gt;
      &lt;%= link_to_add_fields("Add a Pilot", f, :pilots, :class =&gt; "btn btn-primary", :title =&gt; "Add a new Pilot to the list of Pilots that fly this Ship.") %&gt;
      &lt;p&gt;&lt;/p&gt;
    &lt;/fieldset&gt;

    &lt;div class="modal-footer"&gt;
      &lt;%= f.submit("Save", :class =&gt; "btn btn-primary", :title =&gt; "Save the changes to this Ship.") %&gt;
      &lt;%= link_to("Cancel", ships_path, :confirm =&gt; "Are you sure you want to cancel?  Any changes will be lost.", :class =&gt; "btn btn-inverse", :title =&gt; "Cancel the changes and return to the Home page.") %&gt;
    &lt;/div&gt;
&lt;% end %&gt;</pre>
<p>The interesting part is on line 43, where we&#8217;re rendering the <code>_pilots_table.html.erb</code> partial view. Notice how we&#8217;re passing our <code>form</code> to it? That&#8217;ll allow us to use the <code>fields_for</code> method on the &#8220;parent&#8221; <code>form</code> (i.e. the <code>Ship</code>&#8216;s <code>form</code>) to generate input fields for all the <code>Ship</code>&#8216;s <code>Pilots</code>. Let&#8217;s take a look at the <code>_pilots_table.html.erb</code> partial view, shall we? Yes, let&#8217;s:</p>
<p><code><strong>app/views/ships/_pilots_table.html.erb:</strong></code></p>
<pre class="brush:ruby">&lt;table id="pilots-table" class="table table-hover table-striped"&gt;
  &lt;thead&gt;
    &lt;th&gt;First Name&lt;/th&gt;
    &lt;th&gt;Last Name&lt;/th&gt;
    &lt;th&gt;Call Sign&lt;/th&gt;
  &lt;th&gt;&lt;/th&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;%= f.fields_for(:pilots) do |pilots_form| %&gt;
      &lt;tr class="fields"&gt;
        &lt;td&gt;&lt;%= pilots_form.text_field(:first_name) %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= pilots_form.text_field(:last_name) %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= pilots_form.text_field(:call_sign) %&gt;&lt;/td&gt;
        &lt;% if current_page?(new_ship_path) || current_page?(edit_ship_path) %&gt;
            &lt;td&gt;
              &lt;%= link_to_remove_fields('&lt;i class="icon-remove"&gt;&lt;/i&gt;'.html_safe, pilots_form, :title =&gt; "Delete this Pilot.") %&gt;
            &lt;/td&gt;
        &lt;% end %&gt;
      &lt;/tr&gt;
    &lt;% end %&gt;
  &lt;/tbody&gt;
&lt;/table&gt;</pre>
<p>On line 9, we&#8217;re calling <code>fields_for</code> to generate the input fields for each <code>Pilot</code> associated to our <code>Ship</code>. Also notice on line 16 we&#8217;re using our <code>link_to_remove_fields</code> helper method (described in exhaustive detail <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/">here</a>) to create a link that will allow us to delete the <code>Pilot</code> if we want. Because we&#8217;ve used <code>fields_for</code> to wire up the input fields for our associated <code>Pilots</code>, we can edit <em>any</em> of the <code>Pilots</code> and/or the <code>Ship</code>&#8216;s attributes. When we submit our <code>form</code>, everything will be saved to the database in one swell foop. To see what the POST might look like when this <code>form</code> is submitted, you can take a look <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-nested-form-demo-part-1-all-wings-report-in/">here</a>.</p>
<p>To see this in action, let&#8217;s take a look at a screenshot of a <code>Ship</code> being edited:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Nested_Form_Edit_Ship_w_Pilots.png" alt="Editing a Ship with Pilots" width="356" height="305" /></p>
<h2>Adding a new <code>Ship</code> and <code>Pilot</code></h2>
<p>As mentioned previously, adding a new <code>Ship</code> is pretty much like editing an existing <code>Ship</code>. Let&#8217;s add a new ship to our Starfighter Recognition Guide: The TIE Interceptor. We click the &#8220;Add a Ship&#8221; button on the home/landing page, and end up with something like this:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Nested_Form_New.png" alt="Add the Tie Interceptor" width="487" height="397" /></p>
<p>Now we click on the &#8220;Add a Pilot&#8221; button, which renders our <code>_pilot_fields.html.erb</code> partial view as a modal form. We talked about the mechanism to make this work (our <code>link_to_add_fields</code> helper method) in the <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/">last post</a>. Shown below is a screenshot of the modal form that allows us to add a new <code>Pilot</code>:</p>
<p style="text-align: center;"> <img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Nested_Form_Pilot_Modal.png" alt="Add a Pilot to the Tie Interceptor with a modal form" width="468" height="253" /></p>
<p>Here&#8217;s what the <code>_pilot_fields.html.erb</code> looks like under the covers:</p>
<p><code><strong>app/views/ships/_pilot_fields.html.erb:</strong></code></p>
<pre class="brush:ruby">&lt;div id="new-pilot-fields" class="modal fade" data-backdrop="static"&gt;
  &lt;div class="modal-header"&gt;
    &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt;
    &lt;h3&gt;Add a Pilot&lt;%= " to the #{ @ship.name } Pilot Roster" unless @ship.name.nil? %&gt;&lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="modal-body"&gt;
    &lt;fieldset&gt;
      &lt;div class="control-group"&gt;
        &lt;%= f.label(:first_name, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:first_name, :class =&gt; "input-xlarge field") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:last_name, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:last_name, :class =&gt; "input-xlarge field") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      &lt;div class="control-group"&gt;
        &lt;%= f.label(:call_sign, :class =&gt; "control-label") %&gt;
        &lt;div class="controls"&gt;
          &lt;%= f.text_field(:call_sign, :class =&gt; "input-xlarge field") %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;%= f.hidden_field(:_destroy, :class =&gt; "field") %&gt;
    &lt;/fieldset&gt;
  &lt;/div&gt;
  &lt;div class="modal-footer"&gt;
    &lt;button id="addButton" type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" title="Add this Pilot to the list of Pilots that are assigned to this Ship."&gt;Add&lt;/button&gt;
    &lt;button id="cancelButton" type="button" class="btn btn-inverse" data-dismiss="modal" aria-hidden="true" title="Close this screen without adding the Pilot to the list."&gt;Cancel&lt;/button&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;
  pilotFieldsUI.init();
&lt;/script&gt;</pre>
<p>There isn&#8217;t anything very fancy going on in the <code>_pilot_fields.html.erb</code> partial view. I&#8217;d go so far as to say the only interesting bit is the <code>script</code> tag at the bottom. What&#8217;s going on there? Let&#8217;s find out!</p>
<h2>Javascript for the <code>Pilot</code> Modal Form</h2>
<p>So, we have our <code>Pilot</code> input fields appearing in a modal form. What now? What should happen when a user clicks the &#8220;Add&#8221; button on the modal form? How will a user be able to add multiple <code>Pilots</code> to a single <code>Ship</code>?</p>
<p>Well, it&#8217;d be nice if the newly created <code>Pilot</code> was added to the &#8220;Pilots&#8221; table shown in the &#8220;Add a Ship&#8230;&#8221; screen (shown above). Ideally, it&#8217;d be nice if the rows looked exactly the same as the &#8220;Pilots&#8221; table in the &#8220;Editing&#8230;&#8221; screen (also shown above).</p>
<p><code><strong>app/assets/javascripts/ships.js:</strong></code></p>
<pre class="brush:javascript">var pilotFieldsUI = {
    init: function() {
        $('#addButton').on('click', function() {
            formHandler.appendFields();
            formHandler.hideForm();
        });
    }
};</pre>
<p>The code above shows our <code>pilotFieldsUI</code> object literal, which has one function: <code>init</code>. The <code>init</code> function wires up the <code>addButton</code> on our <code>Pilot</code> modal form. As you can see, a couple of methods will be invoked when a user clicks the &#8220;Add&#8221; button on the <code>Pilot</code> modal form. Let&#8217;s check those out next:</p>
<p><code><strong>app/assets/javascripts/ships.js:</strong></code></p>
<pre class="brush:javascript">var formHandler = {
    // Public method for adding a new row to the table.
    appendFields: function() {
        // Get a handle on all the input fields in the form and detach them from the DOM (we will attach them later).
        var inputFields = $(cfg.formId + ' ' + cfg.inputFieldClassSelector);
        inputFields.detach();

        // Build the row and add it to the end of the table.
        rowBuilder.addRow(cfg.getTBodySelector(), inputFields);

        // Add the "Remove" link to the last cell.
        rowBuilder.link.appendTo($('tr:last td:last'));
    },

    // Public method for hiding the data entry fields.
    hideForm: function() {
        $(cfg.formId).modal('hide');
    }
};</pre>
<p>Again, the <code>formHandler</code> is nothing spectacular. The idea behind the <code>formHandler</code> is like this: the <code>formHandler</code> manages the orchestration of all the fancy UI stuff. He&#8217;ll delegate the specifics (e.g. building a row element w/the <code>Pilot</code> input fields) to other objects. In this case, we want to build a row that we&#8217;ll add to the Pilots table and we&#8217;ll want to hide the modal form when we&#8217;re done. To achieve that, we have a couple of methods:</p>
<ul>
<li><strong>appendFields:</strong> This method will add the input fields from the <code>Pilot</code> modal form and add them as a new row to the Pilots table on the <code>Ship</code> form.</li>
<li><strong>hideForm:</strong> Hides/dismisses the <code>Pilot</code> modal form (thanks, <a href="http://twitter.github.com/bootstrap/javascript.html#modals">Twitter Bootstrap</a>!).</li>
</ul>
<p>I wanted to keep all of my IDs and other &#8220;magic string&#8221; type stuff in one place, so I created a quick <code>cfg</code> object literal that looks like what&#8217;s shown below:</p>
<p><code><strong>app/assets/javascripts/ships.js:</strong></code></p>
<pre class="brush:javascript">var cfg = {
    formId: '#new-pilot-fields',
    tableId: '#pilots-table',
    inputFieldClassSelector: '.field',
    getTBodySelector: function() {
        return this.tableId + ' tbody';
    }
};</pre>
<p>The <code>cfg</code> object is referenced by the <code>formHandler</code> and the <code>rowBuilder</code>. That gives me an excellent segue to the <code>rowBuilder</code>, which looks like this:</p>
<p><code><strong>app/assets/javascripts/shipsjs:</strong></code></p>
<pre class="brush:javascript">var rowBuilder = function() {
    // Private property that define the default &lt;TR&gt; element text.
    var row = $('&lt;tr&gt;', { class: 'fields' });

    // Public property that describes the "Remove" link.
    var link = $('&lt;a&gt;', {
        href: '#',
        onclick: 'remove_fields(this); return false;',
        title: 'Delete this Pilot.'
    }).append($('&lt;i&gt;', { class: 'icon-remove' }));

    // A private method for building a &lt;TR&gt; w/the required data.
    var buildRow = function(fields) {
        var newRow = row.clone();

        $(fields).map(function() {
            $(this).removeAttr('class');
            return $('&lt;td/&gt;').append($(this));
        }).appendTo(newRow);

        return newRow;
    }

    // A public method for building a row and attaching it to the end of a &lt;TBODY&gt; element.
    var attachRow = function(tableBody, fields) {
        var row = buildRow(fields);
        $(row).appendTo($(tableBody));
    }

    // Only expose public methods/properties.
    return {
        addRow: attachRow,
        link: link
    }
}();</pre>
<p>The <code>rowBuilder</code> has one purpose in life &#8211; to build a <code>&lt;TR&gt;</code> element that will be added to the &#8220;Pilots&#8221; table. The <code>&lt;TR&gt;</code> element will contain the input fields from the <code>Pilot</code> modal form.</p>
<p>The <code>rowBuilder</code> is a bit more complex than his brethren <code>cfg</code> or <code>formHandler</code>. There are some properties/methods of the <code>rowBuilder</code> that don&#8217;t need to be called by anyone else, so I wanted to keep those private. To achieve that, I used the <a href="http://blog.pluralsight.com/2012/10/02/revealing-module-pattern-structuring-javascript-code-part-iii/">revealing module pattern</a> (sounds awesome, right?!) to only expose the methods that should be&#8230; err&#8230; exposed, I guess. I like this pattern a lot and I think you get a lot of bang for your buck by using it. It&#8217;s easy to implement, makes code more readable, and <em>clearly communicates the intent to other developers</em>. With an extra line or two, we&#8217;ve told the next guy/girl who works on this project what parts of the <code>rowBuilder</code> are guts/plumbing and what parts are intended for use by other components of our program.</p>
<p><strong style="color: #f00;">CODE SMELL:</strong> The <code>rowBuilder.link</code> property should probably be private and should probably be added to the new <code>&lt;TR&gt;</code> element before it&#8217;s returned. Right now, the <code>rowBuilder.link</code> property is used in the <code>formHandler.appendFields()</code> method (line 12 in the <code>formHandler</code> snippet). This is an area that is ripe for refactoring.</p>
<p>With all that javascript, what happens when a user clicks the &#8220;Add&#8221; button after adding a new <code>Pilot</code> to the Tie Interceptor <code>Ship</code>? Well, the screen looks like this:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.fairwaytech.com/wp-content/uploads/2013/02/Nested_Form_After_Pilot_Modal.png" alt="Add a Ship with a Pilot" width="494" height="384" /></p>
<h2>Summary: It&#8217;s Away!</h2>
<p>So&#8230; there you have it. We created a new TIE Interceptor <code>Ship</code> with a <code>Pilot</code> named Maarek Stele. Because of our implementation, the user can change any of the <code>Pilot</code> attributes before committing everything to the database. When the user clicks the &#8220;Save&#8221; button, the POST will contain the <code>Ship</code> and <code>Pilot</code> attributes (again, en example of what the POST will look like can be found <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-nested-form-demo-part-1-all-wings-report-in/">here</a>).</p>
<h2>Devil&#8217;s Advocate: My Scope&#8217;s Negative, I Don&#8217;t See Anything!</h2>
<p><em><strong>Hey Jeff, how come you didn&#8217;t just append a row with new input fields to the &#8216;Pilots&#8217; table to begin with? What&#8217;s with all the modal mumbo jumbo?</strong></em><br />
Sure, we could&#8217;ve done that. If you remember from a long time ago in a <a href="http://www.fairwaytech.com/2013/01/rails-3-2-a-nested-form-demo-part-1-all-wings-report-in/">post</a> far far away, the mission was to add &#8220;child&#8221; objects to a parent object using a modal data entry form. Besides, I think the modal data entry form makes for a better user experience. Adding a new row of data entry fields would be a little subtle, don&#8217;cha think? If you pop up a modal form in front of the user, there&#8217;s no confusion about what&#8217;s going on. It&#8217;s very clear (I hope, anyway) that the user is supposed to provide data for a <code>Pilot</code> and add it to the list.</p>
<h2>Reference</h2>
<ul>
<li><a href="http://railscasts.com/episodes/197-nested-model-form-part-2">Railscast 197</a> was instrumental in getting me started with <code>accepts_nested_attributes_for</code> and <code>fields_for</code>.</li>
<li>The source code for the Starfighter Recognition Guide can be found <a href="https://github.com/jeffjohnson9046/nested-form">here</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/02/rails-3-2-a-nested-form-demo-part-3-were-starting-our-attack-run/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails 3.2: A Nested-Form Demo, Part 2: Accelerate to Attack Speed!</title>
		<link>http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/</link>
		<comments>http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/#comments</comments>
		<pubDate>Thu, 24 Jan 2013 19:14:03 +0000</pubDate>
		<dc:creator>Jeff Johnson</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Rails 3.2]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.fairwaytech.com/?p=3547</guid>
		<description><![CDATA[Overview In our previous post, our intrepid heroes were hurtling headlong into the trenches of the Starfighter Recognition Guide. They maneuvered through the superstructure of the application, setting up a [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>In our <a href="http://www.fairwaytech.com/?p=3454">previous post</a>, our intrepid heroes were hurtling headlong into the trenches of the Starfighter Recognition Guide. They maneuvered through the superstructure of the application, setting up a relationship between themselves (the <code>Pilots</code>) and the <code>Ships</code> they fly. In this post, our ace Rebel pilots will make their approach to the surface of our application.</p>
<h2>The Controller</h2>
<p>Because all of the heavy lifting is being handled by the ActiveRecord configuration defined in our domain model, the controller for the <code>Ship</code> model is pretty standard fare. As a quick refresher, here&#8217;s what the <code>create</code> method in the <code>ships_controller</code> looks like:</p>
<pre class="brush:ruby">  def create
    @ship = Ship.new(params[:ship])

    if @ship.save
      redirect_to(ships_path, :notice =&gt; "The <strong>#{ @ship.name }</strong> ship has been saved successfully.")
    else
      render(:new, :error =&gt; @ship.errors)
    end
  end</pre>
<p>If you&#8217;re interested in looking at the controller in its entirety, you can check it out <a href="https://github.com/jeffjohnson9046/nested-form/blob/master/app/controllers/ships_controller.rb">here</a>.</p>
<p><span id="more-3547"></span></p>
<h2>The Helper Methods</h2>
<p>Taking a cue from the <a href="http://railscasts.com/episodes/197-nested-model-form-part-2">Railscast</a>, I&#8217;ve added a couple of helper methods to make my life a little easier:</p>
<p><strong>app/helpers/application_helper.rb:</strong></p>
<pre class="brush:ruby">module ApplicationHelper
  def link_to_remove_fields(name, f, options = {})
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)", options)
  end

  def link_to_add_fields(name, f, association, options = {})
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index =&gt; "new_#{ association }") do |builder|
      render(association.to_s.singularize + "_fields", :f =&gt; builder)
    end

    link_to_function(name, "add_fields(this, \"#{ association }\", \"#{ escape_javascript(fields) }\")", options)
  end
end</pre>
<p>The code above is lifted pretty much verbatim from the <a href="http://railscasts.com/episodes/197-nested-model-form-part-2?view=asciicast">Railscast</a>, but I still think it&#8217;s worth going over:</p>
<ul>
<li><strong><code>link_to_remove_fields:</code></strong> This method will create a hidden <code>_destroy</code> field (which tells us whether or not the record should be deleted) and a hyperlink that will invoke a javascript method to update our <code>_destroy</code> field.</li>
<li><strong><code>link_to_add_fields:</code></strong>This method will:
<ul>
<li>Create a new instance of our <em>association</em> object (a new <code>Pilot</code> in this case).</li>
<li>Builds a form that we can use to edit our new <code>Pilot</code> object.</li>
<li>The <code>:child_index</code> will be a placeholder that will be replaced by a unique value generated in javascript (more on that in a minute).</li>
<li>Build a hyperlink containing a form for our <code>Pilot</code> object.</li>
</ul>
</li>
</ul>
<h2>The <code>fields_for</code> Method</h2>
<p>Let&#8217;s take a look at what&#8217;s going on with the second and third lines of <code>link_to_add_fields</code> (lines 8 and 9 in the code shown above). We&#8217;re using the <code><a href="http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for">fields_for</a></code> method to build the <code>Pilot</code> input fields for us. At a high level, the <code>fields_for</code> method allows us to build an HTML form without the &lt;form&gt; tags. That means we can put our fields in the &#8220;parent&#8221; form without any problems.</p>
<p>The <code>fields_for</code> method takes a few parameters:</p>
<ul>
<li><strong><code>record_name</code>:</strong> The name of the type of record we want to create. In our case, we&#8217;ll pass &#8220;Pilots&#8221; for this parameter.</li>
<li><strong><code>record_object</code>:</strong> An instance of the object we want to add/edit. In our case, this will be a <code>Pilot</code> object. We created a new <code>Pilot</code> object on the previous line of our <code>link_to_add_fields</code> method (line 7 in the code shown above).</li>
<li><strong><code>options</code>:</strong> Any options that we might want to pass to the <code>fields_for</code> method. In our case, we want a way to uniquely identify each <code>Pilot</code> we create. So, we use a <code>:child_index</code>, and set it to a &#8220;placeholder&#8221;. For this specific example, our placeholder text will be &#8220;new_pilots&#8221;. This placeholder will be replaced with a unique identifier when the form is shown (i.e. when the <code>add_fields</code> javascript method is called).</li>
</ul>
<p>In our <code>fields_for</code> block, we&#8217;re asking it to render our <code><a href="https://github.com/jeffjohnson9046/nested-form/blob/master/app/views/ships/_pilot_fields.html.erb">_pilot_fields.html.erb</a></code> partial view. Observe the second parameter, <code>:f =&gt; builder</code> is the parent form (i.e. the form that contains the input fields for the <code>Ship</code> we&#8217;re working with). This means that the <code>Pilot</code> fields rendered in our call to <code>fields_for</code> will be a part of the &#8220;Add a Ship&#8221; form, which is exactly what we want.</p>
<p>At this point, our <code>fields</code> variable should look like a bit like this (tidied up so it can actually be read):</p>
<pre class="brush:html">
<div id="new-pilot-fields" class="modal fade" data-backdrop="static">
<div class="modal-header"><button class="close" type="button" data-dismiss="modal">×</button>
<h3>Add a Pilot</h3>
</div>
<div class="modal-body">
<fieldset>
<div class="control-group"><label class="control-label" for="ship_pilots_attributes_new_pilots_first_name">First name</label>
<div class="controls"><input id="ship_pilots_attributes_new_pilots_first_name" class="input-xlarge field" type="text" name="ship[pilots_attributes][new_pilots][first_name]" size="30" /></div>
</div>
<div class="control-group"><label class="control-label" for="ship_pilots_attributes_new_pilots_last_name">Last name</label>
<div class="controls"><input id="ship_pilots_attributes_new_pilots_last_name" class="input-xlarge field" type="text" name="ship[pilots_attributes][new_pilots][last_name]" size="30" /></div>
</div>
<div class="control-group"><label class="control-label" for="ship_pilots_attributes_new_pilots_call_sign">Call sign</label>
<div class="controls"><input id="ship_pilots_attributes_new_pilots_call_sign" class="input-xlarge field" type="text" name="ship[pilots_attributes][new_pilots][call_sign]" size="30" /></div>
</div>
<input id="ship_pilots_attributes_new_pilots__destroy" class="field" type="hidden" name="ship[pilots_attributes][new_pilots][_destroy]" value="false" /></fieldset>
</div>
<div class="modal-footer"><button id="addButton" class="btn btn-primary" title="Add this Pilot to the list of Pilots that are assigned to this Ship." type="button" data-dismiss="modal">Add</button> <button id="cancelButton" class="btn btn-inverse" title="Close this screen without adding the Pilot to the list." type="button" data-dismiss="modal">Cancel</button></div>
</div>
<script type="text/javascript">// <![CDATA[
pilotFieldsUI.init();
// ]]&gt;</script>
</pre>
<p>In the last line of the <code>link_to_add_fields</code> method (line 12 in the code above), we hand off the contents of the <code>fields</code> variable to the <code>link_to_function</code> method. The <code>link_to_function</code> method is setting up a link that will call our <code>add_fields</code> javascript method (described in the next section). The <code>fields</code> value will be used as the <code>content</code> parameter of the <code>add_fields</code> method.</p>
<h2>The Javascript</h2>
<p>What&#8217;s a web app without a little javascript? Our helpers shown above make use of the Rails built-in <code>link_to_function</code> helper. The <code>link_to_function</code> will be used to call the javascript methods shown below.</p>
<p><strong>app/assets/javascripts/application.js:</strong></p>
<pre class="brush:javascript">function remove_fields(link) {
    $(link).prev("input[type=hidden]").val("1");
    $(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
    var new_id = new Date().getTime();
    var regex = new RegExp("new_" + association, "g");
    $(link).parent().after(content.replace(regex, new_id));
    $('#new-pilot-fields').modal('show');
}</pre>
<p>Again, the code shown above comes pretty much verbatim from the <a href="http://railscasts.com/episodes/197-nested-model-form-part-2">Railscast</a>. The <strong>remove_fields</strong> function is pretty straightforward:</p>
<ol>
<li>Find the hidden input field that comes before our &#8220;Remove&#8221; (our <code>_destroy</code> field) link and set it&#8217;s value to 1 (i.e. <code>true</code>, meaning we want ActiveRecord to delete this record for us).</li>
<li>Find the closest element that has a <code>class="fields"</code> (in our case, this will be a <code>&amp;ltTR&gt;</code> element) and hide it. Presto! As far as the UI is concerned, we&#8217;ve deleted a <code>Pilot</code>!</li>
</ol>
<p>The <strong>add_fields</strong> function is a little more involved, but there&#8217;s nothing too fancy:</p>
<ol>
<li>Generate an arbitrary unique id based on the current time.</li>
<li>Build a regular expression that will search for &#8220;new_&#8221; + [<em>whatever the name of our <code>association</code> is</em>] (&#8220;new_pilots&#8221; in our case).</li>
<li>Search through our <code>content</code> (the string that represents our <code>Pilot</code> form) and replace &#8220;new_pilots&#8221; with the unique id we generated in Step 1.</li>
<li>Add the <code>Pilot</code>form to the DOM.
<ul>
<li>To be very clear, the HTML shown in the description of the <code>fields_for</code> method will be added to our Add a Ship screen (which we haven&#8217;t seen yet, but trust me &#8211; it&#8217;s on its way).</li>
</ul>
</li>
<li>Display the <code>Pilot</code>form as a modal popup.
<ul>
<li>The <code>modal</code> method comes from <a href="http://twitter.github.com/bootstrap/javascript.html#modals">Twitter Bootstrap</a>.</li>
</ul>
</li>
</ol>
<p>Now, when a user clicks our &#8220;Add a Pilot&#8221; link (which we&#8217;ll see in the next article), a modal form with our <code>Pilot</code> input fields will appear. Hooray!</p>
<h2>Summary: Cut the Chatter, Red 2!</h2>
<p>We&#8217;re bouncing through the magnetic field with our deflectors on. While we haven&#8217;t started our attack run on the views yet, our approach is set up &#8211; the code in this post will make setting up our views a whole lot easier. In our next installment, we&#8217;ll switch on our targeting computers and attack the views. Before they know it, our Rebels will have a full-fledged Starfighter Recognition Guide with which to record their exploits and tales of derring-do.</p>
<p>Stay on target!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fairwaytech.com/2013/01/rails-3-2-a-complex-form-with-modal-data-entry-part-2-accelerate-to-attack-speed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
