INTRODUCTION: Previously, I wrote about the MVC design pattern.  That article focused on the mechanics of the pattern more than a realistic implementation.  In this article we’ll look at a full MVC application, starting with the Model, the Controller and finally the Views as implemented in a Windows 10 Universal Application.

THE MODEL: For this application we’ll use a fairly complex Person class that has normal CRUD properties as well as some data-centric properties such as calculating age from the Date of Birth property.  This will give you a good idea of the kind of classes you can make for serialization using your preferred format (SOAP, JSON, Binary, etc).

EXAMPLE 1 – THE PERSON CLASS

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;

namespace SharpNinja.Models.BlogEntities
{
    [DataContract]
    public class Person : INotifyPropertyChanged
    {
        private string _firstName;
        private string _lastName;
        private DateTime _dateOfBirth = DateTime.Today;

        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

        [DataMember]
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if (value == _firstName) return;
                _firstName = value;
                OnPropertyChanged();
            }
        }

        public string Name => $"{FirstName} {LastName}";

        [DataMember]
        public string LastName
        {
            get { return _lastName; }
            set
            {
                if (value == _lastName) return;
                _lastName = value;
                OnPropertyChanged();
            }
        }

        [DataMember]
        public DateTime DateOfBirth
        {
            get { return _dateOfBirth; }
            set
            {
                if (value.Equals(_dateOfBirth)) return;
                _dateOfBirth = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(Age));
                OnPropertyChanged(nameof(IsChild));
            }
        }

        public int Age => (DateTime.Today - DateOfBirth).Days / 365;

        public bool IsChild => Age < 18;

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

The Person class has a lot of nifty features. It implements INotifyPropertyChanged so that views that are databinding capable are able to bind to the values of the Person. Another feature is that it’s marked as a DataContract which allows it to be easily serialized. The properties representing the serializable content are also decorated with the DataMember attribute.

Just a quick note… See that method invocation of PropertyChanged? That’s the correct way to call an event using Null Propagation.

VIEWS PART 1: Our Person Model now needs to be interacted with in some way. There are two main use cases for our application: get a list of Person instances and editing a Person. For this tutorial we will focus on getting the list of Person instances by create a simple search engine for Game of Thrones characters.

The view for the search engine will define a list of Person objects, an event for telling the Controller that a search is required, and a callback method for the Controller to let the View know that new results are ready.

EXAMPLE 2

using System;
using System.Collections.ObjectModel;
using SharpNinja.Models.BlogEntities;
using SharpNinja.Utilities.MvcBasics;

namespace SharpNinja.UI.Windows10Sample.Views
{
    public interface IPersonsListView : IView
    {
        ObservableCollection<Person> PersonsList { get; set; }

        event EventHandler<string> FindPersons;

        void BindPersonsList();
    }
}

That’s all that’s necessary to define the View, and that’s all that’s necessary to implement the Controller.

BTW, all of the source code for this article (and the next one) is located on GitHub. You will see some code there that’s not 100% pertinent to this article.

THE CONTROLLER: The Controller is the heart of the application. It is responsible for persisting and retrieving Models from the data store, for enforcing the rules of the application, and for providing non-UI oriented logic. In our app, the Controller will act as the search engine, accepting a partial match string as a parameter for the FindPersons event of the IPersonsListView.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using SharpNinja.Models.BlogEntities;
using SharpNinja.UI.Windows10Sample.Views;
using SharpNinja.Utilities.MvcBasics;

namespace SharpNinja.UI.Windows10Sample.Controllers
{
    public class PersonsController : IController
    {
        private List<Person> _fakePersonsDatabase;

        public PersonsController()
        {
            _fakePersonsDatabase = new List<Person>();

            _fakePersonsDatabase.Add(new Person("John", "Snow") { DateOfBirth = new DateTime(1995, 2, 28) });
            _fakePersonsDatabase.Add(new Person("Ned", "Stark") { DateOfBirth = new DateTime(1971, 1, 15) });
            _fakePersonsDatabase.Add(new Person("Stannis", "Barathian") { DateOfBirth = new DateTime(1952, 12, 8) });
            _fakePersonsDatabase.Add(new Person("Aria", "Stark") { DateOfBirth = new DateTime(2003, 7, 10) });
        }

        #region IDisposable
        protected bool _isDisposed = false;
        public void Dispose()
        {
            if (!_isDisposed)
            {
                // Dispose of resources

                _isDisposed = true;
            }
        }
        #endregion

        #region Views
        private readonly List<IView> _views = new List<IView>();
        private IPersonsListView _personsListView = null;

        protected IPersonsListView PersonsListView
        {
            get
            {
                return _personsListView ??
                       (_personsListView = _views.FirstOrDefault(x => x is IPersonsListView) as IPersonsListView);
            }
        }
        #endregion

        public void Initialize(ICollection<IView> views)
        {
            foreach (var view in views)
            {
                if (view is IPersonsListView &amp;&amp; !_views.Any(x => x is IPersonsListView))
                {
                    _views.Add(view);

                    PersonsListView.FindPersons -= PersonsListViewOnFindPersons;
                    PersonsListView.FindPersons += PersonsListViewOnFindPersons;
                }
            }
        }

        private void PersonsListViewOnFindPersons(object sender, string s)
        {
            if (PersonsListView != null)
            {
                var search = s.ToLower();
                var results =
                    _fakePersonsDatabase.Where(
                        x => x.FirstName.ToLower().Contains(search) || x.LastName.ToLower().Contains(search)).ToList();

                if (results.Count > 0)
                {
                    PersonsListView.PersonsList = new ObservableCollection<Person>(results);

                    PersonsListView.BindPersonsList();
                    PersonsListView.SetStatus($"Found {results.Count} persons matching {s}", false);
                }
                else
                {
                    PersonsListView.SetStatus($"No results found for {s}.", true);
                }
            }
        }
    }
}

There’s a lot going on here, so let’s start at the top. Our application implements a fake datastore of GoT characters. This is not typical of a real app, but I didn’t want to introduce database code into this first example.

Next, you will see a property named PersonsListView. This property makes it possible to use a strongly typed instance of the View while only having to do the type checking once.

Our compulsary Initialize method adds IView instances to the controller. It knows about the events exposed in the View and appropriately registers to those events.

Finally, our event handler method does the searching of the fake datastore and places the data in the View’s PersonsList and invokes the View’s BindPersonsList call-back method.

STOPPING POINT:  That’s enough for this article.  The next article will bring it all together into a Windows 10 Universal App.  See you then!

INTRODUCTION: There are a couple of reasons to have public classes that need to control their own instantiation. First, is the Singleton pattern (read more here), but another is when you have an object that gets instantiated through reflection. Enter that Factory Pattern. Objects that implement the Factory Pattern are known as Object Factories. There may be any number of objects they create, from reflected types to deserialized data. Object Factories are responsible for making sure the object you request is instantiated correctly and ready to work.

A popular reason for the Factory Pattern is Dependency Injection (I will be doing an article on that in the near future). Essentially, Dependency Injection allows you to create an object from a definition stored in some configuration, and assign it to some known contract. The class that does this magic is the Object Factory.

Another popular reason for the Factory Pattern is to allow a polymorphic sub-class to provide it’s own instantiation signature that is separated from the construction of the class hierarchy. An example is in the Entity Framework where the implementation classes for entities contained a CreateEntityName static method to instantiate the entity and ensure that all non-nullable fields are maintained without having to overload the constructor, which is left as a default constructor so that the user could optionally use the object initializer.

Of the two use cases above, the Dependency Injection technique is the most useful, but for sake of brevity, I will use a simple Object Factory to show the mechanics of the pattern in C#.

EXAMPLE

public static class MyFactory
{
  public static ConstructedObject MakeObject(string data)
  {
    // Don't allow an instance without data!
    if(data == null) throw new ArgumentNullException("Data cannot be null.");

    // Create the object and return it.
    return new ConstructedObject { Data = data };
  }
}

// Our constructible class.
public class ConstructedObject
{
  // No constructor defined, so Data must be initialized
  // by the factory.
  public string Data {get; set;}
}

public class Program
{
  public static void Main(string[] args)
  {
    // Check for arguments.
    if(args.Any())
    {
      // Contrived attempt to get a null data.
      var data = args[0].Length > 0 ? args[0] : null;
    
      try 
      {
        // Create the object.
        var obj = MyFactory.MakeObject(data);
 
        // Yay!
        Console.WriteLine(obj.Data);
      }
      catch(ArgumentNullException ane)
      {
        // Boo!
        Console.WriteLine(ane.ToString());
      }
    }
  }
}

CONCLUSION: The Factory Pattern is one of the most useful utility patterns around. In just this simple example I’ve shown how an Object Factory can apply business rules as an object is instantiated. Another use case could be a class with a static method to provide an instance if and only if certain preconditions are met. This would allow the return of a null object instead of throwing an exception. Really, the sky’s the limit for what can be accomplished with a Factory Pattern implementation!

INTRODUCTION: Singleton is the design pattern that is the easiest to abuse and hardest to nail down. You must correctly ascertain when they are appropriate and to what scope. But first, what is a Singleton? Singletons are classes that should only be instantiated once per application. These classes typically represent a set of functionality that is global to the application, yet deserves to be encapsulated into a single set of functionality.

The Singleton should expose itself as a static property from the class definition, making available public instance methods only from the referenced static property. Singletons should have a single purpose. Some examples are a Window manager for an Application, or a Report generator. I’ve even used a Singleton to manage the state of a WinForms ribbon. The main thing to remember is that the Singleton only gets instantiated at a global scope and should have a narrow focus.

For an example, let’s make a Singleton that performs acts as a state manager for a fictional application. This application will represent a wizard that must move between three steps.

EXAMPLE:

public class AppSingleton
{
  // Private static reference to the long instance of this
  // Singleton.  
  private static readonly AppSingleton _instance = new AppSingleton();

  // Current state of the application.
  private State _state = State.Start;

  public State State => _state;

  // Private constructor ensures that only the Singleton
  // can create new instances.
  private AppSingleton() { }

  public AppSingleton Instance => _instance;

  // Instance method to change the state of the application,
  // returns the resulting app state.
  public State MoveNext()
  { 
    switch(_state)
    {
      case State.Start:
        _state = Middle;
        break;

      case State.Middle:
        _state = Finish;
        break;

      case State.Finish:
        _state = Completed;
        break;
    }
    return _state;
  }

  // Instance method to change the state of the application,
  // returns the resulting app state;
  public State MovePrevious()
  {
    switch(_state)
    {
      case State.Middle:
        _state = First;
        break;

      case State.Finish:
        _state = Middle;
        break;
    }
  }

  // Here we can tell the singleton to perform some work.
  // You do not need this method signature, you can have
  // as many "worker" methods as is necessary.  This is 
  // just an example!
  public void DoSomething(params object[] args)
  {
    // DO some work!
  }
}

public enum State
{
  Start, Middle, Finish, Completed
}

public class Program
{
  public static void Main(string[] args)
  {
    AppSingleton.Instance.DoSomething(1);
    var state = AppSingleton.Instance.MoveNext();

    if(state != State.Start) 
    {
      // We moved state!  Do something else!
      AppSingleton.Instance.DoSomething(2);

      // Let's go back and try again!
      state = AppSingleton.Instance.MovePrevious();

      // Etc.
    }
    else
    {
      // Uh-oh, the singleton says it cannot move.
    }
  }
}

Here our application state is managed by the AppSingleton. The main program simply attempts to manipulate that state by providing data to the Singleton to process. In a real app, there would be user interaction that would drive the wizard forwards and backwards.

CONCLUSION: Singletons are a very powerful arrow in your C# quiver. Single-user applications are great usages for them. If you are not sure if you should use a singleton, ask yourself these questions:

  • Does the Singleton represent a single state within the application?
  • Does the Singleton have logic that should be encapsulated?
  • Do you need to control the object lifecycle for the Singleton?

If your answer is yes to these questions, a Singleton is right for you!

INTRODUCTION: I may be about to start a holy war, but this is actually a topic I’ve had to very recently deal with at work. For years I’ve standardized the theming of websites on jQueryUI and ThemeRoller. It was simply the thing to do. All the cool kids did it. It was kinda easy and if you followed the rules you’d (pretty much) avoid trouble. ThemeRoller is easy to use, there’s tons of great pre-built themes, and it got the job one. Then came Bootstrap, and it set the web on its ear. Bootstrap is more than just a theming mechanism, it’s a complete way of designing your website from both a layout and a stylistic perspective.

For years we were told the web would magically make it easy to write consistent applications that would work anytime, anywhere. For years we fought with browser incompatibilities, indecisiveness on visual standards, and a general lack of any kind of standardization on how the UI of a web application should act. Twitter decided enough is enough and dropped a big bomb on the whole net. If you want a consistent UI experience, you need a consistent tool and the appropriate conventions to go with it.

Bootstrap is that tool. Bootstrap enforces those conventions. Bootstrap not only assigns the pretty colors, but it tells your layout where to go, how wide to be based on the device, and whether or not certain elements should even be visible based on the device. All without the web developer (notice I did not say graphic/web designer) having to lift a finger. Bootstrap really is the closest thing to a magic bullet that the web has seen since ASP.Net was born.

CONCLUSION: So what do you do about all your old websites? If they ain’t broke…. But if you do have to refactor the UI for whatever reason, you should really look at converting them to Bootstrap. The shelf life of jQueryUI is basically up. Time to learn Bootstrap.

INTRODUCTION: Let’s take a poll… As a developer, what keeps you on your toes, yet mind-numbingly bored at the same time? For me, it’s null reference checking. I know I’m not alone and that it’s such a pervasive problem that Microsoft decided to do something about it. Welcome to the enlightened world of Null Propagation.

Null Propagation is a new feature in C# 6 that allows you to chain together nullable operations into a single chain that short-circuits on the first null reference, without worrying about having to check the whole chain for null references.

This is one of the most impressive solutions to the mess that arises from continuously nested null reference checks. Let’s look at some code.

EXAMPLE 1

string oops = null;
oops = MethodThatMayReturnNull();
if(oops != null)
{
    // Assume an extension method on String.  **
    oops.MethodThatProcessesOopsThatMayReturnNull(someOtherValue);

    if(oops != null)
    {
        // You get the picture...
    }
}

** (see: This Article)

What a mess!

EXAMPLE 2

string oops = MethodThatMayReturnNull()?.MethodThatProcessesOopsThatMayReturnNull(someOtherValue); // Just keep chaining!

Where’s the Null Reference checks? See that ? between methods? It means that the second method will be called only if the first method does NOT return a null value. If it does return a null value, then the call chain is broken and oops contains a null. That’s when you test for null: when it actually means something semantically to the application.

One of the most common usages of Null Propagation is calling events. Turn 4 lines of code into 1!

// Old way
if(eventDeclaration != null)
{
    eventDeclaration(this, EventArgs.Empty);
}

// The Null Propagation Way
eventDeclaration?.Invoke(this, EventArgs.Empty);

CONCLUSION: I love C# 6! This is a game changer. You write better code that is both easier to read, and more reliable (admit it, how many times have you neglected that Null Reference Check because you were certain you’d never have a Null Reference. How’d that work for ya?) Now, with Null Propagation, there’s no excuse for writing code that doesn’t use proper Null Reference checking because your Null Reference checks are only needed for business logic, not boilerplate.

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&lt;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.