INTRODUCTION: The Gang of Four were pretty smart folks. They gave us a lot of design patterns to use to make better application architectures. One of the patterns they gave us was the Facade, which is generally used to provide common functionality for objects that don’t necessarily have a polymorphic purpose for the object. In C# we use static classes to build facades, which is great. Facade classes allow you to group together similar functionality and because the classes and methods are static, there is an expectation that they should work on any instance of the object(s) being manipulated.

Extension methods take the Facade one step further. Instead of having to reference a Facade class specifically, the extension methods bring the facade methods right to the class(es) they apply to. You might be asking right now, “What is an extension method?” Extension methods are defined as static methods of static classes that receive the context of a single object instance that allows you to present the functionality of the method as an extension of the object.

EXAMPLE

public static class MyExtensionFacade
{
    // Normal facade implementation
    public static void IncrementInt32ByDecimal(out int source, decimal value)
    {
        source += (int)(value + 0.5m);
    }

    // Extension Method
    // Notice the use of the this keyword, it defines the object that the
    // extension method works on.
    public static void IncrementByDecimal(this int source, decimal value)
    {
        IncrementInt32ByDecimal(out source, value);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        int i = 10;
        decimal d = 15.75m;

        // Call facade method as normal.
        MyExtensionFacade.IncrementInt32ByDecimal(out i, d);

        Console.WriteLine($"i = {i}");

        // Call as extension method
        i.IncrementByDecimal(d);

        Console.WriteLine($"i = {i}");
    }
}

CONCLUSION: As you can see from the example, the extension method is much simpler to call and makes your code cleaner. As a matter of fact, the entire LINQ framework is a series of extension methods. They can be a very valuable and powerful arrow in your quiver of Ninja tricks.

INFO: If you are looking for information specifically related to ASP.Net MVC, then continue your Google Search.  This article is about the MVC Design Pattern and a simple implementation in C#.

OVERVIEW: The MVC (Model-View-Controller) design pattern was introduced by the Gang of Four as a means of describing an application from the perspective of the three layers of the application (Data – Presentation – Logic).  Over the years many different implementations of the MVC pattern have emerged.  I am now about to introduce my personal implementation which has served me well for nearly a decade.

THE MODEL:  Since this is a .Net blog, I will give my example using Microsoft’s Entity Framework.  Whether you prefer to design on the database or in code, the DbContext you create is the perfect repository for your data.  As a matter of fact, the objects created by the DbContext are perfect for your Models, so you don’t have to write any special code!

THE VIEW:  Many MVC implementations lock the view into a specific technology.  I do not.  Instead, I expose Views as Interfaces.  What implements the interface is irrelevant. Here is an example View:

public interface IView
{
    // This is the interface that all views will derive from. This
    // base view will allow us to generalize the controller.
}

public interface ISampleView : IView
{
    // Properties representing your data
    List<Model%gt; ModelData { get; set; }

    // Actions that the controller responds to
    event EventHandler<Model> SaveModelData;
    event EventHandler<Guid> LoadModelDataByGroupUID;

    // Actions that the view responds to
    void BindModelData();
}

Now that we have defined our view, we can implemented it in many different ways. Here’s a simple Web Form that implements the above view.

public class SampleView : Page
{
    public List<Model> ModelData { get; set; }

    public void BindModelData()
    {
        // Assume the ASPX file defines a ListView named ListView1
        // and we want to sort on a specific field before displaying
        // The data.
        ListView1.DataSource = ModelData.OrderBy(x => x.SortField).ToList();
        ListView1.DataBind();
    }
    
    public event EventHandler<Model> SaveModelData;
    public event EventHandler<Guid> LoadModelDataByGroupUID;
}

The view doesn’t have a lot of moving parts (as is correct). The only real work done in the view is shaping the data for presentation. The main work is handled in the Controller.

THE CONTROLLER: Now we’re talking about the main part of the application. This is where the real work is done. Controllers are typically plain old classes that register a view and manage the interaction between the needs of the view and the storage and manipulation of the data. Often the Controller is a stand alone class, but some frameworks provide an abstract class that provides reusable features. I will instead provide a IController interface to provide a simple Initialize method.

public interface IController
{
    Initialize(IView view);
}

Pretty simple, but this ensures that the View implementation has a consistent contract for registering itself with the controller.

Now, let’s take our example and actually load and save the Model from our SampleView.

public class SampleController : IController
{
    private IView _view;
    protected ISampleView SampleView { get { return _view as ISampleView; } }

    public Initialize(IView view)
    {
        _view = view;
        if(SampleView != null)
        {
            SampleView.SaveModelData += SampleViewSaveModelData;
            SampleView.LoadModelDataByGroupUID += SampleViewLoadModelDataByGroupUID;
        }
    }

    protected void SampleViewSaveModelData(object sender, Model data)
    {
        if(SampleView != null)
        {
            using(var context = new SampleDbContext)
            {
                var existing = context.Models.FirstOrDefault(data);
                if(existing != null)
                {
                    // Copy fields from data to existing
                }
                else
                {
                    context.Models.Add(data);
                }

                context.SaveChanges();
            } 
        }
    }

    protected void SampleViewLoadModelDataByGroupUID(object sender, Guid key)
    {
        if(SampleView != null)
        {
            using(var context = new SampleDbContext)
            {
                SampleView.ModelData = context.Models.Where(x => x.GroupUID = key).ToList();
                SampleView.BindModelData();
            }
        }
    }
}

CONCLUSION: The MVC pattern allows for complete abstraction of the data, presentation and manipulation of that data. Here I’ve provided an overly simplistic example of a complete MVC example. I would strongly encourage you to take this example and expand upon it. For example, you can add fields to your View and then incorporate them into the logic of your controller. The sky is the limit!

Long, long ago, in a time far away, I wrote a blog for IT Toolbox where I talked about development and the life of a developer.  It’s been quite a while, but I feel the need to start blogging again.

To that end, I’ve set up this website, the home of the Sharp Ninja.  Why the Sharp Ninja?  Why not!  OK, well, because I’ve been developing with C# for about 15 years now and I feel like I have some things to share about it.

Some things to look forward to are articles about Windows 10 Universal apps, moving from ASP.Net Web Forms to ASP.Net MVC, WPF and WinForms development, and much more.