Saturday, May 26, 2012

WCF Service Vs Windows Service


This article is all about understanding WCF and Windows service. We will first try to understand what it is at high level and then dig in more.

WCF Service

WCF is meant for designing and deploying distributed applications and it’s a framework for building service-oriented applications.

What is SOA?

A service-oriented architecture is a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating each other to do some activity.

SOA is a buzz word also it is a misconception that when it comes to SOA, we have to create and consume WCF services.Some architects mistakenly assumes and considers WCF as default. However in theory point of view it doesn’t really matter how it’s being implemented. WCF just provides a means for developing distributed services.

We all started working with Web services before WCF came into picture. Web services by itself is service oriented implementation. Guys we already we aware of what are SOA.

Simply stating for SOA, the most basic components would be a service user and a service provider that’s all. As I already mentioned about WCF, its Microsoft’s implementation of service oriented architecture.

What is a Service?

In simple words, a service is the work performed by one that serves or helps.

A service is a reusable component that can be used as a building block to form larger, more complex business-application functionality.

Services are independent. They don’t know or really care whether the service is:
– Running on Windows, J2EE or a Mainframe
– Written in assembler, C, Java, or COBOL.
– Being served by a CRM system, a DDA system, or a database

Don’t think service as just one big massive thing. The services can be broken into compound and granular services.

Why do we need an SOA?

The systems that we build and use today are much complex ones. That doesn’t mean the older systems are not much complex. From my own personal experience, When I was working for Healthcare clearing house , there were products which were built with technology like Foxpro , VB, .NET components (these are legacy systems for now that’s a different story) which are still running since from nearly 20 yrs.

The Object Oriented (OO) solved the problem for medium sized systems or applications. The component orientation solved the problem that a simple objected oriented could not do in a medium sized products or applications. With large systems, neither of this could solve the problem.


When is SOA good and Bad?

Good when you are building a large system or systems of systems or planning for distributed systems then it’s good to go.

It’s bad when there are no distributed systems. It may not be feasible for small or medium sized systems.

Windows Service

Windows service is generally used when an application needs to run continuously in the background without any human intervention. The main functions of a windows service is to run in the background.

We can set the windows service to start automatically when the machine boots and also we can manually stop and re-start later if required.

In simple, these services are developed when we want everything to be done and in a same machine. In contrast to WCF services these services are not distributed in nature. We can have multiple services where in each one can perform some activities.  But as such windows services won’t provide any service to consumers. I mean in general we use windows service to do something autonomously without any other external applications interacting with it. However we can host a WCF service with in a windows service and make the WCF services available to consume within in an intranet environment.

Consider an example where in you can make use of this. You have developed an application which pushes some messages (Say Windows MSMQ or a Service broker queue). In such cases you can go with a simple windows service which runs in the background continuously monitoring the queue for the incoming messages. Once you have the message, we can simply process the same.

Monday, May 7, 2012


Behavioral Driven Development (Part 1)

Behavioral driven development is all about documenting or producing the executable specification. We think in terms of various scenario’s or steps and write unit tests to verify the behavior of objects under test.


BDD is said to be superset of TDD. If you are aware of the TDD process where in we write the failing unit tests, then write the production code; verify the test to make it pass. Refactor code and verify the tests. 


One thing I would like to tell the reader is BDD is not just about unit testing. It’s about how you drive your tests with various behaviors. One has to think and come up with various scenarios for a use-case then start writing acceptance test for the same.


TDD Technique




















With BDD, we are writing a feature tests. What that means is write unit tests with the behavior in mind. We think about various scenarios and write unit tests to make it to pass.

BDD focuses on the Acceptance tests or executable specification. Think as an end user performing various steps to accomplish a particular use case/scenario. You can go with one Use case at a time and follow the acceptance tests to cover the same.



BDD Technique














The key difference what we can think of TDD and BDD is the focus on the initial design and creation of tests. With BDD we are focusing on the steps or features to achieve our goals rather than focusing on the just writing a passing test with TDD.

BDD is all about documenting the executable specification in terms on Unit tests which verifies the behavior of our system. There are many tools available for doing BDD. SpecFlow is one among the good tool that I personally suggest with which we can easily write acceptance tests describing the features.




Saturday, May 5, 2012


Introduction to Mocks and Stubs


Mock objects are simulated objects that mimic the behavior of real objects in controlled ways. We typically create mock objects to test the behavior of some other object.

A stub is a replacement for an existing dependency in the system. By using a stub, you can test your code without dealing with the dependency directly.

Consider a scenario where you need mocks and stubs

    You want to simulate the behavior of the dependent objects, say you wish to mock and test EmailSender. While testing such things we won’t be really connecting to Email server. In this scenario, we can simply mock and test the behavior of email sender and verify the expectations set against the mock object.

    Imagine you are testing a data access class which connects to DB fetches, inserts / updates some data. We can make use of mock and stub techniques to test the DAO logics without the database dependency.

Why Mocking?

If you are planning to isolate the dependencies of an object and unit test, then you will have to mock and test.

Here I'm considering an example of User object which has SendEmail method used to send an email with subject, body and email address.

public class User
{
    public FirstName { get; set; }
    public LastName { get; set; }
    public UserName { get; set;}
    public Password { get; set; }
    public Email { get; set; }       
    public User() { }
    public bool SendEmail(IEmailSender emailSender)  {
        string subject = "Your Password";
        string body = String.Format("{0} {1}, your password is {2}", FirstName,  LastName, Password);
        return emailSender.Send(subject, body, Email);
    }
}

You will notice one thing here the User object depends on the instance of IEmailSender type to send mail for the specified user email address.


public interface IEmailSender
{
   bool Send(string subject, string body, string email);  
}

We will learn how we can mock the EmailSender and test the expected behavior.

The below example is making use of Moq Framework for mock and unit testing

[Test]
public void User_Can_Send_Email()
{
        var emailMock = new Moq.Mock<IEmailSender>();
        emailMock
             .Expect(sender => sender.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
             .Returns(true);        
          User user = new User();
          Assert.That(user.SendEmail(emailMock.Object) == true);
}

The unit tests creates a mock object of type IEmailSender and sets the expectation for Send method with any arguments passed as a parameter to it should return ‘true’.

At the ends of the unit test, we did an assertion for the user.SendMail to verify for the true value. You can also add a .Verifiable() on the end of the mock setup code and then call emailMock.Verify() after you run your test code and verify that the method was actually called.

An Example for a Stubbed Class

public class StubbedSecurityDataStore : ISecurityDataStore
{
    public bool Authenticate(string userName, string password)
    {
        return true;
    }
    public string[] GetRoles(string userName)
    {
       return new string[]{“Admin”, “Write”, “Read”};
    }
}

About Moq Framework

Moq is an open source framework and has adopted an API that tries to be both simple to learn and easy to use. The API also follows the arrange-act-assert style and relies heavily on .NET 3.5 features, such as lambdas and extension methods. The learning curve is quite easy, but you need to feel comfortable with using lambdas. 

Difference between Mock and Stubs

Mock objects are used to define expectations i.e. we expect some methods to be called with such and such parameters. Mocks record and verify such expectations.

Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to provide “fake” objects in order to utilize a test scenario. Stubbing a method is all about replacing the method with code that returns a specified result. Most important thing is a stub will never cause a test to fail.