Archive for the Category ◊ .Net ◊

Monday, May 20th, 2013

 

The Microsoft source analyzer for C#, StyleCop can be used to enforce a set of styling and consistency rules among .Net teams in a project/ company. StyleCop can be run as a visual studio plugin or can be integrated with an MSBuild project. StyleCop provides an  extensible framework for plugging in custom rules for the developers.  For implementing a custom rule, the user needs to create a custom rules analyzer class which inherits the SourceAnalyzer and overrides the AnalyzeDocument method to check for violations.
In this post, I’ll show how you can implement extensible custom rules in stylecop by using the visitor pattern.
 
Creating the custom rule analyzer class:
[SourceAnalyzer(typeof(CsParser))]
publicclassMyCodeStandardAnalyzerRules : SourceAnalyzer
{
    publicoverridevoid AnalyzeDocument(CodeDocument document)
    {
        var csDoc = document asCsDocument;
        if(csDoc == null) return;
        if(csDoc.HasEmptyRootElement() ||
csDoc.IsAutoGeneratedCode())
return;
        csDoc.WalkDocument(
                ElementVisitor, null, null
            );
    }
    privatebool ElementVisitor(CsElement element, CsElement parentelement, object context)
    {
        //Implementing the custom rules for CsElement goes here
    }
}
 
Creating the visitor interface
publicinterfaceIVisitor
{
    void SetSourceAnalyzer(SourceAnalyzer alanyzer);
    void Visit(CsElement element);
}
 
Writing the first visitor
publicclassCheckForConstantsHaveUpperCaseNameVisitor : BaseVisitor, IVisitor
{
    publicvoid Visit(CsElement element)
    {
        if (element.ElementType != ElementType.Field || !element.Declaration.ContainsModifier(CsTokenType.Const))
            return;
        if(element.Name.Any(char.IsLower))
            AddViolation(element, RuleNames.CONSTANTS_SHOULD_BE_IN_UPPERCASE,
element.Name, element.LineNumber);
    }
}
publicclassBaseVisitor
{
    privateSourceAnalyzer _sourceAnalyzer;
    publicvoid SetSourceAnalyzer(SourceAnalyzer sourceAnalyzer)
    {
        if (sourceAnalyzer == null) thrownewArgumentNullException(“sourceAnalyzer”);
        _sourceAnalyzer = sourceAnalyzer;
    }
    protectedvoid AddViolation(ICodeElement element, string rule, paramsobject[] values)
    {
        _sourceAnalyzer.AddViolation(element, rule, values);
    }
}
 
Creating the Element class to accept the visitor
publicclassCodeElement
{
    privatereadonlySourceAnalyzer _analyzer;
    privatereadonlyCsElement _element;
    public CodeElement(SourceAnalyzer analyzer, CsElement element)
    {
        _analyzer = analyzer;
        _element = element;
    }
    publicvoid Accept(IVisitor visitor)
    {
        visitor.SetSourceAnalyzer(_analyzer);
        visitor.Visit(_element);
    }
}
 
The visitor dispatcher to resolve all visitors (Using a dependency injection container is much easier J)
publicclassVisitorDispatcher
{
    privatestaticVisitorDispatcher _dispatcher;
    privatestaticreadonlyobject _lockObject = newobject();
    publicList<IVisitor> Visitors { get; privateset; }
    publicstaticVisitorDispatcher Instance
    {
        get
        {
            if (_dispatcher == null)
            {
                lock (_lockObject)
                {
                    _dispatcher = newVisitorDispatcher();
                    var visitors = from type inAssembly.GetExecutingAssembly().GetTypes()
                                    where type.IsAssignableFrom(typeof(IVisitor))
                                    selectActivator.CreateInstance(type)
asIVisitor;
                    _dispatcher.Visitors = newList<IVisitor>(visitors);
                }
            }
            return _dispatcher;
        }
    }
}
 
Finally visiting the element with the visitors
privatebool ElementVisitor(CsElement element, CsElement parentelement, object context)
{
    if (element.IsAutoGenerated()) returntrue;
    var codeElement = newCodeElement(this, element);
    VisitorDispatcher.Instance.Visitors.ForEach(codeElement.Accept);
    returntrue;
}
The last step is to build your project and drop the new project’s dll into the StyleCop installation directory and run the style cop
rules on your projects. Style cop will automatically look for assemblies in the directory and pick up the new rules for your team.
Author:
Monday, May 20th, 2013

It could happen that you may have authentication and also authorization in your web application.
The authorization could be at page level and you need to enforce that in every page of your web application.

In these kind of scenarios httpmodule could turn out to be very handy. Httpmodule could be made
to behave like an gate keeper who on every request would check with the page being requested if the
request is from valid user or not. Below C# example would make it clear what I am talking about,

//Define interface which every page is required to implement
public interface IAuthorization
{
bool IsPageAccessible();
}

public partial class RequestedPage : Page, IAuthorization
{
public bool IsPageAccessible()
{
//Your authorization check logic goes here
}
}

public class AuthorizerHttpModule : IHttpModule
{
void httpModule_AuthorizeRequest(object sender, EventArgs e)

{

IAuthorization pageToAuthorize = HttpContext.Current.Handler as IAuthorization;

//Enforce authorization to be implemented.
if(pageToAuthorize == null) { //throw exception}

if(!pageToAuthorize.IsPageAccessible()){ //Redirect to unauthorized page}

}

}

Category: .Net, Security | Tags: , ,  | Leave a Comment
Sunday, May 12th, 2013

 

Every imperative operation in the system represents a command in CQRS. A Command is simply a DTO-type of object that contains the data necessary to make one specific change to the state of the system. The service method that accepts a command does not returns any values. In case of WCF services, if the command execution failed, a fault contract exception is thrown. The method that accepts the command is responsible for validating the command via a command validator object (remember SRP :) ) before passing it to a
handler object to execute the command.
Below is an example of a DTO that encapsulates the command information in our sample. Note that the commands have an Identity object in our sample.
public class RespondToRsvpCommand : ICommand
{
    public Guid RsvpReferenceId { get; set; }
    public bool Response { get; set; }
    public override string ToString()
    {
        return“Respond to RSVP”;
    }
}
 
The command handlers are responsible for executing the commands.
You can normally group commands to an aggregate in a command handler as given
below.
public class RsvpCommandHandler : ICommandHandler<RespondToRsvpCommand>, ICommandHandler<ConfigureRsvpCommand>,
                                    IDependencyResolver
{
    [InjectionConstructor]
    public RsvpCommandHandler()
    {
        ResolveDependencies();
    }
    private ICommandValidator<RespondToRsvpCommand> RespondToRsvpCommandValidator { get; set; }
    private ICommandValidator<ConfigureRsvpCommand> ConfigureRsvpCommandValidator { get; set; }
    public void Process(RespondToRsvpCommand command)
    {
        //RSVP
processing logic goes here
    }
    publicbool Validate(ConfigureRsvpCommand command)
    {
        returntrue;
    }
    publicvoid Process(ConfigureRsvpCommand command)
    {
        //throw
new NotImplementedException();
    }
    publicbool IsValid(RespondToRsvpCommand command)
    {
        return RespondToRsvpCommandValidator.Validate(command);
    }
    publicbool IsValid(ConfigureRsvpCommand command)
    {
        return ConfigureRsvpCommandValidator.Validate(command);
    }
    publicvoid ResolveDependencies()
    {
        RespondToRsvpCommandValidator = Container.Current.Resolve<ICommandValidator<RespondToRsvpCommand>>();
        ConfigureRsvpCommandValidator = Container.Current.Resolve<ICommandValidator<ConfigureRsvpCommand>>();
    }
}
 
As you can see, I’ve used the ICommandValidator instances to validate the respective commands in the context. I’ve also used the unity dependency container as my dispatcher object to dispatch the respective command handlers.
Next: Events
Sunday, May 05th, 2013

CQRS is an object oriented architectural pattern built on the principle that every method should either be a command that performs an action, or a query that returns data to the client, but not both.

A typical CQRS scenario involves 2 DB’s, a write DB which is used to store transitional data for long running processes.  For a process where a service expects multiple messages, it needs a way to temporary store data before the all the messages arrives. For e.g. to make a customer a preferred customer needs an approval from the management, which takes some time to process the request. The service will need a temporary storage for the preferred customer state change request till the approval comes. The write DB is used to store these kinds of data. The Read DB is not updated till the approval comes.

When the approval finally comes, the service will take the customer information from the write DB, complete the registration process and write it to the read DB. At this time, the temporary customer information in the write DB has done its job and can be removed from the write DB. For simpler process such as change customer first name, the change can be written to the read DB right away. Writing to the write DB is not required because there is no temporary data in this case.

This simple approach brings following benefits (from Rinat Abdullin’s blog)

  • Denormalized query persistence is optimized for the reads (which usually make up the most of the persistence IO) resulting in better performance and user experience;
  • We can optimize our read side for the needs of the UI (i.e.: fetching dashboard for the user in a single query) which will result in better development experience and less risk of breaking something on the write side.
  • Read side can be put on some cloud storage, which is inherently optimized for the reads, could be partitioned, replicated and even distributed via CDN;
  • By offloading data reads to synchronous queries we automatically increase the performance of the write side – now it has lower stress and lower probability of hitting a deadlock

This blog is an attempt to implement the principles of CQRS in a very simple way, for demonstrating the concepts of CQRS like:

  • Commands
  • Command Handlers (validation and execution)
  • Queries
  • Query parameters and Query results
  • Command Dispatchers.
Next : Commands

 

Wednesday, May 01st, 2013

 

Most of the tests for a product backlog are defined in terms of UI as that’s how the P.O or stakeholders think of the user story. Creating
UI tests is also important for agile teams as it is a way of telling our customers that the user acceptance scenarios are tested and  verified on every release and he/ she is going to use the application which is intended to work as he/ she expects. But integrating the UI automation tests with the builds (CI) comes with some challenges like browser configurations, non-interactive sessions etc. For these reasons frameworks that do not drive an actual browser, but simulate browser behaviors are becoming popular among agile teams.
 NHtmlUnit is a .Net wrapper of HtmlUnit a UI-less browser for Java programs. It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc… just like you do in your ”normal” browser. NHtmlUnit can be easily integrating with other unit testing frameworks like NUnit, MSTests etc.
A simple example of testing web pages using NHtmlUnit is as given below.
[TestClass]
public class SampleAppSmokeTestSuite
{
    private WebClient _webClient;
    [TestInitialize]
    public void TestInitialize()
    {
         _webClient = newWebClient(); 
    }
    [TestCleanup]
    publicvoid TestCleanup()
    {
        _webClient.CloseAllWindows();
    }
    [TestMethod]
    publicvoid UserLoginAcceptanceScenario()
    {
        var loginPage = _webClient.GetPage(“http://localhost:42017/Home.aspx”) asHtmlPage;
        Debug.Assert(loginPage != null, “loginPage !=
null”
);
        var header = loginPage.GetElementById(“header”);
        Assert.AreEqual(header.TextContent, “NHTML UNIT”);
        var txtUserName = loginPage.GetElementById(“txtUsername”);
        var txtPassword = loginPage.GetElementById(“txtPassword”);
        txtUserName.SetAttribute(“value”, “user@mailserver.com”);
        txtPassword.SetAttribute(“value”, “password”);
        var submitButton = loginPage.GetElementById(“btnLogin”);
        var homePage = submitButton.Click() asHtmlPage;
        Debug.Assert(homePage != null, “homePage !=
null”
);
        var homeHeader = homePage.GetElementById(“header”);
        Assert.IsTrue(homeHeader.TextContent.Contains(“Welcome”));
    }
}
The test initialize methods creates a WebClient object, which is the starting point for NHtmlUnit tests. This object acts as your browser simulator. The GetPage method returns the html page for the Uri passed to the method. The IPage object represents a single web page along with all of the client’s data including HTML, JavaScript, and CSS etc. You can now use this HtmlPage object to access the DOM elements by using methods like GetElementById, or GetElementByClass or GetByXPath etc. Once the elements are accessed you can use the object model to get or set values on these elements and perform actions like Click to simulate the actual behavior of the user. By integrating with an existing unit testing framework, you can do your assertions to validate the results.
Author:
Thursday, April 25th, 2013

Dependency Inversion Principle (DIP)

Basic idea is instead of low level modules are defining the way that high level modules interact with them, we can invert the dependency. So no longer are the high level modules going to be defined on low level ones, but the high level modules will define some kind of interface that low level modules must obey and then the low level modules depends on the interface or abstraction in order to function.

Ex: Portable chargeable devices like mobiles, cameras, laptops

They all have their own ports to get them charged. Like Mobile phones may have micro or mini usb; Cameras will have under connection in; laptops will have their own port.

So you cannot use the same plug to connect these. What’s wrong here is that the surge protector should be defining what these devices should confirm to recharge. As a result the power step should have all the different plugs that the portable devices use to recharge them.

This is an example of not using Dependency Inversion principle.

If we use the Dependency inversion to solve this problem, we will have the common port that will be used for charging and that will be defined by some high-level module (the power step). So the same plug can be used to connect to different type of devices.

The programming example here is:

  1

 We have a high level class depending on interface that is specified by low level class. Now in this case the low level class is not creating an interface. It is just a way the publicly exposed members that low level class defines an interface that high level class uses.

The problem is

2

 

If we have more low level classes, we should have a switch or if statement to be able to handle different low level classes. So the higher level classes should know about all these things and the High Level class is not reusable.

If we invert the dependencies

3

 We have taken that interface above that line. That line represents Layering. If you think about your architecture, the high level class belongs to different layer from the low level. So we have the high level class defining the interface. This might exists as a abstract base class or Interface or some other contract. But the concept is the high level class has said, you must confirm this interface if I am going to use you to do this job. Now the low level class has to confirm the interface specified by the high level class and in fact the high level class also depends on that interface.

If we add multiple low level classes we can provide different implementations.

4

They all depend on the interface. But nothing happened to high level class. It becomes reusable.

Category: .Net  | Leave a Comment
Author:
Monday, April 22nd, 2013

Background:

This is one of my favorite, old and yet powerful feature which is available in C# 3.0 and above version…

Let’s think of a scenario where in, we need to add a new method to already existing class. There are many options available like

If the source code is available, either I can directly go to that class and add the method or

I can inherit that class in my derived class and add new method in my derived class

For ex: To a third party API class “Calculator” which provides methods like Add, Sub, Multiply and Divide of 2 numbers. Let say I need to add new method “HCF” to calculate Highest common factor of 2 numbers

But what if the source code for the class where we need to add new method is not available????

What if I need to use this newly added method at various places??

Here comes the use of Extension methods to make our life simpler and to write code easier… :)

What are Extension methods?

Extension methods are a special kind of static method. These methods are called as if they were instance methods on the extended type.

Extension methods allow us to extend new functionality for existing type without having to create a new derived type, recompile, and modify the original type.

How do we implement it?

Create a static “CalculatorExtension” class and new static method called “HCF”

For whichever class we have to extend the functionality, pass that class in the new method created along with “this” keyword.

public static class CalculatorExtension

{

public static int HCF(this Calculation calc, int x, int y)

{

var highestNumber = x > y ? x : y;

var lowestNumber = x > y ? y : x;

var remainder = 1;

while (remainder != 0)

{

remainder = highestNumber % lowestNumber;

highestNumber = lowestNumber;

lowestNumber = remainder;

}

return highestNumber;

}

}

That’s it. We are done. Wherever we need, we can use that new method as if it was a built in method for Calculator. All extension methods will have a down arrow symbol as you can see below.

Conclusion:

  • This keyword has to be the first parameter in the extension method parameter list.
  • Extension methods cannot access private methods in the extended type
  • If you want to add new methods to a type, you don’t have the source code for it, the ideal solution is to use and implement extension methods of that type.
  • If the extension method created has same signature methods inside the type we are extending, then the extension methods will never be called.

This extension method is widely used in LINQ. In my next blog, I will write a new extension method for LINQ and lets  see the practical use of it .

Category: .Net  | Leave a Comment
Author:
Thursday, April 18th, 2013

Microsoft Fakes

The fakes framework can be used to test any .NET method. Microsoft fakes mocks objects with no preexisting interfaces.

The fakes framework actually provides two ways to create mock objects.

  1. Shims
  2. Stubs

Getting started with Sims

Create a new class library in visual studio 2012. And add the class CartToShim

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

namespace FakingExample

{

 public class CartToShim

{

publicint CartId { get; set; }

publicint UserId { get; set; }

public ReadOnlyCollection<CartItem> CartItems { get; set; }

private List<CartItem> cartItems = newList<CartItem>();

public DateTime CreateDateTime { get; set; }

public CartToShim(int cartId, int userId)

{

CartId = cartId;

UserId = userId;

CreateDateTime = DateTime.Now;

CartItems = new ReadOnlyCollection<CartItem>(cartItems);

}

public void AddCartItem(int productId)

{

var cartItemId = DataAccessLayer.SaveCartItem(CartId, productId);

cartItems.Add(new CartItem(cartItemId, productId));

}

}

}

 

Add CartItem class

namespace FakingExample

{

 public classCartItem

{

   public int CartItemId { get; set; }

   public int ProductId { get; set; }

   public CartItem(int cartItemId, int productId)

{

CartItemId = cartItemId;

ProductId = productId;

}

}

}

Add the DataAccessLayer class

using System.Data;

using System.Data.SqlClient;

namespaceFakingExample

{

publicstaticclassDataAccessLayer

{

public static int SaveCartItem(int cartId, int productId)

{

using (var conn = newSqlConnection(“”))

{

var cmd = newSqlCommand(“InsCartItem”, conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue(“@CartId”, cartId);

cmd.Parameters.AddWithValue(“@ProductId”, productId);

conn.Open();

return (int)cmd.ExecuteScalar();

}

}

}

}

 

Add unti test project to the solution

In the untitest project, add the FakingExample project

Now right click on the FakingExample reference in the unit test project and select “Add Fakes Assembly”

This will create the following references

Shim

Now we are ready to do faking.

Add CartToShimTests test class to the test project

using Microsoft.QualityTools.Testing.Fakes;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FakingExample.Tests

{

[TestClass]

public class CartToShimTests

{

[TestMethod]

public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()

{

using (ShimsContext.Create())

{

int cartItemId = 42, cartId = 1, userId = 33, productId = 777;

Fakes.ShimDataAccessLayer.SaveCartItemInt32Int32 = (c, p) => cartItemId;

var cart = new CartToShim(cartId, userId);

cart.AddCartItem(productId);

Assert.AreEqual(cartId, cart.CartItems.Count);

var cartItem = cart.CartItems[0];

Assert.AreEqual(cartItemId, cartItem.CartItemId);

Assert.AreEqual(productId, cartItem.ProductId);

}

}

}

}

 

Now run the unti test. Notice that our test completely skipped over the SaveCartItem in DataAccessLayer, otherwise we would have received exception saying invalid connection string.

 

In my next post I will show the Stubs example.

 

 

Thanks

Vinay

Author:
Friday, January 25th, 2013

Misuse of exception handling has been a common problem in any software project that do not have a proper guidelines, strategy or framework on how to handle exceptions. It leads to lost of bugs coming over and over again. The purpose of this article is to establish some practices for proper exception handling code.

Practice #1: Never use “catch(Exception e)”

Catching exception like this, swallows the original exception and causes

  • Unexpected and unfriendly exceptions shows up on the application user interface. Ex: “Object reference not set to an instance of an object”
  • Developers/Programmers have tough time debugging the origin of the problem in the source code.
  • The software sometime continues to work as if no error has happened and the failure is never fixed.

Let me expain the problem with this kind of exception handling with a small C# example. Consider the following code:
try
{
CallSomeMethod();
}
catch (Exception e)
{
... do something here....
}

That will catch ALL exceptions that emit from CallSomeMethod(), including exceptions that should not be caught at this point. Some exceptions should be handled by higher level code. Some exceptions should cause the application to crash. The code should only catch the most specific exception type that needs to be handled and allow all other exceptions to pass up the call stack.

For example, next year another programmer may modify CallSomeMethod() to throw a new exception that needs to be handled by the UI. Since the code will catch that exception, the User Interface layer will never see the exception, and therefore will not function properly.

For example, a lower-level system call may throw an exception caused by some resource failure (unable to load a file or open a network port) that should stop the application. However, the catch() will stop the exception, the application will continue to run, and the end-user will complain that it is not functioning properly.

In both the examples, programmer/developer will have a hard time to debug any issue related to CallSomeMethod API.

Practice #2: Logging is not sufficient error handling.

Consider this code:
try
{
CallSomeMethod();
}
catch (SomeException e)
{
log.Error("Oops there was an error: {0}", e.ToString());
}

The users will never know that an error occurred, because they don’t read the log file unless they have a reason to. If the application appears to be functioning, and does not display an error message on the screen, then the user has no reason to read the log file. However, the application may not be functioning properly, and the users will not be aware of the problem.

The only case where logging is sufficient is when the exception is re-thrown.
catch (SomeException e)
{
log.Error("Oops there was an error: {0}", e.ToString());
throw;
}

OR
catch (SomeException e)
{
log.Error("Oops there was an error: {0}", e.ToString());
throw new SomeOtherException("error here", e);
}

Category: .Net  | One Comment
Monday, January 21st, 2013

 

It is a common scenario in domain modeling to implement roles such as Manager, Salesman, and Engineer etc. in the applications, which are basically subclasses of a common role player class such as an Employee. However, this means that different instances of the role classes are actually different objects with different state and different identity, even if they are meant to represent the same logical entity.
At first glance it sounds like a case for inheritance, but there are complications as the same object may show multiple behavior or can
make changes to another role during its lifetime. For e.g. an Engineer may become an Architect or a Manager in the organization. The expectation is to have a model where a class could be seen as more than one concept or role, and where attributes specific to one of those concepts can be specified.
The Role Object Pattern addresses this problem by representing an object and its roles as a composition of one role player object
and arbitrarily many role objects. The role class model provides the flexibility of the association with role-specific attributes and even class operations, if needed.
Using the role object pattern the above problem statement can be addressed like 
The employee class defines methods for managing roles via the RoleObject abstraction. The common superclasses for employee specific roles are provided by the EmployeeRole class. The concrete implementations for the EmployeeRole like Engineer, Salesman or Manager define and implement the interface for specific roles. The role objects are instantiated at runtime and added to the employee to add operations specific the role.
[TestClass]
public class EngineerRoleTests
{
    private Employee _employee;
    [TestInitialize]
    publicvoid Initialize()
    {
        _employee = newEmployee(“Prajeesh Prathap”);
        _employee.AddRole(newEngineer());
    }
    [TestMethod]
    publicvoid CanRetrieveARoleFromAnObjectAtALaterPoint()
    {
        var manager = _employee.GetRoleOf<Engineer>();
        Assert.IsNotNull(manager);
    }
}