Introduction to MVP in ASP .NET

First we’ll remember a few things about the pattern Model View Presenter. The model represents your business rules, or business model. The View is the form that the user will be using, and the Presenter will be the connection between the Model and the View. To simplify things, we are going to say that the View’s responsibilities are two: to expose the data to the user and the presenter, and to notify of events to the presenter. The presenter will act upon this events based on the View state, and consume the model in order to update the state of the view.

Let’s look at the first example, we need a page where I can see my account settings. We’ll need the UserName and the roles of our account. We’ll start by building our View:

<form id="form1" runat="server">
 <label>User name</label>
 <asp:Label runat="server" ID="lblUserName"></asp:Label>
 <br />
 <label>Roles</label>
 <ul>
  <%= RenderRoles() %>
 </ul>
</form>

Now we need a way to expose the UserName and Roles to the presenter. In this case we’ll create some properties in the code behind:

public string UserName
 {
 get { return lblUserName.Text; }
 set { lblUserName.Text = value; }
 }

 public string[] Roles
 {
 get { return (string[])ViewState["Roles"]; }
 set { ViewState["Roles"] = value; }
 }

This is what we want to expose to the presenter. So we’ll create an IAccountView like that looks like this:

 interface IAccountView
 {
  string UserName { get; set; }
  string[] Roles { get; set; }
 }

In order to render the Roles we’ll add the following method:

 protected string RenderRoles()
 {
  if (Roles != null)
 {
  var sb = new StringBuilder();
  foreach (var role in Roles)
   sb.AppendLine(string.Format("<li>{0}</li>", role));
  return sb.ToString();
 }
 else
  return string.Empty;
 }

Now we need a Presenter for our view. The only thing we need to notify to the presenter is that we are rendering for the first time, and we need to load the form. So we’ll need a presenter that conforms to this interface:

 interface IAccountPresenter
 {
  void OnInitialize();
 }

There’s a very good reason for naming the method OnInitialize and not Load, or Initialize. We’ll make a design choice here and whenever it’s possible (and convenient) we’ll start our presenter interface methods with “On” to illustrate that it’s an event. This will make the presenter code cleaner by dividing notification methods from other helper methods.

So here is how the Page_Load might look like:

 IAccountPresenter presenter;
 protected void Page_Load(object sender, EventArgs e)
 {
  presenter = new AccountPresenter(this);
  if (!IsPostBack)
  {
   presenter.OnInitialize();
  }
 }

And that’s it for our View for now. Now let’s build this AccountPresenter. Notice that the Presenter depends on the View, and that’s why it receives the view in the constructor. As for the OnInitialize, that’s where the presenter has to go over to the model to get that information and manipulate the view in order to update the status of the View. Here’s our presenter:

 public class AccountPresenter : IAccountPresenter
 {
  IAccountView view;
  AccountModel model;
  public AccountPresenter(IAccountView account)
  {
   view = account;
   model = new AccountModel();
  }

  internal void OnInitialize()
  {
   view.UserName = model.GetUserName();
   view.Roles = model.GetUserRoles(view.UserName);
  }
 }

How the model retrieves the user name and the roles doesn’t matter, that’s your business rules. You might even have a return “Gustavo”; hardcoded in the GetUserName as far as I’m concerned ;)

Up to here, we have the same MVP example you’ll find everywhere. The advantages so far are: that you have your model out of your code behind; you have your presenter and view loosely coupled so you could even mock or IoC these; and you divided the code and the classes responsibilities thus minimizing the classes complexity. But there are a lot of other reasons to use MVP. Let’s see how we can start building up this MVP example a little.

Base Interfaces and Base Classes

I usually consider it a good practice to have both base interfaces and base classes in my code. It adds extensibility and reusability points in the code. I think we could use some base interfaces in here.

IView

IView will contain whatever we want to expose to every presenter. The only thing that comes to my mind right now is the Title of the page, but we can get anything like stuff you would usually keep in the session or take from the MasterPage.

 public interface IView
 {
  string Title { get; set; }
 }

IPresenter

The view depends on the presenter, and from the view’s perspective the first thing we need from a presenter is to be able to set its view. So our IPresenter will have a method for doing this (here is our first exception to our “On” prefix rule):

 public interface IPresenter
 {
  void SetView(Views.IView view);
  void OnInitialize();
 }

BaseView

BaseView will be our base class for all our views. This class will implement IView, and will have some of the things we do in every page. Such as the Page_Load method. There’s a high chance that for every form we do using MVP we’ll want to create our presenter in the Page_Load, and set the View pretty much like we did in our AccountView. So let’s refactor our code so we don’t have to handle this in every codebehind.

 public abstract class BaseView<T> : Page, IView where T : IPresenter, new()
 {

  public virtual T Presenter { get; set; }
  protected void Page_Load(object sender, EventArgs e)
  {
   Presenter = new T();
   Presenter.SetView(this);
   if (!IsPostBack)
   {
    Initialize();
    Presenter.OnInitialize();
   }
  }
  public virtual void Initialize(){}
 }

We could easily get rid of the “new()” constraint over T if we had an IoC container, but in this case for the sake of simplicity we’ll omit that part.

BasePresenter

Our BasePresenter will implement the IPresenter and solve the SetView so we don’t have to take of this in every presenter.

 public class BasePresenter<T> : IPresenter where T : IView 
 {
  public T View { get; set; }
  public virtual void SetView(Views.IView view)
  {
   if (view == null)
   throw new ArgumentNullException("view");
   if (!view is T)
    throw new ArgumentException("view parameter must be of type: " + typeof(T).Name, "view");

   View = (T)view;
  }
  public virtual void OnInitialize(){}
 }

The result

Next we should inherit IAccountView from IView, IAccountPresenter from IPresenter, Account from BaseView and AccountPresenter from BasePresenter. And here’s how Account looks like:

 public partial class Account : BaseView<AccountPresenter>
 {

  public string UserName
  {
   get { return lblUserName.Text; }
   set { lblUserName.Text = value; }
  }

  public string[] Roles
  {
   get { return (string[])ViewState["Roles"]; }
   set { ViewState["Roles"] = value; }
  }

  #region render methods
  protected string RenderRoles()
  {
   if (Roles != null)
   {
    var sb = new StringBuilder();
    foreach (var role in Roles)
     sb.AppendLine(string.Format("<li>{0}</li>", role));
    return sb.ToString();
   }
   else
    return string.Empty;
  }
  #endregion

 }

As you can see, it only has the specific implementation of IAccountView, and no Page_Load method! Now let’s look at our AccountPresenter:

 public class AccountPresenter : BasePresenter<IAccountView>
 {
  AccountModel model;
  public AccountPresenter()
  {
   model = new AccountModel();
  }

  public override void OnInitialize()
  {
   View.UserName = model.GetUserName();
   View.Roles = model.GetUserRoles(View.UserName);
  }
 }

As you can see we can take care of our Model and our events only without worrying about the SetView plumbing.

In this post we have showed how we could take advantage of MVP and base classes in order to create extensibility and reusability points for our web pages. As an example of this, we have centralized the Presenter instantiation and initialization.

Razor from a console – calling child templates

In my previous post I showed how to run a Razor template (.NET’s new view engine) from a console app in order to generate code. In this post I will demostrate how to run another razor template from within a razor template.

This is actually quiet simple, and since we already have the “RazorClient.dll” referenced in the RazorFactory code, we can achieve this with the following code (this goes inside a razor template):

Snippet

@{
	var factory = new RazorClient.RazorFactory();

	using (var template = factory.Create<RazorClient.FileWriter>(@"C:\Users\Gus\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Test2.txt"))
	{

		if(factory.Errors.Length > 0)
		{
			//do something
		}
		else
		{
			template.FilePath = @"C:\Users\Gus\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Test2.txt.out.txt";
			template.Execute();
		}
	}
}

Notice how we need to include the namespace of the classes like in RazorClient.RazorFactory.

This code being so easy led me to the idea of having a main razor file to act as a project and fire the rest of the templates. And I took advantage of the fact that we are firing the rest of the templates from a Razor file to generate a report that showed the status of each template in HTML format. Here is a sample:

Snippet

<html>
<head>
	<style type="text/css">
	.success
	{
		background-color: green;
	}

	.failed
	{
		color: white;
		background-color: red;
	}
	</style>
</head>
<body>
<h1>My project name here</h1>
<p>
Project generated on @DateTime.Now
</p>
<table>
<tr>
<td>Template</td>
<td>Status</td>
<td>Errors</td>
</tr>

<tr>
<td>Test2.cshtml</td>
@{
	try
	{
		//this is my block code.
		var factory = new RazorClient.RazorFactory();
		using (var template = factory.Create<RazorClient.FileWriter>(@"C:\Users\Gus\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Test2.txt"))
		{
 			if(factory.Errors.Length > 0)
			{
				this.Write("<td class='failed'>Failed</td>");
				this.Write("<td>");
				foreach(var t in factory.Errors)
				{
					this.Write(t);
					this.Write("<br />");
				}
				this.Write("</td>");
			}
			else
			{
				template.FilePath = @"C:\Users\Gus\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Test2.txt.out.txt";
				template.Execute();
				this.Write("<td class='success'>Successful</td><td></td>");
			}
		}
	}
	catch(Exception ex)
	{
		this.Write("<td class='failed'>Failed</td>");
		this.Write("<td>");
		this.Write(ex.ToString());
		this.Write("</td>");
	}
}
</table>
</body>
</html>

When I ran this main template, the following html was generated (you might want to tune it up a little, html design is not my thing :) ):

My project name

Project generated on 7/16/2010 10:44:33 AM

Template Status Errors
Test2.txt Successful

So in this post I showed that having a main template to fire the rest of the child templates is a good idea.

Using Razor from a Console Application

I just found out about Microsoft’s new View engine Razor. As soon as I read Scott’s post about it which is great, I wanted to investigate it. One of the things that caught my attention was the fact that Scott said that the view didn’t require to be hosted in a web application, and that executing it from a console app was possible.

So I went ahead, and few hours later of Reflector, dynamic compilation and trial and error (why not?), I figured out a way to do it.

First you need to download WebMatrix, the new MS tool for building simple websites fast and easy. We need WebMatrix so that we can pull the dlls we need in order to use Razor. After installing WebMatrix you can find the necessary assemblies in the following folder: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies. In case you don’t find them there, you can perform a Publish from WebMatrix and that will copy the dlls into the bin folder. The list of dlls we are looking for is:
Microsoft.WebPages.dll
Microsoft.WebPages.Compilation.dll
Microsoft.WebPages.Configuration.dll
Microsoft.WebPages.Helpers.dll
Microsoft.WebPages.Helpers.Toolkit.dll

Next thing we need to do is add the reference to our project of the following assemblies (you can add more if you want to access from the template cshtml or vbhtml files), and don’t forget to mark them as “Copy Always”:
System.dll
System.Core.dll
System.Web.dll
System.Web.Mvc.dll
System.Data.dll
System.Web.Extensions.dll
Microsoft.CSharp.dll
Microsoft.WebPages.dll
Microsoft.WebPages.Compilation.dll
Microsoft.WebPages.Configuration.dll
Microsoft.WebPages.Helpers.dll
Microsoft.WebPages.Helpers.Toolkit.dll
Microsoft.Data.Schema.dll

The only way I have found to execute a razor file (cshtml or vbhtml) is to parse the file with the parsers (Razor uses two parsers to parse a file, a MarkupParser, and a CodeParser, in this case I will use an HtmlMarkupParser and a CSharpCodeParser) found in Microsoft.WebPages.Compilation.Parser, and then compiling the result to a temporary assembly, and extracting the type from the new assembly. So I have wrapped this in a class I called RazorFactory like this:

Snippet

public class RazorFactory
    {
        public List<String> ReferencedAssemblies
        {
            get;
            private set;
        }
        private List<string> errors = new List<string>();
        public string[] Errors
        {
            get
            {
                return errors.ToArray();
            }
        }
        public RazorFactory()
        {
            ReferencedAssemblies = new List<string>();
            ReferencedAssemblies.Add("System.dll");
            ReferencedAssemblies.Add("System.Core.dll");
            ReferencedAssemblies.Add("System.Web.dll");
            ReferencedAssemblies.Add("System.Web.Mvc.dll");
            ReferencedAssemblies.Add("System.Data.dll");
            ReferencedAssemblies.Add("System.Web.Extensions.dll");
            ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            ReferencedAssemblies.Add("Microsoft.WebPages.dll");
            ReferencedAssemblies.Add("Microsoft.WebPages.Compilation.dll");
            ReferencedAssemblies.Add("Microsoft.WebPages.Configuration.dll");
            ReferencedAssemblies.Add("Microsoft.WebPages.Helpers.dll");
            ReferencedAssemblies.Add("Microsoft.WebPages.Helpers.Toolkit.dll");
            ReferencedAssemblies.Add("Microsoft.Data.Schema.dll");
        }
        public T Create<T>(string fileName) where T : class
        {
            using (var reader = new StreamReader(fileName))
            {
                return Create<T>(reader);
            }
        }
        public T Create<T>(TextReader reader) where T : class
        {
            var codeParser = new CSharpCodeParser();
            var markupParser = new HtmlMarkupParser();
            var parser = new InlinePageParser(codeParser, markupParser);

            var listener = new CSharpCodeGeneratorParserListener(
                    "className",
                    "ASP",
                    "System.Web.HttpApplication",
                    "linePragmaFileName",
                    typeof(T).FullName);

            foreach (var n in CodeGeneratorSettings.GetGlobalImports())
                listener.AdditionalImports.Add(n);
            parser.Parse(reader, listener);

            var option = new System.CodeDom.Compiler.CompilerParameters();
            option.ReferencedAssemblies.AddRange(ReferencedAssemblies.ToArray());
            option.GenerateExecutable = false;
            option.GenerateInMemory = true;

            var options = new Dictionary<string, string>();
            options.Add("CompilerVersion", "v3.5");

            var compiler = Microsoft.CSharp.CSharpCodeProvider.CreateProvider("C#", options);

            var compiled = compiler.CompileAssemblyFromDom(
                option,
                listener.GeneratedCode);

            foreach (var e in compiled.Errors)
                errors.Add(e.ToString());

            if (Errors.Length > 0)
                return null;
            else
            {
                var page = Activator.CreateInstance(compiled.CompiledAssembly.GetTypes().FirstOrDefault()) as T;
                return page;
            }
        }
    }

With this you can build the “WebPage” you want to execute, and set it’s properties as you choose. I have done to Base classes that will render the output in the Console or in a file. Here are the classes:

Snippet

    public class ConsoleWriter : WebPage
    {
        public new string Model
        {
            get;set;
        }
        public override void Execute()
        {
            this.Context = new HttpContextWrapper(new HttpContext(new HttpRequest(null, null, null), new HttpResponse(Console.Out)));
        }
        public override void WriteLiteral(object o)
        {
            if (o != null)
                Console.Write(o.ToString());
        }
        public override void Write(Microsoft.WebPages.Helpers.HelperResult result)
        {
            Write(result);
        }
        public override void Write(object value)
        {
            if (value != null)
                Console.Write(value.ToString());
        }
    }

No big deal in the ConsoleWriter. I have added a property called Model to ilustrate that you can add as many properties as you want, and you can use these to render output.
Here is the FileWriter:

Snippet

public class FileWriter<T> : WebPage, IDisposable
    {
        private string filePath;
        public string FilePath 
        {
            get
            {
                return filePath;
            }
            set
            {
                filePath = value;
                File.WriteAllText(FilePath, string.Empty);
                writer = new StreamWriter(FilePath);
                this.Context = new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://razor", null), new HttpResponse(writer)));
            }
        }
        private StreamWriter writer;
        public FileWriter()
        {
        }
        public new T Model
        {
            get;
            set;
        }
        public override void Execute()
        {

        }
        public override void WriteLiteral(object o)
        {
            if (o != null)
                writer.Write(o.ToString());
        }
        public override void Write(Microsoft.WebPages.Helpers.HelperResult result)
        {
            Write(result);
        }
        public override void Write(object value)
        {
            if (value != null)
                writer.Write(value.ToString());
        }
        public void Dispose()
        {
            if (writer != null)
            {
                writer.Flush();
                writer.Close();
                writer.Dispose();
            }
        }
    }

This is one is pretty much the same, but I have added Generics to it, and a property Model that is of type T, again to ilustrate that this is totally valid. I also chose to do this one IDisposable.

Here is how you would use these writers with our RazorFactory:

Snippet

    class Program
    {

        static void Main(string[] args)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Test.txt");

            var factory = new RazorClient.RazorFactory();
            factory.ReferencedAssemblies.Add("ConsoleApplication1.exe");

            using (var page = factory.Create<FileWriter<string>>(filePath))
            {

                if (factory.Errors.Length > 0)
                    foreach (var e in factory.Errors)
                        Console.WriteLine(e);
                else
                {
                    page.FilePath = filePath + ".rzr.txt";
                    page.Model = "this is my model";
                    page.Execute();
                }
            }
            Console.ReadKey();

        }
    }

Check out at how we can do page.Model = “this is my model”, this could easily be page.Model = typeof(Customer) or whatever.

Here is the Test.txt file content:

ASP.NET Web Pages makes it easy to build powerful .NET based applications for the web.
Time: @DateTime.Now.ToString()
Model: @Model

And here is the Test.txt.rzr.txt file output:

ASP.NET Web Pages makes it easy to build powerful .NET based applications for the web.
Time: 7/7/2010 4:25:24 PM
Model: this is my model

Conclusion
We have seen how to run a cshtml or a vbhtml file and generate code, and we have encapsulated that into a helper factory that returns an instance of the template. Then we have provided two way to output the generated code, plus adding some typed and generic properties.

Update: check out my other post on how to call child razor templates.

WCF – Exception handling and disposing channels

Looking for a way to avoid duplicating the Exception handling and disposal code of WCF channels, I ran into this post which gives an interesting approach. However I needed a way make return values more generic, so here is my little tunning.

The code

public static class Service<T>
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
public static TResult Use<TResult>(Func<T, TResult> codeBlock)
{
var proxy = (IClientChannel)_channelFactory.CreateChannel();
bool success = false;
try
{
var result = codeBlock((T)proxy);
proxy.Close();
success = true;
return result;
}
catch(..)
{
//Exception handling here.
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}

How to use it


//Expose this to your system through an interface for proper loosely coupling.
public bool IsUsernameAvailable(string name)
{
return Service<IUserManagementService>.Use<bool>(proxy => proxy.IsUsernameAvailable(name));
}

For those of you using disposable Clients (clients that implement IDisposable) you can use a very similar approach, just wrap the code inside the Use method with a using statement.

With disposable clients

public static class Service<T> where T : IDisposable, new()
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
public static TResult Use<TResult>(Func<T, TResult> codeBlock)
{
using (var proxy = new T())

{
bool success = false;
try
{
var result = codeBlock((T)proxy);
proxy.Close();
success = true;
return result;
}
catch(..)
{
//Exception handling here.
}
}
}
}

VS2010 Modeling Project – Generating classes from UML – t4 template

Here you will find a very simple t4 template for generating the following things from a VS2010 Modeling project:

Classes:
- Class definition.
- Methods.
- Class inheritance.
- Implemented interfaces.
- Properties.
- Associations (with other classes in the form of properties).

Interfaces:
- Interface definition.
- Properties.
- Methods.

Enumerations:
- Enum definition.
- Enum items.

The template

The only thing you need to do in order to use the template is: add a .tt file, change the path of the modelproj so that it points to your own .modelproj file, and then save it. Then you can see the generated code in the file yourtemplate.cs (in case your template is yourtemplate.tt).

Note: I don’t have a wordpress plugin for coloring and formatting the code :)

<#@ template debug="true" hostspecific="true" language="C#v3.5" #>
<#@ output extension=".cs" #>
<#@ assembly name="Microsoft.VisualStudio.Uml.Interfaces.dll" #>
<#@ assembly name="Microsoft.VisualStudio.ArchitectureTools.Extensibility.dll" #>
<#@ assembly name="System.Core.dll" #>
<#@ import namespace="Microsoft.VisualStudio.Uml.Classes" #>
<#@ import namespace="Microsoft.VisualStudio.ArchitectureTools.Extensibility" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#
string projectPath = Host.ResolvePath(@"..\ModelingProject1\ModelingProject1.modelproj");
var project = ModelingProject.LoadReadOnly(projectPath);
//Use the packages where the C# namespace stereotype has been applied.
//You can remove the where if you want to generate all.
IEnumerable packages = project.Store.Root.NestedPackages
.Where(n => n.AppliedStereotypes.Any(s => s.Name == "namespace"));
//Namespaces
foreach(var package in packages)
{
#>
/*
Template by Gustavo Machado.
Project: <#= project.Store.Root.Name #>
*/
using System;
<#= "namespace " + package.Name#>
{
<# foreach(var aType in package.OwnedTypes) { var aClass = aType as IClass; if (aClass != null) { //render the class. #>
public<#= GetClassModifier(aClass) #> class <#= aClass.Name #> <#= GetBaseTypes(aClass) #>
{
<# //render properties. foreach(var p in aClass.OwnedAttributes) { var property = p as IProperty; if (property != null) { //render a property. #>
public <#= p.Type.Name #> <#= p.Name #> { get; set; }
<# } }//end of properties //Render navigation properties (associations) var associations = aClass.Package.OwnedTypes .Where(t => t is IRelationship &&
(((IRelationship)t).SourceElement == aClass ||
((IRelationship)t).TargetElement == aClass)).Cast();
foreach(var assoc in associations)
{
//Look for the correct end of the association.
foreach (var end in assoc.NavigableOwnedEnds)
{
if (end.Opposite.Type == (IType)aClass)
{
#>
public <#= end.Type.Name #> <#= end.Name #> { get; set; }
<# } } } //render methods foreach(var op in aClass.OwnedOperations) { if (!op.IsAbstract) {//render the not implemented exception. #>
public<#= GetMethodModifier(op)#> <#= GetReturnType(op)#> <#= op.Name #>(<#= GetMethodParameters(op)#>)
{
throw new NotImplementedException();
}
<# } else { #>
public<#= GetMethodModifier(op)#> <#= GetReturnType(op)#> <#= op.Name #>(<#= GetMethodParameters(op)#>);
<# } } // end of methods. #>
}
<# continue; //we are done with the class. } var anInterface = aType as IInterface; if (anInterface != null) { //render the interface. #>
public interface <#= anInterface.Name #>
{
<# //render the properties. foreach(var prop in anInterface.OwnedAttributes) { #>
public <#= prop.Type.Name #> <#= prop.Name #> { get; set; }
<# } //render the methods. foreach(var op in anInterface.OwnedOperations) { #>
<#= GetReturnType(op)#> <#= op.Name #>(<#= GetMethodParameters(op)#>);
<# } #>
}
<# continue; } //end of interfaces. var anEnumeration = aType as IEnumeration; if (anEnumeration != null) { #>
public enum <#= anEnumeration.Name #>
{
<# foreach(var enumItem in anEnumeration.OwnedLiterals) { #>
<#= enumItem.Name #>,
<# } #>
}
<# } }#>
}
<# } //foreach package #>
<#+
public string GetBaseTypes(IClass c)
{
string generalizations = string.Empty;
foreach(var g in c.Generalizations)
{
if (g.TargetElement as INamedElement != null)
{
if (string.IsNullOrEmpty(generalizations))
generalizations = ": " + ((INamedElement)g.TargetElement).Name;
else
generalizations += ", " + ((INamedElement)g.TargetElement).Name;
}
}
foreach(var i in c.InterfaceRealizations)
{
if (i.TargetElement as INamedElement != null)
{
if (string.IsNullOrEmpty(generalizations))
generalizations = ": " + ((INamedElement)i.TargetElement).Name;
else
generalizations += ", " + ((INamedElement)i.TargetElement).Name;
}
}
return generalizations;
}
public string GetReturnType(IOperation o)
{
string returnType = string.Empty;
if (o.Type == null)
return "void";
else
returnType = o.Type.Name;
//Check if the method returns a collection.
var returnParameter = o.OwnedParameters.Where(p => p.Direction == ParameterDirectionKind.Return).FirstOrDefault();
if (returnParameter != null && returnParameter.UpperValue as ILiteralString != null)
{
if (((ILiteralString)returnParameter.UpperValue).Value == "*")
returnType += "[]";
}
return returnType;
}
public string GetClassModifier(IClass c)
{
if (c.IsAbstract)
return " abstract";
else
return string.Empty;
}
public string GetMethodModifier(IOperation o)
{
if (o.IsAbstract)
return " abstract";
else if (o.IsStatic)
return " static";
else
return "";
}
private string GetMethodParameters(IOperation op)
{
string parameters = string.Empty;
foreach (var para in op.OwnedParameters.Where(p => p.Direction == ParameterDirectionKind.In))
{
string name = string.IsNullOrEmpty(para.Name) ? para.Type.Name.ToLower() : para.Name;
parameters += string.Format("{0} {1}, ", para.Type.Name, name);
}
if (!string.IsNullOrEmpty(parameters))
return parameters.Substring(0, parameters.Length - 2);
else
return string.Empty;
}
#>

VS2010 Modeling Project – Generating classes from UML – Part 2

Following with my previous post, here I got more on how to navigate modeling projects through code.

Getting method’s return type

public string GetReturnType(IOperation o)
{
string returnType = string.Empty;
if (o.Type == null)
return "void";
else
returnType = o.Type.Name;
//Check if the method returns a collection.
var returnParameter = o.OwnedParameters.Where(p => p.Direction == ParameterDirectionKind.Return).FirstOrDefault();
if (returnParameter != null && returnParameter.UpperValue as ILiteralString != null)
{
//Check if it's a collection.
if (((ILiteralString)returnParameter.UpperValue).Value == "*")
returnType += "[]";
}
return returnType;
}

Method’s parameters


public string RenderMethodParameters(IOperation op)
{
string parameters = string.Empty;
foreach (var param in op.OwnedParameters.Where(p => p.Direction == ParameterDirectionKind.In))
{
string name = string.IsNullOrEmpty(param.Name) ? param.Type.Name.ToLower() : param.Name;
parameters += string.Format("{0} {1}, ", param.Type.Name, name);
}
if (!string.IsNullOrEmpty(parameters))
return parameters.Substring(0, parameters.Length - 2);
else
return string.Empty;
}

Class associations


var associations = aClass.Package.OwnedTypes
.Where(t => t is IRelationship &&
(((IRelationship)t).SourceElement == aClass ||
((IRelationship)t).TargetElement == aClass)).Cast();
foreach (var assoc in associations)
{
var prop = assoc.NavigableOwnedEnds.Where(e=> e.Opposite.Type == (IType)aClass).FirstOrDefault();
if (prop != null)
//Render the property with prop.Type.Name and prop.Name.
}

Enums


foreach(var aType in package.OwnedTypes)
{
var anEnumeration = aType as IEnumeration;
if (anEnumeration != null)
{
var name = anEnumeration.Name;
foreach(var enumItem in anEnumeration.OwnedLiterals)
{
var itemName = enumItem.Name;
}
}

VS2010 Modeling Project – Generating classes from UML

In this post I will show you the C# related stuff, and how to navigate a modeling project through code. The only thing that is clearly missing from the modeling project is the code generation based on diagrams (you can check here for all the types of diagrams). I’ve read somewhere that it is a feature that it’s already planned for the near future. But if you are like me and can’t wait for MS to provide with the solution, then you can keep on reading.

The first thing you have to do in order to be able to use C# stereotypes, is to choose the C# Profile for the package like this:

As soon as you choose C# Profile, you will see a new set of stereotypes in the class diagram.

For a good explanation on UML profiles, and code generation, you can check out this post. Now let’s go to the code. First, you will need to import the following namespaces.

  • Microsoft.VisualStudio.Uml.Classes
  • Microsoft.VisualStudio.ArchitectureTools.Extensibility

How to get a modeling project:

string projectPath = @”c:\YourModelingProject\ModelingProject1.modelproj”;
var project = ModelingProject.LoadReadOnly(projectPath);

How to get namespaces of a modeling project:

//Use the packages where the C# namespace stereotype has been applied.
//You can remove the “where” if you want to generate all.
IEnumerable<IPackage> packages = project.Store.Root.NestedPackages
.Where(n => n.AppliedStereotypes.Any(s => s.Name == “namespace”));
//Namespaces

foreach(var package in packages)
{

How go get namespace classes:

foreach(var c in package.OwnedTypes)
{
var aClass = c as IClass;
if (aClass != null)
{
//render the class.

Class Properties:

//render properties.
foreach(var p in aClass.OwnedAttributes)
{
var property = p as IProperty;
if (property != null)
{
//render a property.

Class Methods:

foreach(var op in aClass.OwnedOperations)

{

Interfaces:

foreach(var c in package.OwnedTypes)
{
var anInterface = c as IInterface;
if (anInterface != null)
{
//render the interface.

Interface Methods:

foreach(var op in anInterface.OwnedOperations)
{
//render the method.

In the next post, I’ll give you the code of a T4 template for generating basic stuff.

One tip regarding t4 templates: I too recommend t4 editor from tangible to work on .tt files, but the Free edition they offer does not come with intellisense for the namespaces I just listed. I guess the easiest work around is to add the references to another console or library project where you will get full intellisense and compile validations.

Applying AOP on IQueryables

When working with LinqToSql or Entity Framework, you will be using IQueryables extensibly. So extensibly, that plenty of your code will be employed in writting Where clauses in Linq. Linq makes it very easy and declarative to ask for whatever you need. The problem araises when you have  complex where clauses and the same conditions all over your repository. For example, suppose your records have a DateDeleted column, which means that the record has been deleted when it is not null (e => e.DateDeleted != null). You could have that condition all over the place. And a similar thing would happen if you had a IsActive, or Status columns.

The proposed solution is very simple, we use method extensions in order to add the most common conditions to the IQueryable<T>. Something like this:

public static IQueryable<Order> ThatAreShipped(this IQueryable<Order> query)
{
return query.Where(o => o.Status == OrderStatus.Shipped);
}
or
public static IQueryable<Order> WhereIdIs(this IQueryable<Order> query, int id)
{
return query.Where(o => o.Id == id);
}

So you can see a simple pattern, when the condition requires parameters, we use the prefix “Where”, and when the condition doesn’t require a parameter, then we use the prefix “That”. So we could see something like the following and easily understand what we will get in return:

var orders = context.Orders.ThatAreShipped().WhereTotalGreaterThan(100).WhereShippingStateIs(“NY”);

The basic AOP concept we are avoiding here is to have similar code Scattered all over our repository. It turns out that method extensions, are an excellent and easy way to apply AOP. If you use the namespace of these extensions to be internal to the repository, then you will see this methods in the repository only. So if you do the following from outside the repository namespace:

var orders = new List<Order>().AsQueryable().ThatAreShipped()

This would throw a compilation error, and that is perfect, because it is a repository concern only.

ASP .NET MVC Controller Factory with Windsor

In this post I will show you how to create your custom Controller Factory for ASP .NET MVC using windsor and other things you can do with it. First if you don’t know Windsor, it’s an Inversion of Control Container which allows you to inject dependencies dinamically. I strongly recommend to read about it in castle project’s website here.

Custom Controller Factory

In order to create your own custom controller factory, you can inherit the DefaultControllerFactory that ships with MVC. The real magic happens when you override the GetControllerInstance(Type controllerType) method in which you will return the instance of the specified controller. In order to create the instance with Windsor you first need to register the types in the container. (I took this sample from the book Pro ASP.NET MVC Framework, which is awesome by the way):

public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;

// The constructor:
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
public WindsorControllerFactory()
{
// Instantiate a container, taking configuration from web.config
container = new WindsorContainer(
new XmlInterpreter(new ConfigResource(“castle”))
);
container.Kernel.AddFacility<

ServiceDependencyPropertiesFacility>();
// Also register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;

foreach (Type t in controllerTypes)
{
container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
}
}
}

Basically it looks for all the classes in the Assembly which implement the IController interface, and then registers the type in the container. Once we have all the types registered we can go ahead and override the method like this:
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
And last but not least! We need to register the controller in the Global.asax file:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
}
Now would we want to do this? Couple of reasons, first we can control the Lifestyle of the controllers re-utilizing controller’s instances if we want to.  And second because it let’s us take advantage of the Dependency Injection capabilities of Windsor. And even take advantage of the Interceptor and include AOP to our project! (more on this soon).

Aspect Oriented Development in .NET

In this post I will illustrate the difference between Aspect Oriented Development, and Aspect Oriented Programming.

If you know PostSharp, then you know it’s an awesome tool (if you don’t, then you should). Logging, Caching and Asynchronous processing are the most common cross-cutting concerns you usually find in most systems;  and attacking those concerns with AOP tools like PostSharp is usually an excellent solution. If we use PostSharp for this, then we are taking advantage of a AOP technique, but it doesn’t mean we are developing in Aspect Oriented manner. However, what about more domain-specific concerns and designing as if everything in your system is a concern? Of course these concerns are not going to “cut across” the entire system, but let’s see how we can think of them as concerns.Assume I have a shopping cart, with many different ways to make the payment. We could say that the Checkout is a concern which is used in every payment type process (thus being a cross-cutting concern). So we could develop a generic Checkout logic, and extend it and use it through mechanisms such as method extensions and PostSharp library. We would inject the specific logic, at the right moment. Something like this:

public class Checkout
{

public void Process()…

public bool CheckInventory()…

public decimal CalculateShipping()…

}

When using the credit card type, we could add a Method extension to validate CreditCards:

public Class CreditCardCheckoutExtensions
{
public static bool VerifyCreditCard(this Checkout aCheckout)…
}

And finally attaching specific methods with PostSharp:
public class CheckoutProcessAttribute : OnMethodBoundaryAspect
{
//This will be executed before the Process method in the Checkout class.
public override void OnEntry( MethodExecutionEventArgs eventArgs)
{
//Logic to validate CreditCard…
if (!eventArgs.Instance.VerifyCreditCards())
throw new InvalidCreditCardException();
}
}

It’s just a simple example to illustrate how we can think of domain-specific functionality as aspects (concerns).