Thursday, September 10, 2015 #

What's new in C# 6.0

 

What's new in C# 6.0

In this article, I am going to talk about new language feature of C# 6.0. I am personally liking these features a lot because they help in writing clean and understandable code.

With the release of Visual Studio 2015 comes the much awaited version 6 of c#. according to mads togersen (PM of C# language team), this version introduces no big concepts but instead ships many small features that helps you write better and clean code.

 

Getter-only Auto-Properties

I am sure everyone has seen and used several types of properties and of those, auto-properties are the short hand and time saver ones. I used auto-properties most of the times. however, there was one limitation with auto-properties in the sense there was no auto feature for read-only properties. if you’d wanted to get one, then you would have to type a read only backing field and serve the need. but with c# 6.0 you get the read only auto-properties.

it worked same as auto properties but when you create a read only auto property, c# compiler create a read only backing field and lets you assign this property in the constructor, much like how a read only field would work.

image

also, if you needed to initialize an auto-property to much like a variable then that's now possible with c# 6.0. see below code-snippet on how this is done.

image

 

Using Static Classes

if you are dealing with static classes, and often calling static-class-name.method, then you no longer need to do that, C# 6.0 has come with simplifying this as a coding style so you are no longer needed to keep typing static class names through out your code. instead, you can directly call static method and it will still function as expected. To use this coding convention you should specify in using statement as using static class-name. check the below code snippet to understand this better.

image

 

observe that I have added an using statement along with static keyword and calling “WriteLine” method directly, instead of writing as “Console.WriteLine”

 

String Interpolation

Another great feature of C# 6.0 is the string interpolation. ok, so let me ask you this first, how many times you have written string.format in your code? you would probably reply hundreds of time and that’s great, now another one, how many times you would have to count and make sure that supplied arguments are in order? and yes, that was some inconvenience to developers. why do I have to specify arguments first and then values, that sometimes leads to confusion and inconvenience. C# has added a great feature in terms of string interpolation that you no longer need to specify arguments ( 0, 1, 2, 3..) and then values. you can put your values directly inside this string.format and get thing done.

lets see this in action:

 

image

note that how convenient its compared to older version of string.format.

 

Expression Bodied Properties

Pretty much like writing a lambda expression, now properties have the facility to expose a lambda instead of a method definition. this is again to encourage clean and maintainable code.

image

 Another example would be

image

 

I am sure by now you must be thinking and appreciating how much these features will help you write clean and maintainable code.

Index Initializers

to understand Index initializers, first check out the code below.

image

there is a simple class Employee__OLDWAY – that I am referring to as old way of doing things, nothing great but look at the ToJson Mehtod, which is initializing a new JOnject and then filling in index initializers as firstName and lastName, and explicit need to create an object is required so that we can return it back.

not anymore you have to do this. because of Index Initializers your new and improved code would look like below ( a much simpler and clean ). isn’t it?

image

 

Null-Conditional Operators

Checking a null condition looks like some in-built mechanism in your C# code, doesn’t it? however, there is now a cleaner approach to this. there wont be a need to add several conditions explicitly to check nulls.

lets see how. but before that, lets take an example of converting a json to object.

image

if you look at the class above, the whole intent of FromJson method is to take a json object and convert it to Employee object, but the majority of code is typed to check the null conditions.

C# 6.0 gives a better way to get rid of these nuisances. take a look at code below. C# 6.0 introduces Elvis operator, “?.”, what “?” does is, it checks if the left part is  not null, if its null then the whole expression is null, if its not null, then it goes further and executed the right part, this way it ensures there are no extra null checks are in the code and provides a better and clean way to write null conditions. cool, isn’t it? take a look at improved code below.

image

 

nameof operator

nameof operator is also new addition to C# 6. its usage is simple, it simply returns the name of a type. you would ask, why do we need it. consider a scenario where you are having to return a name of a type and you hardcode the name and return. it works fine, but what if some new developer comes in and changes the name of the your type, the hardcoded string is now out of sync. to address this particular situation, C# 6 has introduced nameof operator, which you use in exactly these kind of scenarios to have peace of mind even when someone changes the name of your type, a correct name will always be returned wherever you need it.

for example,

image

returning a hardcoded string is a problem, so see below how nameof operator solves this,

image

 

Exception Filters

Visual basic and F# both allows exception filtering, making a condition in your catch blocks and allowing you to filter it based on conditions. this was missing piece in C#, but with 6.0 its has matched what other .net languages offer.

take a look at code-snippet below.

image

the catch block will filter the exception based on provided condition.

Also, Catch and finally blocks “finally” have incorporated async processing

see below,

image

 

And that concludes my article on all the latest features of C# 6.0.

 

Link to sample source code

https://github.com/chetanvihite/csharp6__features

 

Final Thoughts

I hope you have enjoyed reading this article and learnt something new.

go ahead and download VS 2015 and start exploring these features on your own.

Happy Coding!

 

 

Posted On Thursday, September 10, 2015 9:45 AM | Comments (0)

Monday, September 7, 2015 #

Understanding Filters in ASP.net MVC

 

Filters in ASP.net MVC

Filters are interesting and somewhat unique part of ASP.net MVC. Filters are designed to inject logic in between MVC request life cycle events. Filters provide developers with powerful ways to inspect, analyze, capture and instrument several things going around within MVC application. Understanding when each of the filters kick in and play the role can greatly enhance the way developers write logic. plus it gives a very interesting perspective to understand how filters run at multiple points in the request life cycle and have the power to control further execution or  prevent request from executing futher. As of MVC5, there are 5 types of filters.

image

 

Authentication filters

Authentication filters are new addition from MVC 5. These filters kick in first in the request life cycle and perform the authentication logic.

Authorization filters

Authorization filters are executed after the Authentication filters successfully executed and authorizes users roles to ensure current user has access to request resource.

Action filters

Action filters are executed next in the request life cycle and execute any custom logic you may want to perform before and after action execution.

Result filters

Result filters are executed before and after result execution.

Exception filters

Finally, the exception filters are executed when there is an exception during processing of request.

following diagram depicts when each of the filter fires in the MVC request life cycle.

as you can see from the below diagram, as soon as the controller starts execution through Action Invoker, Authentication and authorization filters are the very first filters to be triggered, followed by model binding which maps request and route data to action parameters. which is then followed by Action filter execution, OnActionExecuting fires before the action has been executed and OnActionExecuted is fired after te Action method has finished execution. last comes the Result filters, OnResultExecuting gets fired before executing result, and OnResultExecuted gets fired after the result has been executed. exception filter are special filters in the sense that they get fired as soon as an exception is thrown and you can write your custom logic to log exception or redirect user to a error page and take appropriate action in this filter.

image

Filters in Action

Like any other life cycle events of MVC, implementing filters in MVC is very easy.

Authentication Filter

lets start with Authentication Filter, this filter is recent addition to MVC 5, there is no way you would be able to implement this filter in your older apps. you can leverage this filter for performing authentication related stuff. in the request life cycle, after the URL Routing module has selected the route and controller have been initialized, the first thing that kicks off in the Action method execution is Authentication Filter.

To implement Authentication Filter, you must implement IAuthenticationFilter interface along with deriving from FilterAttribute base class. the key here is IAuthenticationFilter interface that lets you implement two methods, OnAuthentication and OnAuthenticationChallenge. OnAuthentication is primarily used for setting identity Principle or any other type of authentication that your application understands, OnAuthenticationChallenge is the special methods which gets executed just before the result execution. the reason might be that as a developer you would want to do some checks here like authorization or redirecting user to a different login page in case of a HttpUnauthorisedResult case. OnAuthenticationChallenge is used to add a “challenge” to the result before its returned to the user. here is how you would implement it:

 

image

 

don’t worry about “StoreInSession” method call for now, its just logging the events in the session, we will see the output at the end of this to understand what its doing.

Action Filters

Action Filters are the filters that gets executed before and after a method, you can use this filter to implement instrumentation like action performance and other things. to implement Action filter, you need to implement IActionFilter interface and derive from FilterAttribute base class. IActionFilter gives you two methods to implement, OnActionExecuting and OnActionExecuted,. OnActionExecuting gets executed before the Action mehtod execution and OnActionExecuted gets fired after the action method execution.

image

 

Authorization Filter

Authorization filter has been in use for performing authentication and other stuff prior to Authentication filters. to implement Authorization Filter you need to implement IAuthorizationFilter interface and derive from FilterAttribute base class. the interface IAuthorizeFilter gives you one method to implement, “OnAuthorization” where you can perform authorization related checks.

 

image

 

Result Filter

Result filter are the filters that gets executed before and after executing result to a particular http request. you can leverage these filters to do various checks like instrumentation, or manipulating results before they are sent back to browser etc. to customize Result filter, implement IResultFilter interface along with deriving from FilterAttribute class. 

 

image

 

Exception Filter

Exception filters are special filters in the sense that they occur when there is an exception in request execution. you can implement and customize this filter to catch exception as it occurs and probably log it to file system or database and then redirect use to a error page or take any other action that suits your need. to customize this filter implement IExceptionFilter and derive from FilterAttribute base class.

 

image

 

finally, once you have customized all your filters, you would need to go and tell MVC framework to hook up your filters in the request life cycle. this process is called as registration of filters in MVC life cycle. just by implementing some interfaces doesn’t lead to automatic discovery of new customized version of filter to take into effect.

Registering filters could be done in two ways, the first one is to put as controller or action attributes, but in that case you would need to remember putting it on all the controller or actions. another way of registration is to register at a global level, that way you are assured that it will executed for all the controller s and actions.

for option#2, go to Global.asax.cs and under Application_Start event register the customized filters as follows.

image

 

that’s it. once you have registered your filters MVC framework will take care of invoking them through out the life cycle.

Coming back to output of capturing events and logging details in session.

refer to the attached source code, link is available at the end of this blog. in a nutshell, all I have done in the source code is to implement all the filters and adding a log entry into the Session to see which ones gets fired and the order of it. ( just to validate my diagram at the beginning ).

the output of the application is as follows, as you can see OnAuthentication is fired first, followed by OnAuthorization, then Action fitlers (OnActionExecuting and OnActionExecuted), followed by OnAuthenticationChallenge ( which I told earlier that it will be fired before executing results), followed by Result filters (OnResultExecuting and OnResultExecuted ). you might be wondering why OnResultExecuted is not shown here? that because OnResultExecuted  is fired after sending result back to browser, i.e. we see this page and that concludes our request.

image

 

Final Thoughts

MVC is very flexible and robust framework, and Microsoft has written this framework with lot of thinking in mind. custom filters are great example of MVC’s features. use these filters as and when required and leverage one of best framework by Microsoft.

 

Link to Source code

https://github.com/chetanvihite/FiltersinMVC2

As always, feedback, suggestion or comments are always welcome!

 

Happy Coding.

Posted On Monday, September 7, 2015 9:18 AM | Comments (0)

Friday, August 28, 2015 #

Getting started with Apache Cordova

Building cross platform Mobile Applications using Apache Cordova – Part 1

 

Apache Cordova is an open source platform for building cross platform mobile applications that runs on several mobile devices including iPhone, Android, Blackberry, Windows etc. Cordova facilitates writing code in one language and enables it to ship to several mobile devices and platform very easily. Cordova significantly reduces development efforts in order to build cross platform mobile applications. all these features, makes Cordova very special and popular. 

Problem

 

First of all, building a cross platform mobile application is difficult. It takes a lot of time and effort to build and maintain a cross platform application. each of the mobile operating system has its own language and API that you need to understand and build your application, which is not easy and takes a lot of time.

so, we e need a solution that solves our problem and gives us freedom to use our existing skills and build something quick that works on all the major mobile operating systems and serve to our need,

Apache Cordova does exactly this, it gives you the ability to use your existing HTML and  JavaScript knowledge along with providing OS specific APIs that you can build your applications on top of, then compile it for targeted platform and achieve cross platform application development experience with very little effort.

this strategy saves you a lot of time and energy involved in building cross platform applications.

History

 

Before Apache Cordova came into existence PhoneGap was conceptualized and developed during iPhone Dev Camp in 2008. PhoneGap’s first stable release was in 2009 followed by version 1.0 in 2011.

PhoneGap was developed by a company called Nitobi, which was later acquired by Adobe. it was Adobe who denoted PhoneGap to Apache foundation and named it Apache Cordova.

since its inception, Apache Cordova has been supported by big names and companies and has been open source. there is wide community that supports Apache Cordova and regularly maintains it. and that’s why it is so popular platform to build cross platform mobile applications.

How Apache Cordova works?

 

Apache Cordova has two major components, the first one launches your HTML application inside mobile browser and second one lets you interact with mobile specific hardware and APIs through your JavaScript code.

It all starts with instantiating a native shell which in turn starts a mobile browser inside a Mobile App and signals browser to launch the HTML that was packaged with your Mobile App. and that’s how your application runs inside a mobile in general. For most of the part, Apache Cordova is responsible for hosting your HTML app inside its shell and also lets your interact with device specific APIs needed by your application.

Apache Cordova supports variety of APIs that your can use in your application to interact with device and use its features. the API list pretty much covers all the major features of all major mobile devices so you are covered if you don’t require any other custom feature that you don’t intent to use in your Mobile App.

On a high level, it supports, Battery Status, Camera, Console, Contacts, Device, Accelerometer, Compass, Dialogs, File System, File Transfer, Geolocation, InAppBrowser, Media, Media Capture, Splash Screen, Vibration and StatusBar. In my personal opinion most of the business applications require only these features to achieve their goals and fits perfectly for most of the business cases.

 

Why Apache Cordova

 

There are several reasons to choose Apache Cordova as a go to platform for building Cross platform mobile applications.

>> I will start with Simple application where actual native feel is not important.

>> since you can build application using your existing HTML and JavaScript coding skills, learning a new skill set is not required.

>>fits the bill when you want to go to market early, without waiting for months to be able to ship your application on all major platforms.

>> when you want to reuse your existing apps to ship as a mobile app.

you wouldn’t want to choose Apache Cordova when you are very concerned about look and feel of the application or if you have complex UI and need custom API usage. Speed is consideration, only when you are doing some heavy processing or data processing on client side, in that case you wouldn’t want to go ahead with Cordova.

Ok, so far we have seen what Apache Cordova is, its background and how it approaches cross platform mobile app development.

this was part 1 of my series on building cross platform mobile application using Apache Cordova.  Stay tuned for next part where I will talking about development options, environment, a simple Hello World App and much more.

Thanks and Happy Coding!

Posted On Friday, August 28, 2015 10:13 AM | Comments (0)

Friday, July 24, 2015 #

Introduction to KnockoutJS

Introduction

Knockout, developed by Steve Sanderson, is free open source JavaScript library available under MIT license. It was first released in 2010 and since its initial release it has caught attention of industry and has been very popular. It is written purely in JavaScript and works on any web platform, any web browser and has no other dependencies. Features like easy bindings, observables and template support makes it truly unique and very useful for any enterprise application. It’s very robust and takes care of lot of heavy lifting for your application and provides an elegance interface to build apps. It was developed with keeping Model-View-View Model in mind. Note that, it’s not replacement of jQuery and it doesn’t help low level DOM manipulation and event handling, rather it addresses a totally different problem related to UI to Data manipulation.

At a very high level Knockout offers:

Ø Declarative bindings of UI controls to your Data model

Ø Automatic UI refresh based on your data

Ø Dependency Tracking

Ø Template support

Bindings:

To understand the simplicity and power and knockout bindings, imagine a simple scenario where you have to display employee information on UI:

If I choose to do this without knockout, then I will write something like below:

clip_image002

This is just to show data on the page, if we were to save the updated data, then again few more lines of code for save operation too. The more the information, the more the javascript. I have to keep track of all the data that is being displayed and save after it has been submitted. This situation leads to unmanaged Javascript code over the period of time. We don’t want out code to be unmanaged or messy.

Well, fortunately, knockout has a solution for us. Let’s take the exact same problem and we will try to solve it with Knockout this time.

clip_image004

In the sample code shown above, we have declared our UI bindings using data-bind attribute, note that property names are directly bind’d here, and then in scripts we have our view-model with some default data. Now the most important thing is the saveToJson method in which we are using a knockout helper method ko.toJSON which returns json data for any object. Now you can take this json data and pass it to server to perform save operation. Cool…isn’t it?

You can keep extending your UI for more information (like address, phone number and personal information) and just update your binding, that’s all! Knockout will keep track of your UI and data for you. As you see it takes care of all the heavy lifting’s for you and provides you a simple interface to hook up your view model. The end result is also very convincing, a clean and better way of doing things.

Observables:

Observable is another powerful feature of Knockout. Observables are declared using ko.observable() function call and then knockout keeps track of its value. You can extend observables to update other objects, properties, raise events and even perform validation on entered value. Let’s take a very simple example of asking user first name and last name and printing the full name.

 

Check out the above code snippet, we are not doing much and yet we have everything working. Unlike jquery, neither we are capturing any events nor we are worrying about data manipulation, knockout is doing everything forclip_image006 us.

Let’s review the code above to understand how it’s working without much JavaScript code. The very first thing is the HTML markup, in which we have controls and binding information, the only extra thing I have done in this sample is to add a valueupdate event, which will be fired as soon as client updates anything on the UI for that binding. This is to get real time updates from UI. Next is, View model, which has two properties and both of them are observables. Define a property as observable, if you want knockout to keep track of its value, this is pretty much like two-way binding in Silverlight. Lastly, the interesting piece, full name property which is actually a computed function – so in knockout world, if you have any such properties that you want knockout to calculate at runtime, then, you should use ko.computed property descriptor. It will hook up all the dependent observables on the computed property and anytime dependent observable’s value changes, it re calculates the computed property. So anytime, first name or last name changes, knockout updates full name automatically. (Check out the – 03-Observables.html page for actual implementation in sample project linked with this article).

Observable Arrays:

Just like the observables seen before, observable arrays target complex arrays. Knockout has great support for observing complex arrays, and you can certainly define chain of dependency tracking. I’m going to show you how easily knockout handles chain of dependencies in the example shown below:

clip_image008

As you see in the example, our view model has a collection of companies and each company object has a collection of employees. There is nothing fancy in the array but our UI markup has something new which we didn’t see earlier. Knockout has in-built support for collections using “foreach” data bind attribute to loop through all the elements of an array. Once you define any such binding, knockout knows that it has to repeat the UI markup for each of the elements in that array. Not only does it handle the looping iterations elegantly but it also manages the context very well. So for instance, the outer loop (foreach) has company object specific bindings and inside, we have employee object specific binding. Knockout knows exactly how to change the context and which events to plug in at runtime so that correct events are trigged at runtime.

 

Automatic UI Refresh:

Automatic UI refresh is one of the coolest feature of Knockout. As the name suggests, it refreshes the UI automatically when the underlying data changes. The example discussed in above feature also shows the Automatic UI refresh feature, but I’m going to take a different scenario from real world to show you that it’s indeed a coolest feature ever.

clip_image010

clip_image012

The very first thing to notice from the sample above is the separation of concerns, my initial data (Model) is separate from View model and UI markup, in real world, you would want to keep your model providers, View Model and HTML markup in a separate files, so that you achieve good control over separations. After you run the (05-Automatic UI Refresh.html) file from sample project you would notice that, after you click on add or delete buttons the UI refreshes automatically when in reality we are only manipulating the data. Any changes to data are being tracked down on UI and vice versa. This is happening because through bindings knockout knows which html element a data property is mapped to and what to do when any of the data or UI changes.

Template support:

Templates are a simple and convenient way to build sophisticated UI structures. It is one of the most powerful feature of Knockout. It supports several JS template engines like jQuery.tmpl, underscore.js out of the box. To define a template rendering in knockout, use data bind attribute to specify template name and corresponding action with data. As shown in sample below – we have a simple table, which has templates defined. That’s all the html markup we have in this sample. Rest everything is simple JavaScript.

clip_image014

Templates are defined in script block with a script-type little different than usual. This is tell browsers not to execute this immediately, we would like knockout to compose this template when needed at runtime.

clip_image016

Finally, our view model, which is a regular knockout view model with some sample data. Note that actual logic of rendering UI lies with knockout template engine. It will take the instructions from UI markup and render the UI and plug in necessary DOM events. Template support is a simple and yet very powerful feature of knockout which could be extended to build high performing enterprise apps.

clip_image018

Conclusion:

By now, we have seen all the important features of knockout, and you can really tell its potential. Check out the sample code provided with this article to see knockout in action. A quick recap of whatever we have seen before, Knockout offers –

1. Hassle free bindings, observable and template support

2. Increased developer productiveness, clean code and separation of concerns

3. Easy data manipulation on very complex data entry screens

4. Very good community support

5. Cross platform – Cross browser support

6. Plug in support – external plugins like validation, mapping, typescript and many more makes integration and extension with any other JS framework very easy

Lastly, knockout lets you think in terms of your data rather than controls and events. Next time you have a web page to display some data, think in terms of your domain object, use knockout to display and manipulate the data, after the user has done editing, send the object back to server in JSON format.

Knockout is simple and yet very powerful library and comes handy in web application development. Try it out in your next project to take advantage in terms of developer productiveness, better control over your data and doing more with less code.

References:

Sample code is available for free download at https://github.com/chetanvihite/Knockout.Sample

If you have any questions, please feel free to contact me at chetan.vihite@thedigitalgroup.net

http://knockoutjs.com/index.html

Posted On Friday, July 24, 2015 3:37 AM | Comments (0)

Monday, July 6, 2015 #

Understanding Onion Architecture

In this post I am going to talk about Onion Architecture. There are several traditional architectures that exists in web world and each one of the architecture comes with its pros and cons. But most of the traditional architectures raises fundamental issues like tight coupling and separation of concerns. I am going to talk about issues faced with traditional designs and then we will see how Onion Architecture addresses these common issues.

Problems

The traditional and most commonly used web application architecture is Model-View-Controller architecture which is one of the most widely adapted and appreciated architecture throughout the industry. If you have been using Asp.net web forms to develop web application then adopting MVC architecture even fits better, because it provides the required framework to build web apps MVC way. But things doesn’t turn out as planned and leads to very tight coupling between UI and business logic and business logic to database logic. This is because you end up writing all of your logic in server side code (mainly aspx.cs files). This scenario produces very tight coupling over the period of time and system becomes a nightmare to maintain.

Another approach to look at the problems described above is to look at the Traditional Architecture diagram below. As you see, the UI is talking to business logic and business logic is talking to data layer and all the layers are mixed up and depend heavily on each other. None of the layer stand independent, which raises separation of concerns.

{

In other words, if your application has several lines of code in button_submit or page_load events and if it’s doing several things in one single method, then it’s a matter of concern. Because sooner or later system will change and new developers will keep adding new business logic to these existing events, and the eventual situation would be very chaotic. Such systems are always very hard to understand and maintain.

}

image

Further, the biggest drawback of this architecture is unnecessary coupling that it creates. Each layer is coupled to the layers below it, which creates a very tight coupling between these layers, and a tightly coupled system enforces several restrictions and challenges when undergoing changes.

The biggest offender is the coupling of UI and business logic to data access. Typically, The data access changes every few years, historically, the industry has modified the data access techniques at least every three years, so naturally, and it is expected to have some flexibility with data access layer when the system undergoes changes. However, the flexibility with technology upgrades doesn’t come handy with tightly coupled systems. There are always challenges involved changing something which has lot of impact in business critical systems and that’s where these systems fall behind the technology upgrade race and eventually becomes stale and very hard to maintain.

Solution

This is where the Onion Architecture comes in. The term “Onion Architecture” was first coined by Jeffry Palermo back in 2008 in a series of blog posts. The architecture is intended to address the challenges faced with traditional architectures and the common problems like coupling and separation of concerns.

image

Shown above is the proposed Onion Architecture, which has layers defined from core to Infrastructure. The main premise is that it controls coupling.  The fundamental rule is that all code can depend on layers more central, but code cannot depend on layers further out from the core.  In other words, all coupling is toward the center.   This architecture is undoubtedly biased toward object-oriented programming, and it puts objects before all others. At the very center is the domain model, which represents the business and behavior objects. Around the domain layer are other layers with more behavior. The number of layers in application will vary but domain is always at the center. The first layer around the domain is typically we would place interfaces that provides saving and retrieving behaviors, called repository interfaces. Only the interface is in the application core. Out on the edges we see UI, Infrastructure and Tests. The outer layer is reserved for things that potentially changes often, these things are intentionally isolated from the application core. Out on the edges in Infrastructure, we would find classes that implements a repository interface and these classes are coupled to particular way of Data Access, and that’s is why it resides outside the application core.

Let’s see what each of these layers represents and what should each contain.

Domain Layer – At the very core is the Domain layer which holds all of your domain objects. The idea is to have all of your domain objects at this core. Please restrict yourself by keeping just the properties or definitions inside your domain objects and not any piece of code which talks to database or has any other business functions. Besides the domain objects, you could also have domain interfaces, but just the interfaces and not any kind of implementation.

image

See the screenshot from the sample project that I have created using Onion Architecture, under the solution folder 01-Domain, I have got 2 projects Domain.Entities to hold domain objects and Domain.Interfaces to hold domain interfaces. The most interesting thing to notice that there are no special references in this project, and the domain objects are flat objects as they should be, without any heavy code or dependencies.

Service Interface Layer – common operations like Add, Save, Delete should go in here within interfaces. You can define your transactional interfaces like (IOrderService.SubmitOrder) here. One of the most important thing to notice here that service interfaces are kept separate from its implementation, which shows the loose coupling and separation of concerns.

image

Application Services Layer – the implementation of Interfaces defined in Service Interface layers comes here. The service implementation gets data from repositories and processes requests coming in from UI layer. This layer acts as a middleware to provide data from Infrastructure to UI.

image

Look at the references and you will realize that this layer is using domain entities, domain interfaces and service interfaces only, it has no knowledge of where the data comes and where it gets stored, the service is solely dependent on interfaces and at runtime the actual implementation objects gets assigned. Interesting? Well, look at following class to see yourself –

image

The service has dependency on the repository type (interface) which is injected at run time using Castle Windsor and all the methods works on the repository type to perform specific actions.

Infrastructure Layer – this is the outermost layer of onion architecture which deals with Infrastructure needs and provides the implementation of your repositories interfaces. In other words, this is where we hook up the Data access logic or logging logic or service calls logic. Only the infrastructure layer knows about the database and data access technology (Entity framework or Ado.net) and other layers don’t know anything about from where the data comes and how it is being stored.

image

Check out the code map feature of visual studio, which shows an excellent overview of sample solution with arrows pointing in dependency direction –

image

As you see from the diagram it is evident that not a single arrow is pointing upwards in the dependency graph. All the directions are downwards, towards domain or interfaces. Isn’t it cool?

The basic principle of Onion Architecture is to follow the boundaries of these layers – the inner layer can’t depend on its outer layer but can depend on layers beneath. For example, domain layer can’t depend on Infrastructure layer, but Infrastructure layer can depend on Domain layer. Imagine if you put the saveObjectToDatabase method in domain object, then you will depend on Infrastructure layer which is a violation of Onion Architecture. The strategy is to make interfaces defined in the domain layer and put the implementation in Infrastructure layer. Following this principle makes sure we have loose coupling between layers and a real implementation comes only at real time.

Additionally, the Onion Architecture relies heavily on the Dependency Inversion principle to provide the interface implementations at runtime. I have hooked up Castle Windsor in the sample project to achieve dependency inversion at run time. For those who are new to Castle Windsor, it is one of the best IoC container in market today. There are several others (like Ninject, StructreMap, and Unity ) also which are in market but Castle Windsor is personally my favorite.

Before closing my article – I’d like to leave you guys with one though – which is “loose coupling”. See the beauty of loose coupling achieved using this architecture. The advantages are not just limited to loose coupling but other features like Separation of concern and domain model approach makes it an awesome architecture to follow.

Take a look at the sample project available for free download at https://github.com/chetanvihite/OnionArchitecture.Sample to see Onion Architecture in action. If you have any questions please feel free to send me an email at chetan.vihite@thedigitalgroup.net.

References:

http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

http://www.cunningclinton.com/post/2011/07/19/Onion-Architecture.aspx

Posted On Monday, July 6, 2015 6:20 AM | Comments (0)

Understanding Onion Architecture

In this post I am going to talk about Onion Architecture. There are several traditional architectures that exists in web world and each one of the architecture comes with its pros and cons. But most of the traditional architectures raises fundamental issues like tight coupling and separation of concerns. I am going to talk about issues faced with traditional designs and then we will see how Onion Architecture addresses these common issues.

Problems

The traditional and most commonly used web application architecture is Model-View-Controller architecture which is one of the most widely adapted and appreciated architecture throughout the industry. If you have been using Asp.net web forms to develop web application then adopting MVC architecture even fits better, because it provides the required framework to build web apps MVC way. But things doesn’t turn out as planned and leads to very tight coupling between UI and business logic and business logic to database logic. This is because you end up writing all of your logic in server side code (mainly aspx.cs files). This scenario produces very tight coupling over the period of time and system becomes a nightmare to maintain.

Another approach to look at the problems described above is to look at the Traditional Architecture diagram below. As you see, the UI is talking to business logic and business logic is talking to data layer and all the layers are mixed up and depend heavily on each other. None of the layer stand independent, which raises separation of concerns.

{

In other words, if your application has several lines of code in button_submit or page_load events and if it’s doing several things in one single method, then it’s a matter of concern. Because sooner or later system will change and new developers will keep adding new business logic to these existing events, and the eventual situation would be very chaotic. Such systems are always very hard to understand and maintain.

}

image

Further, the biggest drawback of this architecture is unnecessary coupling that it creates. Each layer is coupled to the layers below it, which creates a very tight coupling between these layers, and a tightly coupled system enforces several restrictions and challenges when undergoing changes.

The biggest offender is the coupling of UI and business logic to data access. Typically, The data access changes every few years, historically, the industry has modified the data access techniques at least every three years, so naturally, and it is expected to have some flexibility with data access layer when the system undergoes changes. However, the flexibility with technology upgrades doesn’t come handy with tightly coupled systems. There are always challenges involved changing something which has lot of impact in business critical systems and that’s where these systems fall behind the technology upgrade race and eventually becomes stale and very hard to maintain.

Solution

This is where the Onion Architecture comes in. The term “Onion Architecture” was first coined by Jeffry Palermo back in 2008 in a series of blog posts. The architecture is intended to address the challenges faced with traditional architectures and the common problems like coupling and separation of concerns.

image

Shown above is the proposed Onion Architecture, which has layers defined from core to Infrastructure. The main premise is that it controls coupling.  The fundamental rule is that all code can depend on layers more central, but code cannot depend on layers further out from the core.  In other words, all coupling is toward the center.   This architecture is undoubtedly biased toward object-oriented programming, and it puts objects before all others. At the very center is the domain model, which represents the business and behavior objects. Around the domain layer are other layers with more behavior. The number of layers in application will vary but domain is always at the center. The first layer around the domain is typically we would place interfaces that provides saving and retrieving behaviors, called repository interfaces. Only the interface is in the application core. Out on the edges we see UI, Infrastructure and Tests. The outer layer is reserved for things that potentially changes often, these things are intentionally isolated from the application core. Out on the edges in Infrastructure, we would find classes that implements a repository interface and these classes are coupled to particular way of Data Access, and that’s is why it resides outside the application core.

Let’s see what each of these layers represents and what should each contain.

Domain Layer – At the very core is the Domain layer which holds all of your domain objects. The idea is to have all of your domain objects at this core. Please restrict yourself by keeping just the properties or definitions inside your domain objects and not any piece of code which talks to database or has any other business functions. Besides the domain objects, you could also have domain interfaces, but just the interfaces and not any kind of implementation.

image

See the screenshot from the sample project that I have created using Onion Architecture, under the solution folder 01-Domain, I have got 2 projects Domain.Entities to hold domain objects and Domain.Interfaces to hold domain interfaces. The most interesting thing to notice that there are no special references in this project, and the domain objects are flat objects as they should be, without any heavy code or dependencies.

Service Interface Layer – common operations like Add, Save, Delete should go in here within interfaces. You can define your transactional interfaces like (IOrderService.SubmitOrder) here. One of the most important thing to notice here that service interfaces are kept separate from its implementation, which shows the loose coupling and separation of concerns.

image

Application Services Layer – the implementation of Interfaces defined in Service Interface layers comes here. The service implementation gets data from repositories and processes requests coming in from UI layer. This layer acts as a middleware to provide data from Infrastructure to UI.

image

Look at the references and you will realize that this layer is using domain entities, domain interfaces and service interfaces only, it has no knowledge of where the data comes and where it gets stored, the service is solely dependent on interfaces and at runtime the actual implementation objects gets assigned. Interesting? Well, look at following class to see yourself –

image

The service has dependency on the repository type (interface) which is injected at run time using Castle Windsor and all the methods works on the repository type to perform specific actions.

Infrastructure Layer – this is the outermost layer of onion architecture which deals with Infrastructure needs and provides the implementation of your repositories interfaces. In other words, this is where we hook up the Data access logic or logging logic or service calls logic. Only the infrastructure layer knows about the database and data access technology (Entity framework or Ado.net) and other layers don’t know anything about from where the data comes and how it is being stored.

image

Check out the code map feature of visual studio, which shows an excellent overview of sample solution with arrows pointing in dependency direction –

image

As you see from the diagram it is evident that not a single arrow is pointing upwards in the dependency graph. All the directions are downwards, towards domain or interfaces. Isn’t it cool?

The basic principle of Onion Architecture is to follow the boundaries of these layers – the inner layer can’t depend on its outer layer but can depend on layers beneath. For example, domain layer can’t depend on Infrastructure layer, but Infrastructure layer can depend on Domain layer. Imagine if you put the saveObjectToDatabase method in domain object, then you will depend on Infrastructure layer which is a violation of Onion Architecture. The strategy is to make interfaces defined in the domain layer and put the implementation in Infrastructure layer. Following this principle makes sure we have loose coupling between layers and a real implementation comes only at real time.

Additionally, the Onion Architecture relies heavily on the Dependency Inversion principle to provide the interface implementations at runtime. I have hooked up Castle Windsor in the sample project to achieve dependency inversion at run time. For those who are new to Castle Windsor, it is one of the best IoC container in market today. There are several others (like Ninject, StructreMap, and Unity ) also which are in market but Castle Windsor is personally my favorite.

Before closing my article – I’d like to leave you guys with one though – which is “loose coupling”. See the beauty of loose coupling achieved using this architecture. The advantages are not just limited to loose coupling but other features like Separation of concern and domain model approach makes it an awesome architecture to follow.

Take a look at the sample project available for free download at https://github.com/chetanvihite/OnionArchitecture.Sample to see Onion Architecture in action. If you have any questions please feel free to send me an email at chetan.vihite@thedigitalgroup.net.

References:

http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

http://www.cunningclinton.com/post/2011/07/19/Onion-Architecture.aspx

Posted On Monday, July 6, 2015 6:06 AM | Comments (0)

Saturday, July 4, 2015 #

Understanding Cyclomatic complexity and its importance in code analysis metrics

 

cyclomatic complexity:

Cyclomatic complexity in code is software metric used to indicate the complexity in the program. It is a quantitative measure of the number is linearly independent paths through programs source code.

Read more about cyclomatic complexity here.

In normal terms, the cyclomatic complexity measure tells how complex is your code. Based on the numbers given per method in source code, one can easily tell if the code is complex or not. The cyclomatic complexity also affects other software metrics like code maintainability index.

The cyclomatic complexity is more in the classes/methods where there are lot of conditional operators (e.g if..else, while, switch statements ).

The number of lines in a class or a method also affects the cyclomatic complexity. More number of lines means, combination of several logic altogether, which clearly violates SRP ( single responsibility principle).

Let’s see some examples of how cyclomatic complexity is being calculated:

clip_image001

clip_image003clip_image005

 

Calculating Cyclomatic complexity using Visual Studio:

In visual studio, Go to, Analyze option and select either the Calculate Code Metrics for Selected Projects or Calculate Code Metrics for Solution. As the each option suggests, choosing second option would analyze complete solution compare to previous one which would analyze it for selected projects.

Clicking on either of the options would open up Code Metrics Results window that would show all the Analysis details. Result window contains analysis results in terms of Maintainability Index, Cyclomatic complexity, Depth of Inheritance, Class coupling and Lines of code.

A good maintainable code would have code complexity less than 10 points. If any of your method is having more than 10 points, then it’s surely a candidate for refactoring. Remember, the lesser is the number the better it is maintainable.

clip_image007

clip_image008

Resolving higher Cyclomatic complexity:

The main objective of understanding cyclomatic complexity to avoid excessive code complexity source code, so that it clean and maintainable.

Let’s see some ways by which we can reduce the cyclomatic complexity:

1. Validate and remove unwanted if statements: its known problem and a code issue that more the conditional statements, the more are the code complexities. First validate and see which if statements can be removed so the code complexity is reduced.

2. Refactoring: refactoring is helpful in dealing with very high cyclomatic complexity of source code. The higher the number, the more it needs refactoring. Every developer should try refactoring bigger methods into smaller methods to reduce the code complexity. Use the single responsibility principle to break bigger classes into smaller ones thus reducing dependency on single class doing multiple functions.

3. Remove unnecessary/redundant else conditions: if the if. Else block are doing some logic or returning something based on some condition, then its better to have just one single if statement, instead of if..else block. Remember that even the else in this case would be redundant. See following example:

Before:

clip_image009

4. Combine conditions to reduce cyclomatic complexity: often the simple code would have some complexity, due to conditional statements, but rewriting those with simple LINQ conditions would reduce the count:

Before:

clip_image011

After:

List<String> filteredList = originalList.where(s => matches(s));

One word of caution is to be careful with such linq queries. If you think the query can get more complex, then it won’t serve the purpose, in that case it would be better to live with complexity of 2, rather than 1.

We want to keep the code readable as well as simple. So make sure your LINQ queries are not exploited in near future.

5. Apply Strategy Pattern to get rid of long switch cases:

One good advice I would always give to developers is to use Strategy pattern, rather than switch…case statements. Remember that using a strategy pattern is a replacement to your switch..case statement. Having said that, please ensure NOT to enforce strategy for smaller switch cases, if the switch cases are going to be extended over the period of time, then surely it’s a candidate for strategy, otherwise, its won’t make much sense.

One good example of using strategy pattern over switch case would be a tax calculation problem for 50 states… you know that using swich statement in this case would be very long, so instead apply strategy pattern for achieving low cyclomatic complexity and clean code.

6. Apply Command pattern to reduce meat from switch…case statements:

clip_image013

So we have seen how important is cyclomatic and why it was included in the visual studio code analysis toolset. Since it’s already available in visual studio, all the developers, leads and managers should take use of this to analyze code metrics and adhere to some numbers, which they feel would keep the code quality better.

Posted On Saturday, July 4, 2015 7:11 AM | Comments (0)

Tuesday, June 30, 2015 #

A Detailed Walkthrough of ASP.net MVC Request Life Cycle

 

 

MVC Request Life Cycle

Life cycle of MVC request is a series of steps involved in processing client request. Regardless of technology and platforms almost all the web frameworks have one or other type of Request life cycle and MVC is no different. Understanding the life cycle of any web framework helps better leverage the features for processing requests.

In this article I am going to explain what exactly happens in ASP.NET MVC request life cycle and what each step in the life cycle does and how we can leverage it further based on our needs. This article specifically targets Page life cycle which is different from Application life cycle. A typical Application life cycle contains Application start and Application End events, however http Life cycle is something which is repeated for every request. Since application events are also part of life cycle, we will see them as we move along.

The MVC Request Life Cycle

The entry point of MVC Request life cycle is URL Routing module, the incoming request from IIS pipeline is handed over to URL Routing module which analyses the request and looks up Routing table to figure out which controller the incoming request maps to. Routing Table is a static container of routes defined in MVC application with corresponding controller action mapping. If the route is found in the routing table MVCRouteHandler executes and brings the instance of MVCHttpHandler. Together they act as a gateway into the MVC Framework.

MVC handler begins initializing and executing controller. The MVCHttpHandler also takes of converting route data into concrete controller that is capable of serving the request. MVC handler does all this with the help of MVC Controller factory and activator which are responsible for creating an instance of the controller. This is also the place where the Dependency Injection is performed if the application has been designed to invoke parameterized controller constructor and satisfy its dependencies.

After the controller instance is created the next major step is to find and execute the corresponding action. A component called ActionInvoker finds and executes the action defined in routing table. Before the action method is called model bindings takes place which maps data from http request to action method parameters. After the model binding, action filters are invoked which includes OnActionExecuting filter. This is followed by action execution and Action Executed filter execution and finally preparing Action Result.

Once the Action method has been finished executing the next step is Result execution. MVC separates the action declaration from Result execution. If the Result from action execution is view, then depending upon configuration, ASPX or Razor view engine will be called to find and render the html view as a response of http request. If the result was not view then it’s passed as-is to http response.

Following is the conceptual view of MVC request life cycle.

image

Webforms and MVC

If you have ever developed a web forms application in the past, then it’s always a good idea to understand some of the differences between these two.

· Service to a request in Web forms life cycle corresponds to serving a physical file on the disk. However this is not the case in MVC. IN MVC, there is not real concept of serving files from the disk, rather Controller action are executed to render a view to the user.

· Despite the differences both the web forms and MVC requests implement through HttpHandler. In web forms each page is derived from IHttpHandler interface and request is served more directly. MVC controllers are also derived from HttpHandlers.

From a higher level, MVC is just another way to manage request from ASP.net platform. One can create their own pipeline and build a framework like MVC or web forms on their own. Following image depicts this idea. also, throughout this article you will recognize the extension points to better leverage the framework.

 

image

Application Life Cycle

MVC application life cycle contains two application level events that are associated with start and end events of the application. Application start fires when the application is brought to life by a very first request to the application. Application end event is fired when application has been shut down.

It’s important to understand application life cycle events to get a better understanding on how MVC life cycle starts. So far we have seen that URL Routing module is the starting point for MVC application that has a collection of predefined routes to map from. Now, the question here is how does URL routing handler gets this information from? The answer is simple, using Application start event. MVC applications provide these events in Global.asax file which contains all the application level events. All the prestart things are managed in the application start event.

MVC Application_Start event is:

· An event that fires when first request is received.

· Can be used to run initial configuration and settings code

· The event takes care of registering all areas of MVC application, installing global filters, adding routes and bundles.

Register routes

Since Application_start event is the first event that gets called when application receives its very first request, all the pre application tasks like routing takes place here.

As you see in the diagram below ResolveRequestCache needs to know the routes to choose from, and this needs to have static route collection already created.

image

PreApplicationStart:

PreApplicationStart is another option at the assembly level to register something before the application starts. It could be used to run some initial configuration code or register modules or any other code that needs to be executed before the application starts.

HttpHandlers

HttpHandlers are classes that implement IHttpHandler and generate a response to HttpRequest. There could be httpHandler re-assignment in a life cycle of a request but only one http handler executes and provides response.

There are two sets of events in the MVC request life cycle that concerns HttpHandlers, [MapRequestHandler and PostMapRequestHandler] and [RequestHandlerExecute and PostRequestHandlerExecute].

MapRequestHandler and PostMapRequestHandler are the events in the life cycle which determines the httpHandler responsible for executing the request. Only the selection happens during this time.

RequestHandlerExecute and PostRequestHandlerExecute are the life cycle events that actually executes the htttp handler determined in the earlier phases of request life cycle.

Refer to following diagram below (note post events have been omitted in the diagram).

image

Creating an HttpHandler:

Create a class that implements IHttpHandler interface

Register the HttpHandler through code or web.config

IHttpHandler exposes two members:

· IsReusable

· ProcessRequest()

SampleHandler.cs

image

HttpModules

HttpModules are classes that implement IHttpModule interface and are designed to respond to Life cycle events. In a given Http life cycle, multiple http modules can respond to one single request and can also hook into multiple life cycle events. So they are not tied to any specific event, rather they can act at several places during the life cycle and expose multiple development possibilities.

One of the advantage HttpModules bring is the reusability, modules written once can be reused any several application across frameworks. Features such as logging and authentication are best examples of wrapping things up in a HttpModule. One can also do the all these things possible in HttpModule in a Global.asax file, but that won’t achieve reusability and abstraction.

image

Creating a HttpModule

· Implement the IHttpModule interface

· Register the HttpModule through code or config

· IHttpModule exposes two members:

1. Init()

2. Dispose()

HttpModule and HttpContext

HttpModule and HttpContext work with each other in the life cycle of a request to serve and achieve the goals of a module. For instance, HttpModule can populate the user information and populate UserInfo object inside HttpContext for applications read its value and proceed accordingly. HttpModules takes advantage of hooking within the lifecycle events, even before the ASP.net MVC framework starts taking control of request. In fact, HttpModules can act early on to request in the very first event itself, “Begin Request”, much before the MVC life cycle takes over. This gives HttpModules an edge over MVC requests because you could respond to a request early on and take appropriate actions well before. This can have some serious implications, there are certain things which HttpModules can do really better, while avoiding the MVC framework completely.

image

Comparing HttpHandlers and HttpModules

Many HttpModules can service one request, however only one HttpHandler can service a request.

HpptModules are primarily used to modify and support requests through services, however HttpHandlers are used to generate a response that is sent back to browser using an HttpHandler.

HpptModules are implemented through IHttpModule interface, and HttpHandlers are implemented through IHttpHandler interface

Both HttpModule and HttpHandler can be registered through code or config file.

HttpModules and deigned to integrate with any of the life cycle events, however HttpHandlers are generally concerned with events related to mapping and execution.

MVCRouteHandler and MVCHandler

UrlRouting module is a special module that contains PostResolveRequestCache event that actually matches the incoming request to routing table and executes routing handler for it. Routing handler is simply a class that implements IRouteHandler interface and exposes one method “GetHttpHandler” and return MvcHandler to execute further. MvcHandler is a standard HttpHandler which exposes two methods, IsReusable and ProcessRequest. The ProcessRequest inside the MvcHandler is the entrance into the MvcFramework.

Controllers

Controllers and actions are the two very important components in MVC that every developer work with. Controllers takes care of orchestrating relationships between views and models. Controllers are nothing complex but a class that implements IController interface and exposes one method “Execute ()”. This execute method actually kicks the execution of controllers in the request life cycle. At a high level, the job of a MvcHandler is to generate a response by executing a controller. But a lot goes under the curtain so let’s try to understand how the controller is selected, instantiated and executed to serve the request.

MvcHandler doesn’t create an instance of controller right away, rather takes help from several other important classes to perform this. MvcHandler first calls a method ProcessRequestInit() which calls a controller factory to select a controller using the route data provided. Once the selection is performed by controller factory, Controller Activator creates an instance of requested controller using Dependency Resolver. If no dependency resolved was found then Controller Activator manually creates an instance of controller and returns it for execution. Once the controller has been initialized MvcHandler calls controller.Execute() method to begin processing execution. Following diagram depicts the control flow.

image

Controller Factory

Controller factory is used directly by MvcHandler to get the Controller to execute. Its primary responsibility to find the appropriate type of controller to serve the request. At the heart of ControllerFactory is the interface IControllerFactory that a default controller factory implements.

You could add your own custom factory by implementing IControllerFactory interface. The interface exposes three main methods:

· CreateController for creating controller, it should return a type that implements IController.

· GetControllerSessionStateBehavior determines how session is handled for a given controller.

· ReleaseController for releasing any resources factory is holding onto.

DefaultControllerFactory

MVC framework provides a robust controller factory out-of-the box, called as “DefaultControllerFactory”. This default factory handles a lot of low level work for getting and creating an instance of desired controller. For instance, if the incoming request is myAPP/Order/22, then controller factory would create an instance of OrderController or whatever is being specified in routing data.

The default controller also has access to “Dependency Resolver”, which helps in resolving dependencies of controller. This is the place where custom dependency resolvers fits in to give way for IoC container to come in and resolve dependencies like parameterized contractors etc.

Creating a Custom controller factory

In most of cases you would attach a controller factory component into your application and let the external components handle creating objects for you. Of course, there are some solid reasons for employing an external component to do this, since controller creation and dependency resolution could be some complex. There are several IoC containers available like CastleWindsor, Unity, Ninject etc. that works out of the box and are available on nuget for download. However I still want to pursue creating a custom controller factory for demonstration purposes anyway.

To create a custom controller factory, first create take a controller, that implements IController as below.

image

Next, create a class which implements IControllerFactory. IControllerFactory exposes three methods, CreateController, GetSessionStateBehavior and ReleaseController.

image

Finally, just set the custom controller factory in Global.asax file. And that’s it.

Now when you browse your /contact page, you should see the response that you set in the controller.

image

Action Method Execution

Once the Controller has been chosen and initialized execution start, this includes choosing an Action using ActionInvoker’s Select method. Action invoker selects appropriate method using route data and method names to choose best fit method. Once the selection is done, Authentication filters fires to ensure that current user is authenticated. If the authentication fails then a challenge is sent back to the use, which could involve redirect user to a login page. If the authentication passes, request moves ahead with authorization. Once again, the same process happens, if the user is not authorized, then a challenge is sent back to browser, otherwise request pipeline moves. Once the authentication and authorization are passed, request moves forward with identifying parameters required to pass in to selected action. This process is called as Model Binding. Model binding collects data from query string, route data and request to generate objects required by Action method. The process correctly maps the parameters to objects and also takes care of converting incoming types to correct types required by Action method.

Once the model binding has been done, Action filters kick in. before an action method is being called, OnActionExecuting filter is executed and any code placed inside this filter gets executed. Once the OnActionExecuting has been executed, Action method execution starts. Once the Action method has been executed and a response has been generated, another filter OnActionExecuted gets executed.

All the steps involved in Action execution are very much extensible and that makes MVC a great framework to work with. Following figure depicts the Action method execution flow.

image

Action Invoker

Controller’s execution is really empowered by ActionInvoker’s select method in the sense that it can select appropriate action in variety of ways. Like many other MVC framework components Action Invoker also implements a simple interface “IActionInvoker” that exposes one method InvokeAction.

image

The method takes two arguments, controllerContext and actionName that are used to select and invoke appropriate action. In almost all the cases you don’t need to implement this interface because MVC by default provides a powerful implementation, ControllerActionInvoker. Further, default behaviour of controller action invoker can be customized using extension points.

Action Selectors

So how does Action Selector work? In a very straight forward way, Action Selectors select an action based on Route Data and matches the method name. Sounds simple, but there is more to it. If you have worked with Http methods before, you might recognize that MVC provides Action methods with http attributes. One can decorate action methods with these http attributes to specify how this method should be invoked. For example, it ensure that a http GET request can’t invoke http POST method, just because the name matches.

Some common Action selectors that MVC provides are HttpGet, HttpPost, AcceptVerbs, ActionName, NonAction and Custom.

Selecting an action is a multi-step process. First off, MVC determines which methods are eligible, only public non-static, non-special methods (e.g. constructors, ToString() are excluded) are considered in the Action method selection. Then, the framework matches signature of the methods with incoming request.

· If any valid method, with signatures matches to only one method then that method is returned otherwise No Match error is thrown.

· If there are multiple methods found with same signature then only one where action selectors matches is returned otherwise No Match error is thrown.

· If there are multiple methods with same action selectors then Ambiguous Match error is thrown.

Refer to code fragment below, which depicts a common scenario where we have one method to show form to register and another one to handle posting of same form. In such cases, it’s always best to have HttpGet or HttpPost selectors specified so that appropriate method is called to serve the request.

image

Just like other components of MVC, Action Selectors are also extensible. You could create your own custom action selector by deriving ActionMethodSelectorAttribute class. This class exposes one method to determine if the current method is valid for a request or not using “IsValidForRequest” method.

image

Model Binding

Model binding is the process that maps data from request and supply to Action methods parameters. Model binding takes places after the authorization filters have executed and model is ready to bind. Model binder works with Value provides to get and map data. By default there are four value provides that MVC framework uses, Form Data, Route Data, Query string and posted Files. You can create your own custom value provider to choose data from, such as Cookie Value provider as custom value provider.

Model Binder is implemented from IModelBinder interface. By default, MVC provides a very powerful model binder but you can create your own custom model binder for your specific project needs.

image

Filters

Filters are interesting and somewhat unique part of MVC. Filters are designed to inject logic in between MVC request life cycle. Filters provide users with powerful ways to inspect, analyze, capture and instruments several things going around within MVC projects. A very interesting thing that how filters run at multiple points in the request life cycle compared to other components. As of MVC5, there are 5 types of filters.

image

Authentication filters are new addition from MVC 5. These filters kick in first in the request life cycle and perform the authentication logic.

Authorization filters are executed after the Authentication filters successfully executed and authorizes users roles to ensure current user has access to request resource.

Action filters are executed next in the request life cycle and execute any custom logic you may want to perform before and after action execution.

Result filters are executed before and after result execution.

Finally, the exception filters are executed when there is an exception during processing of request.

Scope of filters

Filters are designed keeping scope in mind and nature and need of your projects. Filters can be applied to specific actions and it will run for only those specified actions. Next, filters could also be decorated at the controller level, so it run for all the action of that controller. Finally, we could also specify filters to run at a global level for all the controllers and actions.

Action Result Execution

The journey of MVC life cycle ends with Action result execution. It’s the last and final step in MVC request life cycle. It’s also the most important one, because this is where result is sent back to browser.

Action result execution starts after action invoker are identified an action to execute. At this point, first the Result Filters are executed before and after actual result execution. OnResultExecuting filter executes first in the sequence, followed by Action Result – ExecuteResult(), which takes care of executing result.

At this point the further execution could branches in to two separate routes. If the result type is View Engine then appropriate view engine Razor or ASPX is brought in to render partial view or view. At the same time, if the Response is any other type, then response if directly written without bringing view engine altogether.

Finally, ResultFilter “OnResultExecuted” is executed which could perform any custom logic written in this filter. Generally speaking, this is the last point in the MVC request life cycle to inject your custom code into the life cycle.

Following the diagram that depicts the Action Result execution flow.

image

Some common Action Result Types

image

Custom Action Result Types

Adding a new custom Action result type is very and requires very little effort to plug n new action result types.

First off, create a new class derived from ActionResult class, and then override ExecuteResult method to provide your own implementation.

Lets say, we want to change the default json result type to something different, like use Json.net to covert to json instead of default json conversion.

We will have to start with a class that is derived from ActionResult class and overrideExecuteResult method to use our own custom logic.

See the class below,

image

Once this is in place, on any action method, we can use this as return type, see the code fragment below –

image

Yes, it is that simple to create a custom Action result type.

View Results and View Engine

View results are the most common results type that as a MVC developer you might be using. On a high level, View result is responsible for returning HTML back to your browser. View Result employs View Engine to do this task and ensures the correct views are being rendered.

There are two view engines that MVC provides by default, Razor View Engine and Legacy View Engine. Razor view engine is more sophisticated and fast compared to Legacy engine. Legacy view engine understands ASPX format code and emits raw HTML.

View rendering process starts when the View Result calls the Execute Result method from its base class ViewResultBase. The ExecuteResult from viewResultBase calls the abstract method FindView. The child view result overrides this method and calls FindView from view engine, which either returns a view or list of locations searched to locate a view. Finally ViewEngineResult returns a view which has single method “Render” which actually writes response to the request. Following is the diagram that depicts this flow.

image

If we look at ViewEngine, which actually implements IViewEngine interface and exposes three methods, FindView, FIndPartialView and ReleaseView. First two methods which deals with finding view are important to search and locate view and return it for processing. ReleaseView method simply releases any resources holding by viewengine like FileStream

image

Default Razor Search Locations

By default view engine looks up at location, shown in the diagram below. If for some reason it can’t find a view then it throws an exception. Once the view has been found viewengine calls its render method to emit html code for browser to display on the screen.

image

This concludes the MVC request life cycle.

I hope I have touched much more points than a regular article and presented a lot many ways to leverage MVC. Feel free to reach me on chetan.vihite@gmail.com should you have any questions.


Posted On Tuesday, June 30, 2015 10:22 AM | Comments (0)

Friday, June 5, 2015 #

ASP.Net MVC Request Life Cycle

 

Life cycle of MVC request is nothing but a series of steps involved in processing client request. Regardless of technology and platforms almost all the web systems have one or other type of Request life cycle and MVC is no different. Understanding the life cycle of any web technology helps better leverage the features of processing requests.

In this article I will explain what exactly happens in ASP.NET MVC request life cycle and what each step in the life cycle does and how we can leverage it further based on our needs. This article specifically targets Page life cycle which is different from Application life cycle. A typical Application life cycle contains Application start and Application End events, however http Life cycle is something which is repeated for every request. Since application events are also part of life cycle we will see them as we move along.

The MVC Request Life Cycle

 

The entry point of MVC Request life cycle is URL Routing module, the incoming request from IIS pipeline is handed over to URL Routing module which analyses the request and looks up Routing table to figure out which controller the incoming request maps to. Routing Table is a static container of routes defined in MVC application with corresponding controller action mapping. If the route is found in the routing table MVCRouteHandler executes and brings the instance of MVCHttpHandler. Together they act as a gateway into the MVC Framework.

MVC handler begins initializing and executing controller. The MVCHttpHandler also takes of converting route data into concrete controller that is capable of serving the request. MVC handler does all this with the help of MVC Controller factory and activator which are responsible for creating an instance of the controller. This is also the place where the Dependency Injection is performed if the application has been designed to invoke parameterized controller constructor and satisfy its dependencies.

After the controller instance is created the next major step is to find and execute the corresponding action. A component called ActionInvoker finds and executes the action defined in routing table. Before the action method is called model bindings takes place which maps data from http request to action method parameters. After the model binding, action filters are invoked which includes OnActionExecuting filter. This is followed by action execution and Action Executed filter execution and finally preparing Action Result.

Once the Action method has been finished executing the next step is Result execution. MVC separates the action declaration from Result execution. If the Result from action execution is view, then depending upon configuration, ASPX or Razor view engine will be called to find and render the html view as a response of http request. If the result was not view then it’s passed as-is to http response.

Following is the conceptual view of MVC request life cycle.

clip_image002

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Webforms and MVC

 

If you have ever developed a web forms application in the past, then it’s always a good idea to understand some of the differences between these two.

· Service to a request in Web forms life cycle corresponds to serving a physical file on the disk. However this is not the case in MVC. IN MVC, there is not real concept of serving files from the disk, rather Controller action are executed to render a view to the user.

· Despite the differences both the web forms and MVC requests implement through HttpHandler. In web forms each page is derived from IHttpHandler interface and request is served more directly. MVC controllers are also derived from HttpHandlers.

From a higher level, MVC is just another way to manage request from ASP.net platform. One can create their own pipeline and build a framework like MVC or web forms on their own. Following image depicts this idea.

clip_image004

 

 

 

 

 

 

 

 

Application Life Cycle

 

MVC application life cycle contains two application level events that are associated with start and end events of the application. Application start fires when the application is brought to life by a very first request to the application. Application end event is fired when application has been shut down.

It’s important to understand application life cycle events to get a better understanding on how MVC life cycle starts. So far we have seen that URL Routing module is the starting point for MVC application that has a collection of predefined routes to map from. Now, the question here is how does URL routing handler gets this information from? The answer is simple, using Application start event. MVC applications provide these events in Global.asax file which contains all the application level events. All the prestart things are managed in the application start event.

MVC Application_Start event is:

· An event that fires when first request is received.

· Can be used to run initial configuration and settings code

· The event takes care of registering all areas of MVC application, installing global filters, adding routes and bundles.

Register routes

 

 

clip_image006

 

 

 

 

 

 

 

 

 

 

 

 

 

 

clip_image008

Posted On Friday, June 5, 2015 9:46 AM | Comments (0)

Wednesday, June 3, 2015 #

Code Metrics | Understanding Cyclomatic Complexity using Visual Studio

cyclomatic complexity: 

 

Cyclomatic complexity in code is software metric used to indicate the complexity in the program. It is a quantitative measure of the number is linearly independent paths through programs source code.

Read more about cyclomatic complexity here.

 

In normal terms, the cyclomatic complexity measure tells how complex is your code. Based on the numbers given per method in source code, one can easily tell if the code is complex or not. The cyclomatic complexity also affects other software metrics like code maintainability index. 

 

The cyclomatic complexity is more in the classes/methods where there are lot of conditional operators (e.g if..else, while, switch statements ).

The number of lines in a class or a method also affects the cyclomatic complexity. More number of lines means, combination of several logic altogether, which clearly violates SRP ( single responsibility principle).

 

Let’s see some examples of how cyclomatic complexity is being calculated:

 

Cyclomatic complexity of 1:

public void Method()

{

    Console.WriteLine("Hello World!");

}

 

Cyclomatic complexity of 2:

void Method(bool condition)
{
    if (condition)
    {
        Console.WriteLine("Hello World!");
    }
}

Cyclomatic complexity of 3:

public void Method(bool condition1, bool condition2)
{
    if (condition1 || condition2)
    {
        Console.WriteLine("Hello World!");
    }
}

Cyclomatic complexity of 8:

public void Method(DayOfWeek day)
    {
 
        switch (day)
        {
            case DayOfWeek.Monday:
                Console.WriteLine("Today is Monday!");
                break;
            case DayOfWeek.Tuesday:
                Console.WriteLine("Today is Tuesday!");
                break;
            case DayOfWeek.Wednesday:
                Console.WriteLine("Today is Wednesday!");
                break;
            case DayOfWeek.Thursday:
                Console.WriteLine("Today is Thursday!");
                break;
            case DayOfWeek.Friday:
                Console.WriteLine("Today is Friday!");
                break;
            case DayOfWeek.Saturday:
                Console.WriteLine("Today is Saturday!");
                break;
            case DayOfWeek.Sunday:
                Console.WriteLine("Today is Sunday!");
                break;
        }
    }

 

Calculating Cyclomatic complexity using Visual Studio:

                        

In visual studio, Go to, Analyze option and select either the Calculate Code Metrics for Selected Projects or Calculate Code Metrics for Solution. As the each option suggests, choosing second option would analyze complete solution compare to previous one which would analyze it for selected projects.

                         Clicking on either of the options would open up Code Metrics Results window that would show all the Analysis details. Result window contains analysis results in terms of Maintainability Index, Cyclomatic complexity, Depth of Inheritance, Class coupling and Lines of code.

                         A good maintainable code would have code complexity less than 10 points. If any of your method is having more than 10 points, then it’s surely a candidate for refactoring. Remember, the lesser is the number the better it is maintainable.


cyclomatic complexity: what is it and how to it affects the code

 

The cyclomatic complexity in code is software metric used to indicate the complexity in the program. It is a quantitative measure of the number is linearly independent paths through programs source code.

Read more about cyclomatic complexity here.

 

In normal terms, the cyclomatic complexity measure tells how complex is your code. Based on the numbers given per method in source code, one can easily tell if the code is complex or not. The cyclomatic complexity also affects other software metrics like code maintainability index. 

 

The cyclomatic complexity is more in the classes/methods where there are lot of conditional operators (e.g if..else, while, switch statements ).

The number of lines in a class or a method also affects the cyclomatic complexity. More number of lines means, combination of several logic altogether, which clearly violates SRP ( single responsibility principle).

 

Let’s see some examples of how cyclomatic complexity is being calculated:

 

Cyclomatic complexity of 1:

public void Method()

{

    Console.WriteLine("Hello World!");

}

 

Cyclomatic complexity of 2:

void Method(bool condition)
{
    if (condition)
    {
        Console.WriteLine("Hello World!");
    }
}

Cyclomatic complexity of 3:

public void Method(bool condition1, bool condition2)
{
    if (condition1 || condition2)
    {
        Console.WriteLine("Hello World!");
    }
}

Cyclomatic complexity of 8:

public void Method(DayOfWeek day)
    {
 
        switch (day)
        {
            case DayOfWeek.Monday:
                Console.WriteLine("Today is Monday!");
                break;
            case DayOfWeek.Tuesday:
                Console.WriteLine("Today is Tuesday!");
                break;
            case DayOfWeek.Wednesday:
                Console.WriteLine("Today is Wednesday!");
                break;
            case DayOfWeek.Thursday:
                Console.WriteLine("Today is Thursday!");
                break;
            case DayOfWeek.Friday:
                Console.WriteLine("Today is Friday!");
                break;
            case DayOfWeek.Saturday:
                Console.WriteLine("Today is Saturday!");
                break;
            case DayOfWeek.Sunday:
                Console.WriteLine("Today is Sunday!");
                break;
        }
    }

 

Calculating Cyclomatic complexity using Visual Studio:

                        

In visual studio, Go to, Analyze option and select either the Calculate Code Metrics for Selected Projects or Calculate Code Metrics for Solution. As the each option suggests, choosing second option would analyze complete solution compare to previous one which would analyze it for selected projects.

                         Clicking on either of the options would open up Code Metrics Results window that would show all the Analysis details. Result window contains analysis results in terms of Maintainability Index, Cyclomatic complexity, Depth of Inheritance, Class coupling and Lines of code.

                         A good maintainable code would have code complexity less than 10 points. If any of your method is having more than 10 points, then it’s surely a candidate for refactoring. Remember, the lesser is the number the better it is maintainable.



Resolving higher Cyclomatic complexity:

 

The main objective of understanding cyclomatic complexity to avoid excessive code complexity source code, so that it clean and maintainable.

 

Let’s see some ways by which we can reduce the cyclomatic complexity:

1.    Validate and remove unwanted if statements: its known problem and a code issue that more the conditional statements, the more are the code complexities. First validate and see which if statements can be removed so the code complexity is reduced.

 

 

2.    Refactoring: refactoring is helpful in dealing with very high cyclomatic complexity of source code. The higher the number, the more it needs refactoring. Every developer should try refactoring bigger methods into smaller methods to reduce the code complexity. Use the single responsibility principle to break bigger classes into smaller ones thus reducing dependency on single class doing multiple functions.  

 

 

3.    Remove unnecessary/redundant else conditions: if the if. Else block are doing some logic or returning something based on some condition, then its better to have just one single if statement, instead of if..else block. Remember that even the else in this case would be redundant. See following example:

Before:

private string __GetString(OracleDataReader eventReader, string key)

        {

            if (__CheckDbNull(eventReader, key ) )

                return  "--";

            else

            {

                return eventReader[key].ToString();

            }

}

After:

private string __GetString(OracleDataReader eventReader, string key)

        {

            if (__CheckDbNull(eventReader, key ) )

                return  "--";

            return eventReader[key].ToString()

}

 

4.    Combine conditions to reduce cyclomatic complexity: often the simple code would have some complexity, due to conditional statements, but rewriting those with simple LINQ conditions would reduce the count:

Before:

List<String> filteredList = new List<String>();
 
foreach (String s in originalList){
   if (matches(s)){
      filteredList.add(s);
   }
}

      After:

List<String> filteredList = originalList.where(s => matches(s));

 

One word of caution is to be careful with such linq queries. If you think the query can get more complex, then it won’t serve the purpose, in that case it would be better to live with complexity of 2, rather than 1.

 

We want to keep the code readable as well as simple. So make sure your LINQ queries are not exploited in near future.

 

5.    Apply Strategy Pattern to get rid of long switch cases:

One good advice I would always give to developers is to use Strategy pattern, rather than switch…case statements. Remember that using a strategy pattern is a replacement to your switch..case statement. Having said that, please ensure NOT to enforce strategy for smaller switch cases, if the switch cases are going to be extended over the period of time, then surely it’s a candidate for strategy, otherwise, its won’t make much sense.

One good example of using strategy pattern over switch case would be a tax calculation problem for 50 states… you know that using swich statement in this case would be very long, so instead apply strategy pattern for achieving low cyclomatic complexity and clean code.

private void CalculateTax(string state)

        {

            switch (state)

            {

                case "TX" :

                    // calculate TX TAX

                    return;

                case "CA":

                    // calculate CA TAX

                    return;

                case "AZ":

                    // calculate AZ TAX

                    return;

                case "TN":

                    // calculate TN TAX

                    return;

                case "SC":

                    // calculate SC TAX

                    return;

                case "NC":

                    // calculate NC TAX

                    return;

                case "MN":

                    // calculate MN TAX

                    return;

            }

        }

6.    Apply Command pattern to reduce meat from switch…case statements:

 

 

One example from real project: see below example of GetEventList method. Nothing wrong looks in this method except its bit long and has cyclomatic complexity of 28.

The reason for higher cyclomatic complexity is simple, lots of conditional statements throughout execution.

 

 

 

 

One real world example:

 

Now let’s try to refactor below code and compare the difference.

 

Before Refactoring:

 

public EventSearchResponse GetEventList(string LicenseNumber, string DisplayAll, string OrderBy, string SortColumn, int start, int PageSize, out int TotalCount, out List<Event> outEventList)

        {

            //LicenseNumber = "1110065845";

            EventSearchResponse eventListResult = new EventSearchResponse();

            TotalCount = 0;

            List<Event> events = new List<Event>();

            outEventList = events;

            eventListResult.TotalCount = TotalCount;

            var currentdate = DateTime.Now;

            BindValues bvParam = new BindValues();

            //bvParam["IN_USERTYPE"] = userType;

            bvParam["PDISPLAYALL"] = DisplayAll;

            bvParam["PLICENSE_NUMBER"] = Convert.ToUInt64(LicenseNumber);

            bvParam["PORDER"] = SortColumn;

            bvParam["PSORTBY"] = OrderBy;

            bvParam["PSTARTINGPOINT"] = start;

            bvParam["PNUMOFRECORDS"] = PageSize;

            bvParam["OUT_EVENT_DETAILS"] = events;

            using (DbSession session = MyDb.DefaultConnection)

            {

                OracleDataReader eventReader = null;

                try

                {

                    session.OpenConnection();

                    session.ExecuteProcedure(__SPGetEvents, bvParam);

                    eventReader = bvParam["OUT_EVENT_DETAILS"] as OracleDataReader;

                    if (eventReader.HasRows)

                    {

                        while (eventReader.Read())

                        {

                            if (!(eventReader["EVENT_ID"] == DBNull.Value))

                            {

                                events.Add(new Event()

                                {

                                    EVENT_ID = Convert.ToInt64(eventReader["EVENT_ID"] == DBNull.Value ? 0 : eventReader["EVENT_ID"]),

                                    EVENTNAME = eventReader["EVENTNAME"] == DBNull.Value ? "--" : eventReader["EVENTNAME"].ToString(),

                                    EVENT_TYPE = eventReader["EVENT_TYPE"].ToString(),

                                    DUE_DATE = eventReader["DUE_DATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["DUE_DATE"]),

                                    EXPIRATIONDATE = eventReader["EXPIRATIONDATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["EXPIRATIONDATE"]),

                                    EVENT_EXPIRATION_DATE = eventReader["EVENT_EXPIRATION_DATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["EVENT_EXPIRATION_DATE"]),

                                    FEE = Convert.ToDecimal(eventReader["FEE"] == DBNull.Value ? null : eventReader["FEE"]),

                                    SUBMITTED_DATE = eventReader["SUBMITTED_DATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["SUBMITTED_DATE"]),

                                    EVENT_STATUS = eventReader["EVENT_STATUS"] == DBNull.Value ? "--" : eventReader["EVENT_STATUS"].ToString(),

                                    TRACKING_METHOD_DESC = eventReader["TRACKING_METHOD_DESC"] == DBNull.Value ? "--" : eventReader["TRACKING_METHOD_DESC"].ToString(),

                                    TRACKING_NUMBER = eventReader["TRACKING_NUMBER"] == DBNull.Value ? "--" : (eventReader["TRACKING_NUMBER"].ToString()),

                                    TRACKING_METHOD_CD = Convert.ToInt64(eventReader["TRACKING_METHOD_CD"] == DBNull.Value ? null : eventReader["TRACKING_METHOD_CD"]),

                                    TRACKING_METHOD_NAME = eventReader["TRACKING_METHOD_NAME"] == DBNull.Value ? "--" : eventReader["TRACKING_METHOD_NAME"].ToString(),

                                    NOTES = eventReader["NOTES"] == DBNull.Value ? "--" : eventReader["NOTES"].ToString(),

                                    DUE_DATE_START = eventReader["DUE_DATE_START"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["DUE_DATE_START"]),

                                    RENEWAL_TYPE = eventReader["RENEWAL_TYPE"].ToString(),

                                    RENEWAL_RULE_TYPE_CD = Convert.ToInt64(eventReader["RENEWAL_TYPE"] == DBNull.Value ? null : eventReader["RENEWAL_TYPE"].ToString() == "One Time" ? "3002" : "3003"),

                                    RECURREANCE = eventReader["RECURRANCE"].ToString(),

                                    RECURREANCE_PATTERN = eventReader["RECURRENCE_PATTERN"].ToString(),

                                    MAXRECORDS = Convert.ToInt64(eventReader["MAXRECORDS"]),

                                    viewFlag = eventReader["DUE_DATE"] == DBNull.Value ? "E" : DateTime.Compare(Convert.ToDateTime(Convert.ToDateTime(eventReader["DUE_DATE"]).ToString("MM/dd/yyyy")), Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"))) >= 0 ? "E" : "V",

                                });

                            }

                        }

 

                        if (events != null)

                        {

                            if (events.Count() > 0)

                            {

                                TotalCount = Convert.ToInt32(events[0].MAXRECORDS);

                                eventListResult.Events = outEventList;

                                eventListResult.TotalCount = TotalCount;

                            }

                        }

                    }

                    if (null != eventReader)

                        eventReader.Close();

                    session.SafeClose();

                }

                catch (Exception Ex)

                {

                    ErrorLog.MyErrorLog.SafeLog(Ex);

                }

                finally

                {

                    if (null != eventReader)

                        eventReader.Close();

                    session.SafeClose();

                }

                return eventListResult;

            }

        }

 

So, start with refactoring the most common objects that are being used, followed by creating some private methods for further processing.

 

After refactoring:

public EventSearchResponse GetEventList(string LicenseNumber, string DisplayAll, string OrderBy, string SortColumn, int start, int PageSize, out int TotalCount, out List<Event> outEventList)

        {

            //LicenseNumber = "1110065845";

            EventSearchResponse eventListResult = new EventSearchResponse();

            TotalCount = 0;

            List<Event> events = new List<Event>();

            outEventList = events;

            eventListResult.TotalCount = TotalCount;

            var currentdate = DateTime.Now;

            BindValues bvParam = new BindValues();

            //bvParam["IN_USERTYPE"] = userType;

            bvParam["PDISPLAYALL"] = DisplayAll;

            bvParam["PLICENSE_NUMBER"] = Convert.ToUInt64(LicenseNumber);

            bvParam["PORDER"] = SortColumn;

            bvParam["PSORTBY"] = OrderBy;

            bvParam["PSTARTINGPOINT"] = start;

            bvParam["PNUMOFRECORDS"] = PageSize;

            bvParam["OUT_EVENT_DETAILS"] = events;

            using (DbSession session = MyDb.DefaultConnection)

            {

                OracleDataReader eventReader = null;

                try

                {

                    session.OpenConnection();

                    session.ExecuteProcedure(__SPGetEvents, bvParam);

                    eventReader = bvParam["OUT_EVENT_DETAILS"] as OracleDataReader;

                    if (eventReader.HasRows)

                    {

                        while (eventReader.Read())

                        {

                            if (eventReader["EVENT_ID"] != DBNull.Value)

                            {

                                events.Add(__GetEventRecord(eventReader));

                            }

                        }

                        if (events.Any())

                            {

                                TotalCount = Convert.ToInt32(events[0].MAXRECORDS);

                                eventListResult.Events = outEventList;

                                eventListResult.TotalCount = TotalCount;

                            }

                    }

                 

                }

                catch (Exception ex)

                {

                    ErrorLog.MyErrorLog.SafeLog(ex);

                }

                finally

                {

                    if (eventReader != null) eventReader.Close();

                    session.SafeClose();

                }

                return eventListResult;

            }

        }

        private Event __GetEventRecord( OracleDataReader eventReader)

        {

            return new Event()

                {

                    EVENT_ID = __GetInt64(eventReader, "EVENT_ID"),

                    EVENTNAME = __GetString(eventReader, "EVENTNAME"),

                    EVENT_TYPE = eventReader["EVENT_TYPE"].ToString(),

                    DUE_DATE = __GetDate(eventReader, "DUE_DATE"),

                    EXPIRATIONDATE = __GetDate(eventReader, "EXPIRATIONDATE"),

                    EVENT_EXPIRATION_DATE = __GetDate(eventReader, "EVENT_EXPIRATION_DATE"),

                    FEE = __GetDecimal(eventReader, "FEE"),

                    SUBMITTED_DATE = __GetDate(eventReader, "SUBMITTED_DATE"),

                    EVENT_STATUS = __GetString(eventReader, "EVENT_STATUS"),

                    TRACKING_METHOD_DESC = __GetString(eventReader, "TRACKING_METHOD_DESC"),

                    TRACKING_NUMBER = __GetString(eventReader, "TRACKING_NUMBER"),

                    TRACKING_METHOD_CD = __GetInt64(eventReader, "TRACKING_METHOD_CD"),

                    TRACKING_METHOD_NAME = __GetString(eventReader, "TRACKING_METHOD_NAME"),

                    NOTES = __GetString(eventReader, "NOTES"),

                    DUE_DATE_START = __GetDate(eventReader, "DUE_DATE_START"),

                    RENEWAL_TYPE = eventReader["RENEWAL_TYPE"].ToString(),

                    RENEWAL_RULE_TYPE_CD = __GetInt64(eventReader, "RENEWAL_TYPE_CD"),

                    RECURREANCE = eventReader["RECURRANCE"].ToString(),

                    RECURREANCE_PATTERN = eventReader["RECURRENCE_PATTERN"].ToString(),

                    MAXRECORDS = Convert.ToInt64(eventReader["MAXRECORDS"]),

                    viewFlag = __GetViewFlag(eventReader),

                };

        }

        private bool __CheckDbNull(OracleDataReader reader, string key)

        {

            return (reader[key] == DBNull.Value);

        }

 

        private decimal __GetDecimal(OracleDataReader eventReader, string key)

        {

            return Convert.ToDecimal(__CheckDbNull( eventReader, key) ? null : eventReader[key]);

        }

 

        private Int64 __GetInt64(OracleDataReader reader, string key)

        {

            return Convert.ToInt64(__CheckDbNull(reader, key) ? null : reader[key]);

        }

 

        private string __GetString(OracleDataReader eventReader, string key)

        {

            return __CheckDbNull(eventReader, key ) ? "--"

                       : eventReader[key].ToString();

        }

       

        private DateTime? __GetDate(OracleDataReader eventReader, string key)

        {

            return __CheckDbNull(eventReader, key)

                       ? null

                       : (DateTime?) Convert.ToDateTime(eventReader[key]);

        }

       

        private string __GetViewFlag(OracleDataReader eventReader)

        {

            return __CheckDbNull( eventReader, "DUE_DATE" ) ? "E"

                       : DateTime.Compare(

                           Convert.ToDateTime(Convert.ToDateTime(eventReader["DUE_DATE"]).ToString("MM/dd/yyyy")),

                           Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"))) >= 0

                             ? "E"

                             : "V";

        }

 

After refactoring one big method into smaller chunks, cyclomatic complexity for original method has been reduced to 8 and other private methods are well under control.



Resolving higher Cyclomatic complexity:

 

The main objective of understanding cyclomatic complexity to avoid excessive code complexity source code, so that it clean and maintainable.

 

Let’s see some ways by which we can reduce the cyclomatic complexity:

1.    Validate and remove unwanted if statements: its known problem and a code issue that more the conditional statements, the more are the code complexities. First validate and see which if statements can be removed so the code complexity is reduced.

 

 

2.    Refactoring: refactoring is helpful in dealing with very high cyclomatic complexity of source code. The higher the number, the more it needs refactoring. Every developer should try refactoring bigger methods into smaller methods to reduce the code complexity. Use the single responsibility principle to break bigger classes into smaller ones thus reducing dependency on single class doing multiple functions.  

 

 

3.    Remove unnecessary/redundant else conditions: if the if. Else block are doing some logic or returning something based on some condition, then its better to have just one single if statement, instead of if..else block. Remember that even the else in this case would be redundant. See following example:

Before:

private string __GetString(OracleDataReader eventReader, string key)

        {

            if (__CheckDbNull(eventReader, key ) )

                return  "--";

            else

            {

                return eventReader[key].ToString();

            }

}

After:

private string __GetString(OracleDataReader eventReader, string key)

        {

            if (__CheckDbNull(eventReader, key ) )

                return  "--";

            return eventReader[key].ToString()

}

 

4.    Combine conditions to reduce cyclomatic complexity: often the simple code would have some complexity, due to conditional statements, but rewriting those with simple LINQ conditions would reduce the count:

Before:

List<String> filteredList = new List<String>();
 
foreach (String s in originalList){
   if (matches(s)){
      filteredList.add(s);
   }
}

      After:

List<String> filteredList = originalList.where(s => matches(s));

 

One word of caution is to be careful with such linq queries. If you think the query can get more complex, then it won’t serve the purpose, in that case it would be better to live with complexity of 2, rather than 1.

 

We want to keep the code readable as well as simple. So make sure your LINQ queries are not exploited in near future.

 

5.    Apply Strategy Pattern to get rid of long switch cases:

One good advice I would always give to developers is to use Strategy pattern, rather than switch…case statements. Remember that using a strategy pattern is a replacement to your switch..case statement. Having said that, please ensure NOT to enforce strategy for smaller switch cases, if the switch cases are going to be extended over the period of time, then surely it’s a candidate for strategy, otherwise, its won’t make much sense.

One good example of using strategy pattern over switch case would be a tax calculation problem for 50 states… you know that using swich statement in this case would be very long, so instead apply strategy pattern for achieving low cyclomatic complexity and clean code.

private void CalculateTax(string state)

        {

            switch (state)

            {

                case "TX" :

                    // calculate TX TAX

                    return;

                case "CA":

                    // calculate CA TAX

                    return;

                case "AZ":

                    // calculate AZ TAX

                    return;

                case "TN":

                    // calculate TN TAX

                    return;

                case "SC":

                    // calculate SC TAX

                    return;

                case "NC":

                    // calculate NC TAX

                    return;

                case "MN":

                    // calculate MN TAX

                    return;

            }

        }

6.    Apply Command pattern to reduce meat from switch…case statements:

 

 

One example from real project: see below example of GetEventList method. Nothing wrong looks in this method except its bit long and has cyclomatic complexity of 28.

The reason for higher cyclomatic complexity is simple, lots of conditional statements throughout execution.

  

One real world example:

 

Now let’s try to refactor below code and compare the difference.

 

Before Refactoring:

 

public EventSearchResponse GetEventList(string LicenseNumber, string DisplayAll, string OrderBy, string SortColumn, int start, int PageSize, out int TotalCount, out List<Event> outEventList)

        {

            //LicenseNumber = "1110065845";

            EventSearchResponse eventListResult = new EventSearchResponse();

            TotalCount = 0;

            List<Event> events = new List<Event>();

            outEventList = events;

            eventListResult.TotalCount = TotalCount;

            var currentdate = DateTime.Now;

            BindValues bvParam = new BindValues();

            //bvParam["IN_USERTYPE"] = userType;

            bvParam["PDISPLAYALL"] = DisplayAll;

            bvParam["PLICENSE_NUMBER"] = Convert.ToUInt64(LicenseNumber);

            bvParam["PORDER"] = SortColumn;

            bvParam["PSORTBY"] = OrderBy;

            bvParam["PSTARTINGPOINT"] = start;

            bvParam["PNUMOFRECORDS"] = PageSize;

            bvParam["OUT_EVENT_DETAILS"] = events;

            using (DbSession session = MyDb.DefaultConnection)

            {

                OracleDataReader eventReader = null;

                try

                {

                    session.OpenConnection();

                    session.ExecuteProcedure(__SPGetEvents, bvParam);

                    eventReader = bvParam["OUT_EVENT_DETAILS"] as OracleDataReader;

                    if (eventReader.HasRows)

                    {

                        while (eventReader.Read())

                        {

                            if (!(eventReader["EVENT_ID"] == DBNull.Value))

                            {

                                events.Add(new Event()

                                {

                                    EVENT_ID = Convert.ToInt64(eventReader["EVENT_ID"] == DBNull.Value ? 0 : eventReader["EVENT_ID"]),

                                    EVENTNAME = eventReader["EVENTNAME"] == DBNull.Value ? "--" : eventReader["EVENTNAME"].ToString(),

                                    EVENT_TYPE = eventReader["EVENT_TYPE"].ToString(),

                                    DUE_DATE = eventReader["DUE_DATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["DUE_DATE"]),

                                    EXPIRATIONDATE = eventReader["EXPIRATIONDATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["EXPIRATIONDATE"]),

                                    EVENT_EXPIRATION_DATE = eventReader["EVENT_EXPIRATION_DATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["EVENT_EXPIRATION_DATE"]),

                                    FEE = Convert.ToDecimal(eventReader["FEE"] == DBNull.Value ? null : eventReader["FEE"]),

                                    SUBMITTED_DATE = eventReader["SUBMITTED_DATE"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["SUBMITTED_DATE"]),

                                    EVENT_STATUS = eventReader["EVENT_STATUS"] == DBNull.Value ? "--" : eventReader["EVENT_STATUS"].ToString(),

                                    TRACKING_METHOD_DESC = eventReader["TRACKING_METHOD_DESC"] == DBNull.Value ? "--" : eventReader["TRACKING_METHOD_DESC"].ToString(),

                                    TRACKING_NUMBER = eventReader["TRACKING_NUMBER"] == DBNull.Value ? "--" : (eventReader["TRACKING_NUMBER"].ToString()),

                                    TRACKING_METHOD_CD = Convert.ToInt64(eventReader["TRACKING_METHOD_CD"] == DBNull.Value ? null : eventReader["TRACKING_METHOD_CD"]),

                                    TRACKING_METHOD_NAME = eventReader["TRACKING_METHOD_NAME"] == DBNull.Value ? "--" : eventReader["TRACKING_METHOD_NAME"].ToString(),

                                    NOTES = eventReader["NOTES"] == DBNull.Value ? "--" : eventReader["NOTES"].ToString(),

                                    DUE_DATE_START = eventReader["DUE_DATE_START"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(eventReader["DUE_DATE_START"]),

                                    RENEWAL_TYPE = eventReader["RENEWAL_TYPE"].ToString(),

                                    RENEWAL_RULE_TYPE_CD = Convert.ToInt64(eventReader["RENEWAL_TYPE"] == DBNull.Value ? null : eventReader["RENEWAL_TYPE"].ToString() == "One Time" ? "3002" : "3003"),

                                    RECURREANCE = eventReader["RECURRANCE"].ToString(),

                                    RECURREANCE_PATTERN = eventReader["RECURRENCE_PATTERN"].ToString(),

                                    MAXRECORDS = Convert.ToInt64(eventReader["MAXRECORDS"]),

                                    viewFlag = eventReader["DUE_DATE"] == DBNull.Value ? "E" : DateTime.Compare(Convert.ToDateTime(Convert.ToDateTime(eventReader["DUE_DATE"]).ToString("MM/dd/yyyy")), Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"))) >= 0 ? "E" : "V",

                                });

                            }

                        }

 

                        if (events != null)

                        {

                            if (events.Count() > 0)

                            {

                                TotalCount = Convert.ToInt32(events[0].MAXRECORDS);

                                eventListResult.Events = outEventList;

                                eventListResult.TotalCount = TotalCount;

                            }

                        }

                    }

                    if (null != eventReader)

                        eventReader.Close();

                    session.SafeClose();

                }

                catch (Exception Ex)

                {

                    ErrorLog.MyErrorLog.SafeLog(Ex);

                }

                finally

                {

                    if (null != eventReader)

                        eventReader.Close();

                    session.SafeClose();

                }

                return eventListResult;

            }

        }

 

So, start with refactoring the most common objects that are being used, followed by creating some private methods for further processing.

 

After refactoring:

public EventSearchResponse GetEventList(string LicenseNumber, string DisplayAll, string OrderBy, string SortColumn, int start, int PageSize, out int TotalCount, out List<Event> outEventList)

        {

            //LicenseNumber = "1110065845";

            EventSearchResponse eventListResult = new EventSearchResponse();

            TotalCount = 0;

            List<Event> events = new List<Event>();

            outEventList = events;

            eventListResult.TotalCount = TotalCount;

            var currentdate = DateTime.Now;

            BindValues bvParam = new BindValues();

            //bvParam["IN_USERTYPE"] = userType;

            bvParam["PDISPLAYALL"] = DisplayAll;

            bvParam["PLICENSE_NUMBER"] = Convert.ToUInt64(LicenseNumber);

            bvParam["PORDER"] = SortColumn;

            bvParam["PSORTBY"] = OrderBy;

            bvParam["PSTARTINGPOINT"] = start;

            bvParam["PNUMOFRECORDS"] = PageSize;

            bvParam["OUT_EVENT_DETAILS"] = events;

            using (DbSession session = MyDb.DefaultConnection)

            {

                OracleDataReader eventReader = null;

                try

                {

                    session.OpenConnection();

                    session.ExecuteProcedure(__SPGetEvents, bvParam);

                    eventReader = bvParam["OUT_EVENT_DETAILS"] as OracleDataReader;

                    if (eventReader.HasRows)

                    {

                        while (eventReader.Read())

                        {

                            if (eventReader["EVENT_ID"] != DBNull.Value)

                            {

                                events.Add(__GetEventRecord(eventReader));

                            }

                        }

                        if (events.Any())

                            {

                                TotalCount = Convert.ToInt32(events[0].MAXRECORDS);

                                eventListResult.Events = outEventList;

                                eventListResult.TotalCount = TotalCount;

                            }

                    }

                 

                }

                catch (Exception ex)

                {

                    ErrorLog.MyErrorLog.SafeLog(ex);

                }

                finally

                {

                    if (eventReader != null) eventReader.Close();

                    session.SafeClose();

                }

                return eventListResult;

            }

        }

        private Event __GetEventRecord( OracleDataReader eventReader)

        {

            return new Event()

                {

                    EVENT_ID = __GetInt64(eventReader, "EVENT_ID"),

                    EVENTNAME = __GetString(eventReader, "EVENTNAME"),

                    EVENT_TYPE = eventReader["EVENT_TYPE"].ToString(),

                    DUE_DATE = __GetDate(eventReader, "DUE_DATE"),

                    EXPIRATIONDATE = __GetDate(eventReader, "EXPIRATIONDATE"),

                    EVENT_EXPIRATION_DATE = __GetDate(eventReader, "EVENT_EXPIRATION_DATE"),

                    FEE = __GetDecimal(eventReader, "FEE"),

                    SUBMITTED_DATE = __GetDate(eventReader, "SUBMITTED_DATE"),

                    EVENT_STATUS = __GetString(eventReader, "EVENT_STATUS"),

                    TRACKING_METHOD_DESC = __GetString(eventReader, "TRACKING_METHOD_DESC"),

                    TRACKING_NUMBER = __GetString(eventReader, "TRACKING_NUMBER"),

                    TRACKING_METHOD_CD = __GetInt64(eventReader, "TRACKING_METHOD_CD"),

                    TRACKING_METHOD_NAME = __GetString(eventReader, "TRACKING_METHOD_NAME"),

                    NOTES = __GetString(eventReader, "NOTES"),

                    DUE_DATE_START = __GetDate(eventReader, "DUE_DATE_START"),

                    RENEWAL_TYPE = eventReader["RENEWAL_TYPE"].ToString(),

                    RENEWAL_RULE_TYPE_CD = __GetInt64(eventReader, "RENEWAL_TYPE_CD"),

                    RECURREANCE = eventReader["RECURRANCE"].ToString(),

                    RECURREANCE_PATTERN = eventReader["RECURRENCE_PATTERN"].ToString(),

                    MAXRECORDS = Convert.ToInt64(eventReader["MAXRECORDS"]),

                    viewFlag = __GetViewFlag(eventReader),

                };

        }

        private bool __CheckDbNull(OracleDataReader reader, string key)

        {

            return (reader[key] == DBNull.Value);

        }

 

        private decimal __GetDecimal(OracleDataReader eventReader, string key)

        {

            return Convert.ToDecimal(__CheckDbNull( eventReader, key) ? null : eventReader[key]);

        }

 

        private Int64 __GetInt64(OracleDataReader reader, string key)

        {

            return Convert.ToInt64(__CheckDbNull(reader, key) ? null : reader[key]);

        }

 

        private string __GetString(OracleDataReader eventReader, string key)

        {

            return __CheckDbNull(eventReader, key ) ? "--"

                       : eventReader[key].ToString();

        }

       

        private DateTime? __GetDate(OracleDataReader eventReader, string key)

        {

            return __CheckDbNull(eventReader, key)

                       ? null

                       : (DateTime?) Convert.ToDateTime(eventReader[key]);

        }

       

        private string __GetViewFlag(OracleDataReader eventReader)

        {

            return __CheckDbNull( eventReader, "DUE_DATE" ) ? "E"

                       : DateTime.Compare(

                           Convert.ToDateTime(Convert.ToDateTime(eventReader["DUE_DATE"]).ToString("MM/dd/yyyy")),

                           Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"))) >= 0

                             ? "E"

                             : "V";

        }

 

After refactoring one big method into smaller chunks, cyclomatic complexity for original method has been reduced to 8 and other private methods are well under control.

 

Posted On Wednesday, June 3, 2015 7:28 AM | Comments (0)