F# Journey: Course 2 – Type Inference

Back to: F# Journey: Course 1 – Immutable Values

You probably know type inference already from C#. But in F# it’s like magic! You don’t have to define the type quite often. The compiler will automatically find out.

Let’s start with some examples:

let a = 1
// or
let plus a b = a + b

“a” is in that case of type “int”. The “plus” functions accepts 2 parameters (a,b) of type int and the return value is automatically treated as int. (I will cover functions in one of the next courses)

But if you want “double” instead of “int” then you can define the type explicitly.

let (a : double) = 4.0
// Or
let plus' (a : double) (b : double) = a + b

“a” and “b” and the function return value are of type double.

Now let’s output the values with the F# “printfn” function.

let a  = 4
printfn "Value of a: %A" a
printfn "Value of a: %d" a
printfn "Value of a: %s" a

The first and second printfn calls will work as expected. But the last one will not work. Your code will not compile at all!
The compiler brings this message: “This expression was expected to have type string
This because the printfn “%s” expects a value of type string. But in our case “a” is of type int.

No let’s have a look at our “plus” function.

let plus a b = a + b
printfn "Plus result: %A" (plus 1 2)
printfn "Plus result: %d" (plus 1 2)
printfn "Plus result: %s" (plus 1 2)

As you may guess, we get the same error again. But now let’s remove the first two printfn calls and try again.

let plus a b = a + b
printfn "Plus result: %s" (plus 1 2)

Yes.. it will still not work but this time we get a different error message: “The type ‘string’ does not match the type ‘int’
Because we want to output a string (%s) F# thinks that the return value of “plus” is of type string. The compiler changed the signature of the function from
int -> int -> int
to
int -> int -> string
Now we can even change the type of the parameters when calling the plus function to string -> string -> string

let plus a b = a + b
printfn "Plus result: %s" (plus "1" "2")

This compiles but the logic of this function doesn’t work as expected. The output is “Plus result: 12″ and not 3. We are just concatenating two strings.
This is the right way how to call the printfn when the types are not defined.

let plus a b = a + b
printfn "Plus result: %d" (plus 1 2)

Even for custom types/records (will be covered in next courses) F# offers some nice features.
The first line in the code below defines a record type and the second line instantiates an object. The type “person” is inferred based on the properties “id” and “name”.

type person = { id : int; name : string }
let personRecord = { id = 1; name = "Darko" }

My F# Journey

After working 4-5 years mainly with object-oriented programming languages like C#, I thought it’s a good time to dive into other programming paradigms. For example: Functional programming -> F#!
Based on the “Indeed Trends” (see at the bottom of this post) we see that the market is still not seeking a lot F# or Scala developers. But I think this will change in the future.

As I progress on my F# “journey” I will write some series of posts here. I hope you’ll enjoy the trip. ;)

Courses:

F# Journey: Course 1 – Immutable Values

F# Journey: Course 2 – Type Inference


Indeed Trends

F# Journey: Course 1 – Immutable Values

Back to: F# Journey

By default all variables in F# are immutable. Hence.. we can not call them “variables” anymore. The term “value” fits better.
Here is a simple example of an immutable value:

let val1 = 2
printfn "%d" val1

Now when you try to change the value like in the code below (line 2) the compiler will bring this warning:
This expression should have type ‘unit’, but has type ‘bool’. Use ‘ignore’ to discard the result of the expression, or ‘let’ to bind the result to a name.

let val1 = 2
val1 = 4
printfn "%d" val1

The compiler does not even recognize this as an valid value assignment! “val1 = 4″ is a valid comparison, and the compiler says that you either have to save the result in a value with the ‘let’ function or to ignore it with ‘ignore’.

But how can I change the value? Mark the value as mutable and use the <- for the assignment.

let mutable val1 = 2
val1 <- 3
printfn "%d" val1

Going back to the compiler message: If you do an comparison as in the code above you can store the result in a value.

let val1 = 2
let comp = val1 = 4
printfn "%b" comp

The result will be "false". (Well at least the value comparison works the same way as in C#) :)

Functions in F# always have return values. F# will automatically determine the return value. In our case here "val1 = 4", the return value is of type 'bool'. If we don't need the return at all, then we can simply ignore it.

let val1 = 2
val1 = 4 |> ignore
printfn "%d" val1

Immutable values in functional programming have some advantages:
- Easier to share state. Locking not needed for immutable data.
- We have less side effects. Once the value is set it can't be changed during the program flow.
- As an developer, you are more aware of what your code is changing or not.
- The code is more clear. Let's take this C# code as an example:

var myContract = new InsuranceContract(startDate, endDate);
myContract.Extend(DateTime.Now.Add(10));

Now guess what the state of myContract object is... Does "Extend" change the endDate property? Or does it create a new InsuranceContract instance? We don't know.
In F# it's clear. Because we can't change the endDate value, the "Extend" function has to return a new InnsuranceContract instance.

Next: F# Journey: Course 2 - Type Inference

WPF MVVM Busy Message With Ambient Context

Every .NET developer has already used an Ambient Context without knowing it. A typical Ambient Context is:

using (var tx = new TransactionScope())
{
    ....
}

The pattern is not very well known. Here is one good description I found: The Wandering Glitch – Ambient Context

I found this pattern very useful for displaying progress/busy messages in WPF applications. The following example shows how to build a simple Ambient Context for it.
The usage of it is slightly different than in the example above with the TransactionScope. I explain later on why.
(The code is on GitHub)

Usage of the BusyContext in a WPF/MVVM application:
The follow code has two nested BusyContext objects. The creation of a context causes the UI to change the progress text. After disposing a context, the previous context message is displayed.

BusyContext

BusyContext


You see, the usage of the BusyContext is fairly easy. The CreateBusyContext is a helper method in my base viewmodel class.
Here you see that the BusyContext constructor takes three parameter. Context store, busy message and a Action which gets triggered after creating and disposing the context. (Why I’m using a context store is explained at the end of the blog post.)

protected BusyContext CreateBusyContext(string message)
{
	var context = new BusyContext(this.BusyContextStore, message, this.NotifyBusyChanged);
	return context;
}

I put the most important classes here. The whole code is on GitHub.

The ContextStore is responsible for storing the contexts. The Current property returns the “deepest” (in nested contexts) context data.

public class ContextStore<TData> : IContextStore<TData>
{
	private Stack<AmbientContext<TData>> _Store = new Stack<AmbientContext<TData>>();

	public TData Current
	{
		get
		{
			if (_Store.Any())
				return _Store.Peek().Data;
			return default(TData);
		}
	}

	public void Add(AmbientContext<TData> context)
	{
		this._Store.Push(context);
	}

	public void Remove()
	{
		this._Store.Pop();
	}
}

The AmbientContext is the base class for the BusyContext:

public abstract class AmbientContext<TData> : IDisposable
{
    private IStoreWriter<TData> _Store;

    private Action _OnDispose;

    public TData Data { get; private set; }

    public AmbientContext(IStoreWriter<TData> store, TData data, Action onContextChange = null)
    {
        this.Data = data;
        _Store = store;
        this._OnDispose = onContextChange;

        _Store.Add(this);
        this.NotifyChange();
    }

    private void NotifyChange()
    {
        if (this._OnDispose != null)
            this._OnDispose();
    }


    public virtual void Dispose()
    {
        _Store.Remove();
        this.NotifyChange();
    }
}

My BusyContext looks quite simple.

public class BusyContext : AmbientContext<string>
{
	public BusyContext(IStoreWriter<string> store, string busyMessage, Action onContextChange = null)
		: base(store, busyMessage, onContextChange)
	{ }
}

Reason why the usage of my BusyContext is slightly different compared to other contexts:
- Undefined storage scope:
I don’t want to restrict the context data to a specific scope. Restricting the context to the current Thread [ThreadStatic] (for example) would mean that I could display only one busy message. This is a huge restrication in a non-single window application like MDI/TDI. So therefore, you have to define a storage. This gives a lot of flexibility. For example: You could show multiple busy messages from same ViewModel in same time by defining two different stores.
- No static classes/properties for getting the current busy message:
Static properties like Thread.CurrentPrincipal return the data of the current Ambient Context. In one way, this is very helpful. But it has some drawbacks when it comes to the unit testing. In my example the data of the current Ambient Context can be retrieved from the store object. The store object is a simple class an can be mocked in unit tests.

First Time WCF Client Contracts = Nightmare!

In one of my projects (WPF, WCF) we are working with server and client side entities. Although the entities look very similar, we had some reasons to separate them:
- Client side entities require more logic
-> Implementation of INotifyPropertyChanged
-> Implementation of IEditableObject
-> Restore handling (When user cancels edit)
All these functionalities were implemented in a base class in the client. When working with WCF and WPF I always prefer the share the service contract interfaces rather than creating client proxies. (The code is cleaner and it gives us more flexibility.) But in this project, we couldn’t share the contracts, because the WCF contract interfaces always references the service side entities.
To solve the problem I came up with different approaches:

Sharing the service contracts between server and client (or creating a client proxy) and using a mapper mapper framework (AutoMapper) to map the entities into our client entities.
Adding the service contracts as “linked” files in the client and working with compilation conditions to “swap” the server side contract/entity namespaces. (Or using the same server entity namespace in the client).
Generating with a script the server contracts + entities in the client. Exchanging the base class of the entities. Deserializing the retrieved data directly into client entities.

I decided to implement the third approach because:
- We don’t need and extract step for mapping between server and client entities.
- Having full control over the contracts and entities. (In case of linked files we still have some restrictions)
- “Real” client entities with client specific base class.

For the implementation of these I decided to use T4. My T4 script runs through my server contracts + entities and generates in the client the “duplicate” code. All generated interfaces classes are partial. So we still can add some additional code. And because the DataContractSerializer relies on the contract namespace and NOT on the CLR namespace, we can use client specific namespace for the generated files. To make sure that all server/client contract interfaces and entities are using the same data contract namespace, I added the ContractNamespace attribute in both assemblies.

// Client assembly
[assembly: ContractNamespace("http://blog.micic.ch/contractexample", ClrNamespace = "ContractExampleClient")]

// Server assembly
[assembly: ContractNamespace("http://blog.micic.ch/contractexample", ClrNamespace = "ContractExampleService")]

So, and here is some very important information!

The DataContractSerializer creates instances of the client entities without calling the constructor. (System.Runtime.Serialization.FormatterServices.GetUninitializedObject) Initialization code must be placed in a [OnDeserializing] or [OnDeserialized] method.
The order of the entity properties (DataMembers) must be the same as on the server. By default, the serializes orders the properties alphabetical. BUT if you have a base class, the serializer orders first the properties of your base class alphabetical and then the properties of the child class. (It’s possible to explicitly define the order -> [DataMember(Order=...)] But that’s too much work for an lazy developer :)

Unfortunately… the WCF error messages aren’t very helpful when your client contracts are wrong. In worst case, you don’t get any exception. I lost at the end 6 hours until I found out that:
- My client entities weren’t initialized correctly because the constructor wasn’t called.
- Not all properties were initialized because the order was wrong. My client entity base class has less properties than the server entity base class. And that screwed up the ordering of the properties “in some” of the entities.

So in short. Make sure that:
- The server and client contract namespaces are the same.
- You are using [OnDeserializing] or [OnDeserialized] methods to initialize your client entity.
- The ordering of the base/child entity classes is correct.

At the end, I was very happy with the solution. The DataContractSerializer is very flexible! In our client entities we have for example ObservableCollection<> properties which are mapping to IEnumerable<> server entities. And the handling with different base interfaces, classes and generics is very good!

The first time you will struggle a little bit. But afterwards you will love to work with server and client side WCF contracts.

Here is an simplified example of your server and client code:


/////// SERVER
namespace ContractExampleService
{
    [ServiceContract]
    public interface IPersonService
    {
        [OperationContract]
        Person[] Get();
    }

    [DataContract]
    public abstract class EntityBase
    {
        [DataMember] public TKey Id { get; set; }
        [DataMember] public DateTime CreatedAt { get; set; }
    }

    [DataContract]
    public class Person : EntityBase
    {
        [DataMember] public string Firstname { get; set; }
        [DataMember] public string Lastname { get; set; }
        [DataMember] public IEnumerable
Addresses { get; set; } } public class Address : EntityBase { public string Street { get; set; } } } /////// CLIENT namespace ContractExampleClient { [ServiceContract] public interface IPersonService { [OperationContract] Person[] Get(); } [DataContract] public abstract class EditableEntity : IEditableObject { public enum EState { NotChanged = 0, Created = 1, Changed = 2, Deleted = 3 } [DataMember] public TKey Id { get; set; } [DataMember] public DateTime CreatedAt { get; set; } public EState State { get; set; } public void BeginEdit() { } public void CancelEdit() { } public void EndEdit() { } } [DataContract] public class Person : EditableEntity { [DataMember] public string Firstname { get; set; } [DataMember] public string Lastname { get; set; } [DataMember] public ObservableCollection
Addresses { get; set; } } [DataContract] public class Address : EditableEntity { [DataMember] public string Street { get; set; } } }

Partial Validation With Data Annotations

Data Annotations provide a very nice way to validate the entities. But under some circumstances, you may don’t want to validate all properties. For example, a property like “createddate” we don’t want to validate in the client layer, because the field is not set at this point. In this situation it would be good to skip the validation for “createddate”.
I wrote a Nuget packages which allows you exclude specific validations.

NugGet https://www.nuget.org/packages/DataAnnotations.PartialValidation
GitHub https://github.com/dmicic/Dmicic.DataAnnotations.PartialValidation

Here is a simple demo. Let’s say, we have an application structured in 3 layers.
Partial Validation - Demo
The Person entity has following property definitions. (See code block)
I prefer the define the “technology neutral” validation attributes in the Business layer. And all other attributes (MVC attributes, EF attributes) I place in the appropriate layer.

public class Person : EntityBase
{
    [Required]
    public string Firstname { get; set; }

    [Required]
    public string Lastname { get; set; }

    [Required]
    public string EMail { get; set; }

    [Required]
    [CreditCardNumber]
    public string CreditCardNumber { get; set; }
}

public abstract class EntityBase
{
    [Required]
    public Guid Id { get; set; }

    [Required]
    [StringLength(10)]
    public string CreatedBy { get; set; }

    [Required]
    public DateTime? CreatedDate { get; set; }

    public string ModifiedBy { get; set; }

    public DateTime ModifiedDate { get; set; }
}

Now when I create a new object of type Person in my UI layer and try to validate it, I will always get validation errors because fields like Id, CreatedBy, CreatedDate are not set. In the UI layer, I only want to validate the properties which can be mutated by the user.
Now I can use the “Partial Validation” framework and define layer specific validation requirements.

var p1 = new Person();
p1.CreditCardNumber = "23434";
p1.EMail = "wrong mail address";

Configuration.Configure()
    .For("UI")
            .Configure<Person>()
                .Property(p => p.CreatedBy).ExcludeAll() // Exclude all validations for CreatedBy
                .Property(p => p.CreatedDate).ExcludeAll() // Exclude all validations for CreatedDate
                .Property(p => p.EMail).Include(new EmailAttribute()) // Include the Email validation for EMail
                .Property(p => p.CreditCardNumber).Exclude<CreditCardNumberAttribute>(); // Exclude the credit card validation for CreditCardNumber

Configuration.Configure()
    .For("Business")
        .Configure<Person>()
                .Property(p => p.CreatedBy).ExcludeAll() // Exclude all validations for CreatedBy
                .Property(p => p.CreatedDate).ExcludeAll(); // Exclude all validations fro CreatedDate


Configuration.Configure()
    .For("DataAccess")
        .Configure<Person>()
            .Property(p => p.CreditCardNumber).ExcludeAllBut<RequiredAttribute>(); // Exclude all except the required validation

var UiResult = PartialValidator.Validate(p1, "UI");
var BusinessResult = PartialValidator.Validate(p1, "Business");
var DataAccessResult = PartialValidator.Validate(p1, "DataAccess");

Here are the result of these layer specific validations.
Partial Validation - Validation Result

This is it! ;)

Here is an example which covers all Partial Validation functions:

Configuration.Configure()
    .For("Layer/Environment")
        .Exclude<MyFirstValidationAttribute>()                  // Exclutions for all entities in this environment
        .Exclude<MySecondValidationAttribute>()
        .Configure<EntityOne>()                                 // Specification for "EntityOne"
            .Property(p => p.Property1)
                .ExcludeAll()                                   // Exlcude all validations for "Property1"
                .Include(new MyFirstValidationAttribute())      // Include specific validation attribute
        .Configure<EntityTwo>()                                 // Specification for "EntityTwo"
            .Property(p => p.Property1)                         // Exclude Required and StringLength validation attribute for "Property1"
                .Exclude<RequiredAttribute>()
                .Exclude<StringLengthAttribute>()
        .Configure<EntityThree>()                               // Specification for "EntityThree"
            .Property(p => p.Property1)                         // Exclude all except "Required" for "Property1"
                .ExcludeAllBut<RequiredAttribute>();

Owin And Razor-enabled MVC Application Framework

I wrote a very tiny MVC Application Framework which runs on OWIN. This Framework uses the Razor engine for the view rendering. It’s very fast because the overhead is quite small. There are just a few lines of code which are between the Owin HTTP server request and the application logic.
For that it doesn’t contain so much functionality as ASP.NET MVC Framework.
This framework handles only HTTP GET requests. HTTP POST is not supported for now.
The code is on GitHub: Razor-enabled MVC Application Framework
The architecture is as follows:

Razor Server - Architecture

Razor Server – Architecture


The whole thing runs in OwinHost.exe and uses the HttpListener. (Well, it can be exchanged due IIS/Self Host and SystemWeb as server.)
The Razor-enabled MVC Application Framework itself handles the requests and invokes based on the request path (owin.requestPath) the appropriate Controller-Action. The Controller-Action result is passed to the Razor engine. The engine loads the view definition and parses it with data. Afterwards the generated HTML view is written to the response body (owin.ResponseBody). That’s it.

The code below demonstrates how to build an application based on the Razor-enabled MVC Application Framework.
The solution is structured as follows:

Razor Demo App

Razor Demo App

First we have to create a Startup class and configure the routes.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use(new Func<object, object>(
            x => new Middleware(new List<Route> 
            {
                // Your routes
                new Route("Person", typeof(PersonController))
            })
        ));
    }
}

Now define your model. In this example: “Person”

public class Person 
{ 
    public string Firstname { get; set; } 
}

Now define your controller.

public class PersonController
{
    public IView Index()
    {
        return new View("Index", new Person() { Firstname = "Max" });
    }

    public IView All()
    {
        var result = new List<Person>();

        for (var x = 0; x < 150; x++)
        {
            result.Add(new Person() { Firstname = "Max " + x });
        }

        return new View("All", result);
    }
}

Almost finished. Now create the views with the Razor syntax.

<html>
  <head>
    <title>Razor Server</title>
  </head>
  <body>
      @foreach (var person in Model)
      { 
        <b>@person.Firstname</b><br />
      }
  </body>
</html>

And

<html>
  <head>
    <title>Razor Server</title>
  </head>
  <body>
    <b>@Model.Firstname</b>
  </body>
</html>

This is it! Run the application an execute some HTTP requests.

Razor Server HTTP Requests

Razor Server HTTP Requests

Generating Files With Razor Engine

The Razor engine can be used outside of ASP.NET. Beside the cool syntax, it’s a very fast engine! And it’s quite easy to use.
In my example I generate a XML file based on a razor template.
(You have to install the NuGet package “RazorEngine”.

This is my model which I use for the rendering:

public class Person
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

public class ReportModel
{
    public DateTime Date { get; private set; }
    public IList<Person> People { get; private set; }

    public ReportModel()
    {
        this.Date = DateTime.Now;
        this.People = new List<Person>();
    }
}

This is the Razor syntax based template.


	@Model.Date
	@foreach (var person in Model.People)
	{
		
			@person.Firstname
			@person.Lastname
		
	}

And here is the code which parses the Razor template and generates an xml file.

var reportData = new ReportModel();

for (var x = 1; x <= 10000; x++)
{
    reportData.People.Add(new Person() 
            { 
                Id = x, 
                Firstname = "Darko " + x, 
                Lastname = "Micic " + x 
            });
}

using (var writer = new StreamWriter(@"C:\output.xml"))
{
    writer.Write(RazorEngine.Razor.Parse<ReportModel>(
				new StreamReader(@"C:\template.xml").ReadToEnd(), 	
				reportData));
}

Cheers!

Demistifying async/await

Microsoft introduced new keywords in C# 5.0 for asynchronous programming. Before C# 5.0 async. programming was only possible with .NET Framework classes. Now it’s implemented in the C# language itself. Here is a simple demo which shows how the keywords can be used.

public async Task<string> DownloadFromWeb()
{
    var client = new HttpClient();
    return await client.GetStringAsync("http://blog.micic.ch");
}

private async void Button1_Click(object sender, RoutedEventArgs e)
{
    var result = await DownloadFromWeb();
    MessageBox.Show("Finished. Length: " +  result.Length);
}

private void Button2_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("UI is not freezed");
}

But await! How does it work?
Async / Await
The Button_Click event handler runs the function DownloadFromWeb. DownloadFromWeb executes an HTTP request on a website. The “GetStringAsync” is a asynchronous method. And the DownloadFromWeb awaits the response, the control flow goes back to the caller function at the await statement. In that case: Button_Click.
But because the Button_Click function awaits the response from DownloadFromWeb, the control flow goes back to the parent. Now the control is in the message loop. The thread is not locked.
Now after the GetStringAsync function finished the work, the control flow jumps to the await statement (green arrows) and executes the rest of the DownloadFromWeb. Afterwards, the control flow is again in the message loop. Now because the DownloadFromWeb task has been completed, the control flow jumps to the await DownloadFromWeb (blue arrows) statement and executed the rest of the Button_Click event handler. And while the control flow is in the message loop, the UI thread (in that case) is not freezed! ;)

Generate Layered ASP.NET MVC Web Applications

I created a generator which generates Business and Data Access functionalities based on your domain model. I’ve build this generator + template because I think it makes sense even in smaller web applications to structure the code well. Also when the web application is very simple we never know which requirements we encounter in the future.
The advantages of my generator and template are:

  • Code generation based on domain model. (Saves you time!)
  • Flexibility. The generator creates partial classes. You can easily extend them.
  • Seperation of concerns.
  • Testability. No direct instantiation of objects. Abstraction with interfaces.
  • Concentrate on the core (Business, UI) of your application.
  • Running application in few minutes!

The solution template contains following projects:

WebUI ASP.NET MVC project.
Business Contains the domain model and the business logic.
DataAccess Data access with ADO.NET EF Code First approach.
Bootstrapper Boostrapping. (Dependency Injection with StructureMap)


T4 Generator Architecture

How does it works?
Prerequisite:

1)
Download the solution from GitHub. https://github.com/dmicic/Dmicic.Template.ApplicationGeneration
(You need only the “Templify” folder.”)
2)
Open the SetupProject.cmd and set the “DestinationFolder”, “TemplateFolder” and “SolutionName” variables.
AppGen SetupProject.cmd
Now run the SetupProject.cmd file.

3)
AppGen Domain Model
Open the solution and define your domain models (in this tutorial “Person.cs”) in the Business project under the folder “Domain”. Then execute the “App_Generator.tt” file. This file generates in this example following files:
Dmicic.WebShop.DataAccess (under .generated folder)

PersonConfiguration.generated.cs ADO.NET EF entity type configuration for Person domain model.
ObjectContext.generated.cs ADO.NET EF DbContext class.
PersonRepository.generated.cs Generic repository class for Person domain model.

Dmicic.WebShop.Business (under ApplicationService\.generated folder)

IPersonRepository.generated.cs Person repository interface. (Implementation is in Dmicic.WebShop.DataAccess project)
IPersonApplicationService.generated.cs Person application service interface contract.
PersonApplicationService.generated.cs Person application service implementation.

4)
The base classes for the repositories and application services contains CRUD functionalities. If you need additional functions you can create a partial class for the appropriate domain model repository or application service.
Here is an example: I’ve created a partial interface “IPersonApplicationService” and a class “PersonApplicationService” in the folder Dmicic.WebShop.Business\ApplicationService.

public partial class PersonApplicationService
{
    public IEnumerable<Person> FindByFirstname(string firstname)
    {
        return this.Repository.GetByCondition((person) => person.Firstname == firstname);
    }
}

public partial interface IPersonApplicationService
{
    IEnumerable<Person> FindByFirstname(string firstname);
}

5)
Now build your application. I recommend to inject the application services. In this example the services are passed as constructor parameters automatically. Here is an example of a simple ASP.NET MVC Controller.

public class SearchController : Controller
{
    private IPersonApplicationService Service { get; set; }
    private IUnitOfWork UnitOfWork { get; set; }

    public SearchController(IUnitOfWork unitOfWork, IPersonApplicationService service)
    {
        this.UnitOfWork = unitOfWork;
        this.Service = service;
    }

    public ActionResult Index()
    {
        var foundPeople = this.Service.FindByFirstname("Darko");
        return this.View(foundPeople);
    }

    public ActionResult SaveSomething()
    {
        // Start transaction. (Optional)
        using (var tx = this.UnitOfWork.StartTransaction())
        {
            var person1 = this.Service.Create();
            person1.Id = Guid.NewGuid();
            person1.Firstname = "Firstname 1";
            person1.Lastname = "Lastname 1";

            this.UnitOfWork.Commit();
            tx.Complete();
        }

        return this.View();
    }
}

When you run the web application, the ObjectContext installs the Database and querying etc will work from the first compile! ;)

Have fun with the generator/template.
Feedback is appreciated!