Sunday, July 13, 2014

OWIN - Katana Web Application

OWIN defines the standard interface between .NET web servers and web applications. KATANA is OWIN implementation for Microsoft servers and frameworks.

If you are not familiar with Katana, read this article An Overview of Project Katana which talks about the history and goals behind OWIN/Katana.

In this post I want highlight Katana's architecture around decoupling host and server from the application.

Katana Architecture

Lets look at some hosting options for OWIN application

  • Custom Host: You can host owin application in a console application or OwinHost (prebuilt Katana host) using Microsoft.Owin.Host.HttpListner.
  • IIS: Owin applications can be hosted in IIS using Microsoft.Owin.Host.SystemWeb server package. Unfortunately with this package, you do not get a lean host as it adds the standard ASP.NET piple. Thats where Helios comes to rescue where we can get all the benefits of IIS without the traditional ASP.NET pipeline.
  • Node.js: Using connect-owin middleware, we can host Owin application in Node.js too.

I have created a demo web api application which highlights how easy it is to switch between different hosts without changing your application. The source code is available here.

Sunday, September 15, 2013

Glimpse - ASP.NET Debugging

As the name suggests Glimpse allows you to glimpse into what is happening on server side of your ASP.NET application. It can save you lot of time whilst debugging by providing plethora of information and also help you learn and understand the internal mechanics of ASP.NET.

You can install Glimpse using Nuget. Ensure you install the right packages for ASP.NET and the features you want use.

You can also use the package manager console to install Glimpse

install-package Glimpse.MVC4
install-package Glimpse.EF5

Glimpse is quite extensible and there are many other packages available from the community.

Once you have installed the packages required for your project, you need to turn on Glimpse by going to http://yourproject:port/Glimpse.axd

Now you can see stats from Glimpse hud in the bottom right corner of your application.

You basically turn Glimpse on and off with cookies, it does not run in background. You can setup security policy to control when you want to use it. For example, locally when debugging or with a specific cookie value, or your authorization role, or parent switch in the web.config.

The Glimpse view is inspired from developer tools like fire bug. The great thing about it is that each tab is a plugin itself and is all built with CSS and javascript.

You can see all the information from your Configuration file like your connection strings. Information on what environment the application is running on. Even SQL queries being run by entity framework and the time taken for them to complete.

Since the server is collecting information on all sessions, you can pull out a popup browser window of Glimpse and connect to sessions from other browsers. For example, you could debug a session for a customer remotely whilst they are performing actions.

I think it is a great tool which should be used in every ASP.NET project. You should watch this great introduction video on Glimpse site by Anthony and Nick.

Sunday, August 25, 2013

Command Query Separation

'Command Query Separation' (CQS) is a design principle by which the methods of an object are categorised separately:

Commands: Changes the state of the system and does not return value.

Public Course Courses.Find(courseName)

Query: Returns a result without having any side effects on the state (i.e. does not alter the observable state of the system).

public void Course.AllocateFaculty(faculty)

Whilst CQS is a sound principle, but there are exceptions in many cases. Some these violations may be acceptable but other could be potentially dangerous.

Lets consider an example where this violation maybe acceptable. The classic violation is Stack.Pop() which is a command and a query. It removes and returns the object at the top of the stack. Another simple example which breaks the pattern but may be useful in multi-threaded programs:

public int IncrementCount()
  int copyOfCount;
    copyOfCount = _count;
  return copyOfCount;
You can manage this better making sure that if a command returns a value, it will go through an out parameter and the command will have a meaningful name IncrementAndReturnCount.
public void IncrementAndReturnCount(out int latestCount)
    latestCount = _count;
There are however instances where CQS violations cause dangerous side effects that can be difficult to debug. Consider the following method in the Course class:
public void GetSchedule()
    this.Schedule = new Schedule();
  return this.Schedule;
It may seem very harmless that the method instantiates the schedule if it is null. But imagine someone added a new operation to send an alert all the allocated faculties of courses which do not have a schedule set.
foreach(var course in Courses)
  if(course.GetSchedule() == null)
By adding command behavior to GetSchedule(), we have accidentally broken the code. Now we must spend time to re-factor the original code.

We can say CQS is clearly intended as a programming guideline rather than a rule for good coding.

Monday, August 19, 2013

Make your web site mobile friendly

Last year on an average 15% of traffic to sites was from mobile devices and this will continue to grow.

There are many solutions to optimize your site for mobile devices. For example adaptive design, responsive design, website conversion. Each has pros and cons, and ranges from free to thousands of dollars. The amount you spend depends on the requirements of your business and your visitors. We will walk through things you can do in context of responsive design to make your site mobile friendly.

Mobile meta tags

We can improve users browsing experience on certain devices by using the mobile webkit.


This meta tag tells the browser how content should fit on the device's screen.

The above example tells the browser to set the viewport to the width of the device with initial scale of 1.0. We can turn off zooming by setting user-scalable=no or can limit the scaling level.

You can also set the width to a pixel value (e.g. 320px) but note not all devices have same width so it's better to stick with device-width and let browser take care of the rest.

You can look into some device specific settings on Android and iOS to further improve user's experience.

Home Screen Icons

iOS and Android devices also accept a rel="apple-touch-icon" (iOS) and rel="apple-touch-icon-precomposed" (Android) for links. They get used as icon on the user's home screen when they bookmark your site.

CSS3 Media Queries

Media queries enables the content's presentation to be customized to a specific range of output devices without having to change the content itself.

Screen Sizes

The example below shows how we can target mobile devices

A media query with the "only" keyword will cause non CSS3-compliant browsers to ignore it. The following example would target tablet screen sizes.

Some of the styling changes that you should enforce:

  • Reduce extra whitespace/padding across the site. Space is premium!
  • Remove :hover states. They'll never been seen on touch devices.
  • Adjust the layout to be single column.
  • Remove the box-shadow around big container div. Large box shadows reduce page performance.
  • Remove opacity changes. Changing alpha values is a performance hit on mobile.
You can read more about media queries here.

CSS Frameworks

In context of responsive design CSS frameworks have many benefits. A well-built CSS framework or boilerplate can streamline the design process, save huge chunks of development time and ensure your website scales properly on all devices. Here are few you can look into:

Saturday, March 12, 2011

Silverlight: Manage XAP Files

The XAP file size for Silverlight projects can become quite large if they are not managed properly. This will cause the initial loading time to increase and slow performance of your application.

Manage common assemblies

To address the duplication of shared assemblies in multiple XAP files, we have couple of options.
  1. The first is to reference all the shared assemblies in the shell application XAP file. Then we can go to the reference of these shared assemblies in each of the modules and set the Copy Local property on the reference to false. This causes the referenced shared assemblies to not be included in the compiled XAP file for that module. However, at runtime, the one provided by the shell application XAP file will also be available to the modules.

    • All the common assemblies are downloaded once.
    • XAP file size for other modules decreases.
    • Subsequent requests are faster.

    • The initial download size will be large.
  2. The second approach is to use application library caching in Silverlight. To use this feature, we need to go to the properties of all the Silverlight projects and select the check box labeled Reduce XAP size by using application library caching. When we do this, any referenced assemblies that have the right metadata files collocated with them will not be included in the XAP file. Instead, they will be placed in a separate .zip file, and the .zip file will be referenced by the XAP file’s ApplicationManifest.xaml file as an external part. These files are added to the browser cache so that they can be reused on subsequent visits. All downloaded files are subject to the caching configuration settings on the server and in the browser. In a typical configuration, files are downloaded only if they are not in the cache or if they are newer than the cached versions. Libraries from Prism, Silverlight SDK and Toolkit have the required metadata files to use this feature.

    If you want to leverage of the functionality for our assemblies, we need to provide the proper metadata files. More about this has been discussed in the following article: How to: Use Application Library Caching

    You can test this option with your application using Fiddler, and see that shared assemblies are only downloaded when they are required and are not downloaded on subsequent requests.

    • XAP file size of all the module decreases.
    • Common assemblies are downloaded separately as they are required.
    • Downloaded common assemblies are cached and available to all modules until new versions are provided. (subject to the caching configuration settings on the server and in the client browser)

    • We cannot use application library caching and out-of-browser support in the same application. Out-of-browser applications require all startup assemblies to reside in the application package.
    • We need to ensure the clients are not using old cached assemblies when new versions of the common assemblies are deployed.

Improve XAP file compression

XAP files are basically just standard ZIP files with different extension, so we can use compression tools (like Winrar) to decrease the file size even more by using the best compression algorithm.

We can create batch file that can be added to all the Silverlight projects to automatically re-compress the project’s XAP file more efficiently. And we can do this easily by adding command in the project’s post-build events. Around 5% to 20% reduction can be achieved depending on the contents of the XAP file.

Sunday, January 16, 2011

The Repository Pattern - Entity Framework

In many applications, business logic accesses data from data stores. There are lot of potential issues when accessing them directly, for example:
  • Code duplication
  • Higher chances of programming errors
  • Problems in testing business logic in isolation from external dependencies
  • Difficulty in implementing centrally managed consistent rules and logic
So it is a good idea to build a layer of abstraction which mediates between the business layer and data source layer of the application. This is where repository pattern comes in to achieve our objectives.

What is Repository
As described on Martin Flower's website:

"A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers."

We will discuss the implementation of repositories in context of DDD(domain driven design) for entity framework. Using generics we will create a base repository which will have all the common functionality. And then we will inherit from the base repository to create model/domain specific repositories.

Repository Interface
This is how the repository interface will look like. IRepository<T> is the contract where T is a POCO class. For testing we can later write an fake implementation to remove the dependency.

    public interface IRepository<T> where T : class
        IQueryable<T> GetQuery();

        IEnumerable<T> GetAll();
        IEnumerable<T> Find(Expression<Func<T, bool>> where);
        T Single(Expression<Func<T, bool>> where);
        T First(Expression<Func<T, bool>> where);

        void Delete(T entity);
        void Add(T entity);
        void Attach(T entity);
        void SaveChanges();

Generic Repository Implementation
The base repository takes an IObjectContext as a constructor argument for dependency injection.

    public abstract class EFRepositoryBase<T> : IRepository<T> where T : class
        readonly IObjectContext _objectContext;
        readonly IObjectSet<T> _objectSet;

        public EFRepositoryBase(IObjectContext objectContext)
            _objectContext = objectContext;
            _objectSet = _objectContext.CreateObjectSet<T>();

        public IQueryable<T> GetQuery()
            return _objectSet;

        public IEnumerable<T> GetAll()
            return GetQuery().ToList();

        public IEnumerable<T> Find(Expression<Func<T, bool>> where)
            return _objectSet.Where(where);

        public T Single(Expression<Func<T, bool>> where)
            return _objectSet.Single(where);

        public T First(Expression<Func<T, bool>> where)
            return _objectSet.First(where);

        public void Delete(T entity)

        public void Add(T entity)

        public void Attach(T entity)

        public void SaveChanges()

Domain specific repository
In these derived repositories you can add the domain/model specific query operations. Here is how the interface and implementation of a User model repository will look like.

    public interface IUserRepository : IRepository<User>
        //add user specific operations

    public class EFUserRepository : EFRepositoryBase<User>, IUserRepository
        public EFUserRepository(IObjectContext objectContext)
            : base(objectContext)
            //add user specific operations

Monday, November 29, 2010

Microsoft Light Switch

Microsoft has come out with a rapid-application development tool to build applications for the desktop, the web, and the cloud. Microsoft is promoting LightSwitch as the simplest way for developers of all skill levels to develop business applications, but it seems to be targeted more at inexperienced developers.

You can download the beta version and look at some demonstration videos here.