Author Archive

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.
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.
Wednesday, January 23rd, 2013

When you start to solve a problem in TDD, one of the questions that most of the developers have is about the correct place to start testing the code.

Is it better to start with a high level functional test (Outside-In) at a user story and drill down into the low level tests as you  progress or to come with an initial low level design and then start writing tests from the lowest component (Inside-Out) in the design and progress to the higher level components?

A short answer would be that it depends on your / team’s coding preference or approach.

If you’re not sure how your code should look like or how it will interact or communicate with other parts of your system, it’s better to have a small design discussion with the team to identify the best possible design solution and start with the low level component and let it evolve as you write more tests.

But if your design already exists (Layered approach, where the layered components are identified like controllers, services, repositories etc.), you can start with the Outside-In approach.

As you see, Inside out testing implies a developer would probably consider the high-level design and break them up into low level components that interact with each other to provide the desired functionality. The developer thinks about how each component will be used by its client components and tests accordingly.

The advantage is that the team can deliver working software quickly as they have started with a proper design in his mind. However, since the code delivered was not written considering the high level user requirements, it may produce code that doesn’t go well with the YAGNI principle and also have a risk of not meeting the actual functionality.

In the Outside In approach, the part of system that has the closest correlation to the user requirements are tested first, guarantees that the critical parts of the application is tested first. Here the focus is more on how the user interacts with the system, rather than how the components interact with each other. The test cases generated hence supports the usability of the system.

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);
    }
}
Monday, December 17th, 2012

 

Dependency injection bindings through an IOC container can be achieved by different ways. For e.g. you can use an XML file based
configuration for registering types or use an imperative code block for registration. Both of these methods use an explicit way if registering and resolving types.
Another common and an easy approach is to use attributes to register and resolve types. In this post, we’ll extend the SharePoint service locator, to register types based on attributes to the container, which can be later used to resolve the mappings.
Creating the attribute:
public class SetAutoRegistration : Attribute, ISpAttribute
{   
    public Type InterfaceType { get; privateset; }
    public string Key { get; privateset; }
    public SetAutoRegistration(Type interfaceType) : this(interfaceType, string.Empty)
    {
    }
    public SetAutoRegistration(Type interfaceType, string key)
    {
        InterfaceType = interfaceType;
        Key = key;
    }
}

Creating a mappings object to define type mappings:
public class Mapping
{
    public Type FType { get; privateset; }
   
    publicType TType { get; privateset; }
   
    public string Key { get; privateset; }
    public Mapping(Type fType, Type tType, string key)
    {
        FType = fType;
        TType = tType;
        Key = key;
    }
}

Extending the ServiceLocator class to add type based mappings:
[SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]
[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public void RegisterTypeMapping(Type fromType, Type toType)
{
    RegisterTypeMapping(fromType, toType, null);
}
[SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]
[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public void RegisterTypeMapping(Type fromType, Type toType, string key)
{
    var typeMappings = GetConfigData();
    var newTypeMapping = newTypeMapping(fromType, toType, null) { InstantiationType = InstantiationType.NewInstanceForEachRequest };
    RemovePreviousMappingsForFromType(typeMappings, newTypeMapping);
    typeMappings.Add(newTypeMapping);
    SetTypeMappingsList(typeMappings);
}
[SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]
[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public void RemoveTypeMappings(Type type)
{
    var typeMappings = GetConfigData();
    foreach (var mapping in typeMappings.ToArray())
    {
        if (mapping.FromType == type.AssemblyQualifiedName)
        {
            typeMappings.Remove(mapping);
        }
    }
    SetTypeMappingsList(typeMappings);
}

Using reflection to register types to service locator during feature activating:
var assembly = Assembly.Load(assemblyToProbe);
var typesToAdd = assembly.GetTypes().Where(x => x.GetCustomAttributes(typeof (SetAutoRegistration), false).Length > 0);
types.AddRange(typesToAdd);
var mappings = BuildMappingsFromTypes(types);
foreach (var mapping in mappings)
{
    if (mapping.Key == string.Empty) serviceLocatorConfig.RegisterTypeMapping(mapping.FType, mapping.TType);
    else  serviceLocatorConfig.RegisterTypeMapping(mapping.FType, mapping.TType, mapping.Key);
}

Attribute based registration in action:
[SetAutoRegistration(typeof(IMyRepository))]
public class MyRepository : BaseRepository<MyEntity>, IMyRepository
{
You can use the same approach to register types to activating service locator for the test cases.
Sunday, December 16th, 2012

 

The SharePoint Service Locator is a reusable component from the MS Patterns & Practices that provides a simple implementation of the service locator pattern. You can use it in your own SharePoint applications to decouple the consumers of an interface from the implementations of that interface. Instead of creating an object by invoking the constructor of a class, you request an object with a specified interface from the service locator. The service implementation can now be replaced or updated without altering the consuming class implementation.
The usage of service locator makes it easy to dependencies that are scattered throughout various projects and solutions. These
dependencies often make it challenging to maintain code over time—if you modify one class, you must recompile every project that references that class. This also makes unit testing code in isolation much more complicated. In short, decoupling your code from specific types makes your code more modular, easier to manage, and easier to test. You can use the RegsiterTypeMapping
method of the ServiceLocatorConfig instance to register the mappings to the service locator.
var serviceLocator =SharePointServiceLocator.GetCurrent();
var mappingsConfig = serviceLocator.GetInstance<IServiceLocatorConfig>();
mappingsConfig.RegisterTypeMapping<IMyService, MyService>();
You can retrieve the interface implementation later in your code using the GetInstance method of the ServiceLocatorConfig instance.
serviceLocator.GetInstance<IMyService>();
Normally you register the instances during the feature activating event and you need to remove the registered mappings from the service locator during feature deactivating event using the remove mappings method.
var serviceLocator =SharePointServiceLocator.GetCurrent();
var mappingsConfig = serviceLocator.GetInstance<IServiceLocatorConfig>();
mappingsConfig.RemoveTypeMapping<IMyService>(null);

Unit testing challenge – Replacing the ServiceLocator in the test context
The service locator from the P&P uses the sharepoint object model to keep store of the mappings and other properties. To
successfully unit test the code that uses the service locator, you need to either use a wrapper object for the service locator or use the ActivatingServiceLocator object instead of the ServiceLocator in the test code.
To replace the service locator instance, you need to replace the actual service locator with the ActivatingServiceLocator
instance as given below.
var activatingServiceLocator =newActivatingServiceLocator();
SharePointServiceLocator.ReplaceCurrentServiceLocator(activatingServiceLocator);
conststring type1 =“Type1″;
conststring type2 =“Type2″;
activatingServiceLocator.RegisterTypeMapping<INotRegisteredType, NotRegisteredType1>(type1);
activatingServiceLocator.RegisterTypeMapping<INotRegisteredType, NotRegisteredType1>(type2);
var notRegisteredType =SpServiceLocator.GetInstance<INotRegisteredType>(type1);
Assert.IsInstanceOfType(notRegisteredType, typeof(NotRegisteredType1));
SharePointServiceLocator.Reset();
Sunday, December 09th, 2012

 

With the availability of Visual Studio 2012 SharePoint Emulators the isolation of the SharePoint API is much easier compared to the
old way of isolating using the Moles or Fakes framework.  In order to incorporate emulators into existing tests you should wrap the relevant code in a SharePointEmulationScope, which accepts EmulationMode enum as a parameter. It is enabled by default which in turn performs run time interception of all Microsoft.SharePoint.dll calls.
You can use the new emulator in your unit test project by using nuget packaging manager and convert your old test case to the new
emulation scope as given below 
 [TestMethod]
publicvoid BuildFromSPListItemShouldCreateANewObjectWithPopulatedValues()
{
    using(ShimsContext.Create())
    {
        var dataMapper = newMyObjectDataMapper();
        conststring customDescription = “Custom
Description”
;
        var spListItem = newShimSPListItem
        {
            ItemGetString = (fieldName) =>
            {
                if (fieldName == BaseInternalFields.Id) return1;
                if (fieldName == BaseInternalFields.Title)
                    return“Some Title”;
                return fieldName == RulesInternalFields.CustomDesc
                    ? customDescription
                            : null;
            },
            FieldsGet = () => newShimSPFieldCollection
            {
                ContainsFieldString =
                    (internalName) =>
                    internalName.Equals(BaseInternalFields.Id) ||
                    internalName.Equals(BaseInternalFields.Title)
||
                    internalName.Equals(RulesInternalFields.CustomDesc)
            }
        };
        var myObject = dataMapper.FromSPListItem(spListItem);
        Assert.IsTrue(myObject.CustomDesc == customDescription);
    }
}


[TestMethod]
publicvoid BuildFromSPListItemShouldCreateANewObjectWithPopulatedValues
()
{
    using (var emulation = newSharePointEmulationScope(EmulationMode.Enabled))
    {
        var dataMapper = newMyObjectDataMapper();
        conststring customDescription = “Custom
Description”
;
        using(var emulatedSite = newSPSite(“http://localhost:8081/MySite”))
        {
            var listId = emulatedSite.RootWeb.Lists.Add(“MyList”, “Custom list”, SPListTemplateType.GenericList);
            var list = emulatedSite.RootWeb.Lists[listId];
            var listitem = list.Items.Add();
            listitem["Title"] = “mytitle”;
            listitem["CustomDesc"] = “Custom Description”;
            var myObject = dataMapper.FromSPListItem(listitem);
            Assert.IsTrue(myObject.CustomDesc == customDescription);
        }
    }
}

Because the emulator relies on the Fakes framework, you can easily reuse your existing code to use the emulators without much pain.
Thursday, December 06th, 2012

Enabling continuous quality is a key focus area of Update 1for VS2012. With the release for Update 1, code coverage results are available for automated test cases as well as manual tests. You can now record your coded ui tests and analyze the code coverage for these tests. Using the test explorer, you can now analyze the code coverage results for a group of tests or a single test.

You can also use the test manager to get the code coverage results for the manual test cases, for enabling code coverage, make sure that you deploy the related .pdb files and provide the path for the files in the settings. The test settings also allow you to specify the environment for running the test cases. You can now choose your target build and run the manual tests cases after choosing your
settings. Once you complete the manual tests, the code coverage results for the executed tests are displayed along with your build results.
Using Test Explorer, you can group and run tests based on their traits (Test Category, Test Property, Priority, and Owner). You can also pause and resume manual test sessions in Microsoft Test Manager, and automatically create an image log of all actions performed during an exploratory testing session.
Update 1 also supports cross-browser testing, with the ability to record web tests in Internet Explorer and then later replay them
with most modern browsers. You can enable cross browser automation by just adding a single line of code to the test methods.
[TestMethod]
publicvoid SampleCodedUITest()
{
    BrowserWindow.CurrentBrowser = “chrome”;
    this.UIMap.FailedLoginTest();
    this.UIMap.RegisterTest();
    this.UIMap.LoginPassTest();
    this.UIMap.AboutPageTest();
    this.UIMap.AssertAboutPage();
}
You can also use the browser name to be loaded from configuration file for complete automation.