Association vs. Aggregation vs. Composition

Association

Association is the most general type of relationship and it  includes other types as well. If the relationship doesn’t fall into a more specific type, like Aggregation or Composition, it can simply be referred to as an Association.

Example: When a Customer places an Order, the relationship is simply an Association.

Association

 

Aggregation

Aggregation is a more specific type of association. In an aggregation the children can also be shared with another owner at the same time, and even if the owner no longer exists, the children can still continue their lifetime.

Example: The relationship between a UserGroup and the Users, is an Aggregation. A User can still have meaning in the system even if it doesn’t belong to a UserGroup, so if you delete a UserGroup you won’t delete its Users. On the other hand, the Users can belong to several UserGroups at the same time.

Aggregation

 

Composition

Composition is a more strict type of Aggregation. In an aggregation, the children cannot be shared with a different owner and it doesn’t make sense for the children to exist without their owner. So, you usually want to delete the children if you delete their owner.

Example: The relationship between an Order and the OrderDetails is a composition relationship. The OrderDetail items are valid only as long as there is an Order related to them. When you delete an Order you will delete it’s OrderDetails as well. An OrderDetail associated to a particular Order cannot belong to a different Order.

Composition

 

Using Ninject in ASP.NET MVC applications

The following article is part of the chapter 4 of my book, Mastering Ninject for Dependency Injection, [PACKT] publishing, 2013.


In this article, we will implement the Northwind customers scenario using Ninject in an ASP.NET MVC 3 application. Ninject MVC extension also supports other versions of the MVC framework. (Download the source code)

Add a new ASP .NET MVC3 Web application to the Northwind solution with references to the Northwind.Core project and Ninject Conventions extension.
We should also reference Ninject MVC extension. The easiest way is to install the Ninject.Mvc3 package using NuGet. Keep in mind that although the name of the package is Ninject.Mvc3, it is upward compatible with newer versions of the MVC framework. Alternatively, we could download the Ninject.Web.Mvc binary from GitHub and reference it from our project. In this case, we also needed to reference the Ninject and Ninject.Web.Common libraries. These libraries are referenced automatically if we install the Ninject.Mvc3 package using NuGet. NuGet also adds the App_Start folder containing a file named NinjectWebCommon.cs to the project. The NinjectWebCommon class contains a Start() method that will be the starting point of the application. It sets up everything to hook Ninject to MVC framework. So, once we have installed Ninject MVC extension using NuGet, we do not need to do anything else to set up our application, and everything will be already there for us. This is because NuGet allows packages to add files to the project as a part of their installation process. The NinjectWebCommon class has a method named CreateKernel which can be used as the Composition Root to register our services. We will talk more about this class in the next section.
If we reference Ninject libraries manually using separately downloaded binary files, we should make the following changes to the MvcApplication class located under the Global.asax file:

  1. The MvcApplication class should derive from the NinjectHttpApplication class, rather than System.Web.HttpApplication.
  2. Instead of having the Application_Start method as the starting point, we should override the OnApplicationStarted method, and anything within Application_Start should go to OnApplicationStarted.
  3. We should override CreateKernel and use it for service registration.

The following code shows the CreateKernel method:

protected override IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Load(new ServiceRegistration());
    return kernel;
}

Even if we use NuGet to set up our project, we can delete the App_Start folder, and use Global.asax as described previously. In this case, we can remove references to the WebActivator and Microsoft.Web.Infrastructure libraries that NuGet has created. It is up to you which approach to use, as they do exactly the same thing in two different ways. The first one is easier to use and does not need any extra efforts to set up the application; while the second one uses the existing Global.asax file as the application startup point and doesn’t require additional files or libraries to be referenced. In this example, we use the Global.asax file as starting point. In the next section, we will use the App_Start and NinjectWebCommon classes which NuGet creates.
Let’s start implementing the presentation of customers list in our application. Open the HomeController class and add a constructor which introduces our ICustomerRepository interface as its parameter:

private readonly ICustomerRepository repository;

public HomeController(ICustomerRepository repository)
{
    this.repository = repository;
}

The next step is to modify the Index action method as follows:

public ActionResult Index()
{
    var customers = repository.GetAll();
    return View(customers);
}

It uses the ICustomerRepository interface to populate customers. Please note that we don’t need to create a new Model for customer and the one that we have already created in our domain layer is being used here. Then delete the existing Index.cshtml View and add a new one with List scaffold template and our Customer domain model as the Model class.
Now add the Create action methods as follows:

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(Customer customer)
{
    if (ModelState.IsValid)
    {
        repository.Add(customer);
        return RedirectToAction("Index");
    }
    return View();
}

The first one is called when the hyperlink Create New is clicked using HTTP GET method and the second one is called when the Create View is submitted using HTTP POST method. The created customer Model is passed to the Create method and can be added to the repository. Checking the ModelState.IsValid property is for server-side validation. We can now add a Create View for this action with Core.Customer as Model class and the Create scaffold template.

Validator injection

Now we need to add some validation rules to our Customer Model class. MVC framework supports different kinds of validation including annotation-based validation in which we use validation attributes on the properties of the Model to define the validation rules:

public class Customer
{
    [Required]
    public string ID { get; set; }
    [Required]
    public string CompanyName { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    [StringLength(10)]
    public string Phone { get; set; }
}

The validation attributes are not part of MVC library and this makes it possible to apply them to our Customer Model within our domain layer. This way, we can share these validation rules among other UI frameworks as well. We just need to reference the System.ComponentModel.DataAnnotations library in our domain project. MVC framework automatically validates the Model based on the provided attributes. But these attributes are limited to basic validation rules. What if we need to check whether the provided ID for our customer is not duplicated? In such scenarios we need to create our custom validation attributes:

public class UniqueCustomerIdAttribute : ValidationAttribute
{
    [Inject]
    public ICustomerValidator Validator { get; set; }

    public override bool IsValid(object value)
    {
        if (Validator == null)
        {
            throw new Exception("Validator is not specified.");
        }
        if (string.IsNullOrEmpty(value as string))
        {
            return false;
        }
        return Validator.ValidateUniqueness(value as string);
    }
}

By deriving from ValidationAttribute and overriding its IsValid method, we can define a custom validation attribute. This validator uses an object of the type ICustomerValidator to validate the given value which is a customer ID across the repository to check whether it is unique or duplicated. The following is the implementation of ICustomerValidator:

public class CustomerValidator : ICustomerValidator
{
    private readonly ICustomerRepository repository;

    public CustomerValidator(ICustomerRepository repository)
    {
        this.repository = repository;
    }

    public bool ValidateUniqueness(string customerID)
    {
        return repository.Get(customerID) == null;
    }
}

Validation is successful, provided the repository cannot find any existing customer with the given customer ID.
You may have noticed that in the UniqueCustomerIdAttribute class we didn’t introduce the ICustomerValidator interface as a dependency in the constructor. The reason is that it is not possible to apply an attribute which requires constructor parameters without providing its arguments. That’s why we used the Property Injection pattern, rather than Constructor Injection. Although this attribute should be instantiated by MVC framework, Ninject can inject the dependency before the IsValid method is called. Now you may be wondering that applying the [Inject] attribute in our domain layer, will make it dependent on Ninject. Well, it didn’t, because we didn’t use the Ninject version of the [Inject] attribute. Instead, we created another InjectAttribute class in our Core library. We discussed about how to set up Ninject to use another attribute instead of its internal [Inject] attribute in Chapter 3, Meeting real-world Requirements. This way we don’t have to have a reference to the Ninject library, and can even replace Ninject with other DI containers without needing to touch the domain layer.
We can now add the UniqueCustomerIdAttribute attribute to the validation rules of our Customer Model:

[Required, UniqueCustomerId]
public string ID { get; set; }

Filter injection

Filters are implementations of the IActionFilter, IResultFilter, IExceptionFilter, or IAuthorizationFilter interfaces that make it possible to perform special operations while invoking an action method. ASP.NET MVC allows us to apply filters in two ways, both of which are supported by Ninject:

  • Applying a filter attribute to the Controller or an Action method. This approach has been supported by MVC framework since its first version and doesn’t fully support DI.
  • Applying filters without attributes using filter providers which is introduced in MVC 3 and supports all DI patterns.

In the first method, the filter class derives from ActionFilterAttribute and the created filter attribute will be applied to a Controller or one of its action methods. Like other attributes, a filter attribute cannot be applied if it does not have a default constructor, so we cannot use Constructor Injection in filter attributes. However, if we use Property Injection using the [Inject] attribute, the dependencies get injected by Ninject without any special configuration. The following example shows how to define an action filter attribute which can pass action information to a performance monitoring service:

public class PerformanceFilterAttribute : ActionFilterAttribute
{
    [Inject]
    public IPerformanceMonitoringService PerformanceMonitor
    { get; set; }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        PerformanceMonitor.BeginMonitor(filterContext);
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        PerformanceMonitor.EndMonitor(filterContext);
    }
}

The implementation of IPerformanceMonitoringService will be injected by Ninject into the property PerformanceMonitor.
MVC3 or later versions of MVC, however, support a new way of applying filters which is DI compatible and allows all DI patterns including Construction Injection. Thus, the previous approach is not recommended in MVC3+.
The following example demonstrates how to define and apply LogFilter to our actions, which can log some tracking information about the called or being called action methods. The filter uses the ILog interface of the Log4Net library as a dependency:

public class LogFilter : IActionFilter
{
    private readonly ILog log;
    private readonly Level logLevel;

    public LogFilter(ILog log, string logLevel)
    {
        this.log = log;
        this.logLevel = log.Logger.Repository.LevelMap[logLevel];
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var message = string.Format(
CultureInfo.InvariantCulture,"Executing action {0}.{1}",            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
       this.log.Logger.Log(typeof(LogFilter), this.logLevel, message, null);    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var message = string.Format(
  CultureInfo.InvariantCulture, "Executed action {0}.{1}",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
 this.log.Logger.Log(typeof(LogFilter),
 this.logLevel, message, null);
    }
}

The LogFilter class uses the provided filterContext argument to determine the name of the Action method and its enclosing Controller. It then uses the injected implementation of ILog to log the tracking information. This class introduces two dependencies, one of which is the ILog interface and the other one is the log level under which the messages should be logged.
In order to tell MVC to use Ninject to resolve a filter, we need to register the filter using the BindFilter method of Kernel:

Kernel.BindFilter<LogFilter>(FilterScope.Action, 0)
     .WithConstructorArgument("logLevel", ("Info");

The first parameter defines the filter scope whose type is System.Web.Mvc.FilterScope and the second one is a number defining the order of the filter. This information is required by MVC to instantiate and apply filters. Ninject collects these information and asks MVC on our behalf to create an instance of the given filter type and apply it to the given scope. In the previous example, LogFilter will be resolved using Ninject with “Info” as an argument for the logLevel parameter and will be applied to all of the Action methods.
The ILog log parameter will be resolved based on how we register ILog. If you have used Log4Net before, you will remember that it can associate each logger to the type of class for which the logger is used:

public class MyClass
{
    private static readonly ILog log =
                       LogManager.GetLogger(typeof(MyApp));
}

This way, the logs can later be filtered based on their associated types.
In order to provide the required type for our logger, we bind it to a method rather than a concrete service. This way we can use the context object to determine the type of object requiring the log:

Bind<ILog>().ToMethod(GetLogger);

The following is the code for the GetLogger method:

private static ILog GetLogger(IContext ctx)
{
    var filterContext = ctx.Request.ParentRequest.Parameters
                    .OfType<FilterContextParameter>().SingleOrDefault();
    return LogManager.GetLogger(filterContext == null ?
        ctx.Request.Target.Member.DeclaringType :
        filterContext.ActionDescriptor.ControllerDescriptor.ControllerType);
}

In the previous code, the context.Request is the request for resolving ILog and ParentRequest is the request for resolving LogFilter. When a filter class is registered using BindFilter, Ninject provides the request with a parameter of type FilterContextParameter, which contains information about the context of the object to which the filter is being applied, and we can then obtain the type of the Controller class from it. Otherwise, this parameter is not provided, which means the logger is not requested by a filter class, in which case, we just use the type of the class requiring the logger.

Conditional filtering (When)

Now what if we are not going to apply the filter to all of the Controllers or the action methods? Ninject provides three groups of the WhenXXX methods to determine in which conditions to apply the filter:

  • WhenControllerType: This method applies the filter to the specified Controller types only.
  • WhenControllerHas: This method applies the filter to those Controllers with specified attribute type
  • WhenActionMethodHas: This method applies the filter to those Action methods with the specified attribute type

Apart from the mentioned three groups, Ninject offers a generic When method which can be used to define any custom conditions which cannot be applied using the previous methods.
The following code shows how to apply LogFilter to those action methods which have LogAttribute, given that the LogAttribute class is a simple class deriving from the Attribute class:

Kernel.BindFilter<LogFilter>(FilterScope.Action, 0)
 .WhenActionMethodHas<LogAttribute>()
 .WithConstructorArgument("logLevel", ("Info");

This is another example that shows how to apply this filter to all of the actions of the HomeController class:

Kernel.BindFilter<LogFilter>(FilterScope.Controller, 0)
 .WhenControllerType <HomeController>()
 .WithConstructorArgument("logLevel", ("Info");

Contextual arguments (With)

In the previous examples, we have always used a constant “Info” argument to be passed to the logLevel parameter. Apart from the standard WithXXX helpers, which can be used on normal bindings, Ninject provides the following WithXXX methods especially for filter binding:

  • WithConstructorArgumentFromActionAttribute: It allows to get the constructor argument from the attribute which is applied to the action method
  • WithConstructorArgumentFromControllerAttribute: It allows to get the constructor argument from the attribute which is applied to the Controller class
  • WithPropertyValueFromActionAttribute: In case of Property Injection, it allows to set the property using a value from the attribute which is applied to the action method
  • WithPropertyValueFromControllerAttribute: In case of Property Injection, it allows to set the property using a value from the attribute which is applied to the Controller class

In the following code, we get the log level from the LogAttribute class rather than always passing a constant string to the logLevel parameter:

Kernel.BindFilter<LogFilter>(FilterScope.Action, 0)
    .WhenActionMethodHas<LogAttribute>()
    .WithConstructorArgumentFromActionAttribute<LogAttribute>(
        "logLevel",
        attribute => attribute.LogLevel);

The previous code requires the LogAttribute class to have the LogLevel property:

public class LogAttribute : Attribute
{
    public string LogLevel { get; set; }
}

Custom awaitable and awaiter types in C# 5.0 asynchronous

In C# 5.0 you can use the await keyword to await an awaitable object. But what is the minimum requirement for an object to be considered awaitable by C#? Interestingly there are no interfaces to be implemented in order to be considered awaitable!
Having a parameter-less method named GetAwaiter() which returns an awaiter object is the only convention for a type to be recognized awaitable by C#:

// This class is awaitable because it has the GetAwaiter method, provided MyAwaiter is an awaiter.
public class MyWaitable
{
    public MyAwaiter GetAwaiter()
    {
        return new MyAwaiter();
    }
}

Now the question is how to make a type awaiter? The minimum requirements for a type to be awiater are implementing the INotifyCompletion interface, and having the IsCompleted property and the GetResult method with the following signatures:

public class MyAwaiter : INotifyCompletion
{
    public void OnCompleted(Action continuation)
    {
        
    }

    public bool IsCompleted
    {
        get
        {
            return false;
        }
    }


    public void GetResult()
    {
       
    }
}

Batch edit TeamCity build configurations

TeamCity supports parameters, so if you are dealing with so many build configurations on your TeamCity server and you need to change something in all of your projects, the best practice is to use parameters or build templates. But what if you need to change a value in multiple build configurations or multiple projects and that value cannot be (or is not) defined as a parameter? In such cases you can use the following shortcut instead of going through each build configuration to edit them:

  1. On the TeamCity machine, open the data directory. It can be identified using the TEAMCITY_DATA_PATH environment variable.
  2. Open the corresponding directory to your required project from %TEAMCITY_DATA_PATH%\config\projects.
  3. All of the build configurations are stored as XML files in the buildTypes directory.
  4. Use a powerful text editor (e.g. Notepad++ ) to batch edit the files.
  5. From the TeamCity administration page, go to Server Administration\Diagnostics\Caches and reset buildsMetadata.

After a couple of seconds the changes should be reflected in all of your build configurations.

Logging Best Practices

In this article I will cover the best practices of logging in terms of the following concerns, regardless of what logging framework we use:
1- What to log
2- How to choose logging levels
3- Where to log

What to log

First of all logging is not a constant forward process. You don’t have to log all you need and then stop touching it. It can be an ongoing process and you can refactor your logging codes as your needs. Although we don’t have to write every possible event of our application upfront just in case we might have need it in future, there are some minimum events that we should log at first place.
All errors and critical conditions should be logged. It doesn’t mean that we should log an error in every Catch clause, because whether or not the caught exception is an error to log, depends on what that exception is and how you are going to handle it. For example your Catch clause might have caught a predicted “Access Denied” exception and have made the appropriate decision. This is not considered as an error but a lower log level like Debug never harms. Any unusual circumstances should be logged even if they don’t effect the application. Consider that the last example is not considered as an unusual circumstance either. It is also a good idea to log the starting point and end point of every process. Ideally if we have singly responsible methods, that would be logging at the beginning and end of each method. We don’t have to log every single parameter of each method but we can log some critical information such as endpoint URLs, connection strings or IDs. We can add more debugging logs later on if we need to. Never worry about too much logs, because almost all of the logging frameworks allow you to disable your logs partially. You can filter them based on the type for which you have logged or the level of your logs. So it is important to name your loggers after their surrounding types or at least give them a meaningful name, as the logger names will later be used for grouping and filtering the logs. It is also crucial to choose appropriate logging levels.

How to choose logging levels

I will never use Info logging level for Debug purposes.
Although logging frameworks allow us to have as many custom logging levels as we need, there are usually several default logging levels that are mostly used:
Fatal: Usually the highest level. Used when a problem stops the application’s functionality. This kind of errors usually happen because of unexpected circumstances for which no alternative solutions are provided. For example, no disk space, network disconnection or any unexpected circumstances which stops the application.
Error: This level is used when an error occurs but it is handled and it doesn’t interrupt the application. It may cause some minor problems or may lead to some consequences in the future. For example a connection to the master database is refused and we redirected the request to the slave to handle the issue.
Warn: For logging unusual circumstances that need consideration or they may lead to future problems. Low disk space is an example which may needs a warning level log.
Info: We use this logging level for monitoring the application’s process. It should be so that when someone reads the logs they can realize what is going on in the application. They shouldn’t contain debugging data or repeated information. So It’s not a good idea to use Info logging level in long loops.
Debug: This is the lowest logging level and it usually contains too much information that we often tend to filter this level out and use it only while debugging the application. It can contain any details that normally we don’t need to see in the logs.

Info or Debug

It is sometimes confusing whether to use Info or Debug. One of the common mistakes is that some developers use debug level for logging of dependencies. For example when a business object is using a data access object which needs to log some database operations, it may look like the data access object should use the debug level as it is serving a lower level functionality. However, when we choose the logging level for a component, we should consider that component in isolation. Any class can be a dependency for a higher level type and at the same time it may depend on other lower level components. When we read the logs we can filter only those components that we need to monitor or debug. So the lower level types should also have their own levels of Info and Debug. This is easier to handle when the application concerns are separated into individual classes. Otherwise you will have to consider a lower priority for some of the multiple concerns which are being addressed in a single class and choose Debug level for them to distinguish them from the main concerns of the same class.

Where to log

The easiest way to log is logging in between your code. But ideally we should consider that each object should have its own concern and logging is yet another concern. So we should separate it and put it somewhere else. Since logging is not limited to a specific layer of the application, it is a cross-cutting concern and two of the best practices to address such concerns are the Decorator design pattern and Aspect Oriented Programming (AOP). Both approach allow you to put your logging logic in separate classes and attach them to the type which is going to be logged. They allow you to log prior to, after, in case of success or in case of failure of a method. One may argue what if they need to log in the middle of a method. The answer is if each method is dealing with a single responsibility you won’t need that. The following code needs to be refactored so we won’t need to log in the middle of the Transfer method.

void Transfer(string source, string dest, Money amount)
{
    log.Info(&amp;amp;amp;amp;quot;Transferring...&amp;amp;amp;amp;quot;);
    log.Info(&amp;amp;amp;amp;quot;Debiting {0}...&amp;amp;amp;amp;quot;, source);
    ... // Debiting implementation
    log.Info(&amp;amp;amp;amp;quot;{0} debited.&amp;amp;amp;amp;quot;, source);
    log.Info(&amp;amp;amp;amp;quot;Crediting {0}...&amp;amp;amp;amp;quot;, dest);
    ... // Creddiing implementation
    log.Info(&amp;amp;amp;amp;quot;{0} debited.&amp;amp;amp;amp;quot;, dest);
    log.Info(&amp;amp;amp;amp;quot;Transfer finished.&amp;amp;amp;amp;quot;);
}

The followoing shows how to refactor the above code:

void Transfer(Account source, Account dest, Money amount)
{
    log.Info(&amp;amp;amp;amp;quot;Transferring...&amp;amp;amp;amp;quot;);
    source.Debit(amount);
    dest.Credit(amount);
    log.Info(&amp;amp;amp;amp;quot;Transfer finished.&amp;amp;amp;amp;quot;);
}

The Debit and Credit implementation should be moved to the Account object.

public class Account
{
    public string Number {get;set;}

    public void Debit(Money amount)
    {
        log.Info(&amp;amp;amp;amp;quot;Debiting {0}...&amp;amp;amp;amp;quot;, this.Number);
        ... // Debiting implementation
        log.Info(&amp;amp;amp;amp;quot;{0} debited.&amp;amp;amp;amp;quot;,  this.Number);
    }

    public void Credit(Money amount)
    {
        log.Info(&amp;amp;amp;amp;quot;Crediting {0}...&amp;amp;amp;amp;quot;,  this.Number);
        ... // Creddiing implementation
        log.Info(&amp;amp;amp;amp;quot;{0} debited.&amp;amp;amp;amp;quot;,  this.Number);
    }
}

Another moral of the above example is that the calling code should not take care of logging for the called method. Each method should log their own responsibilities only.