Adil Akhter's Weblogs

Me, My Thoughts and My Journey ....
Cr-Documentor - A Cool DXCore Plug-in for Visual Studio

May be I am last person on the Earth, who discovered and started using this way too cool plug-in recently ….however, if you have not checked it out yet – probably you should do it now :).

Cr_Documentor gives you just-in time rendering of your XML Documentation to preview it. So, you can update your documentation and at the same time you can preview it how it would look like after you generate documentation for your project using rendering engine like NDoc or SandCastle –

1cr_documentor_realtime

It gives you real time error message if there is any error with the documentation you created. For example , in the following example, since in line 16 , I missed “name” attribute in paramref , it is showing the error with red bold letter :) -

 

2cr_documentor_error

After fixing the problem,  it looks -

3cr_documentor2

In addition , Cr_Documentor  provides a context menu that presents great support  for documentation like-

 

4cr_documentor_contextmenu

Last but not the least, Cr_Documentor also offers options to configure the compatibility level , unrecognized tag handling , Formatting , Display and preview  -

Using the options , you can really configure different aspects of your Documentation. For example, if you change the preview style to SandCastle – the preview will look like -

7cr_documentor_sandcastle

If you want to check it out , you will have to download and Install the DxCore ( A Powerful extensibility framework for Visual Studio) first. Then, you can download and get more details about Cr_Documentor from Google Code.

In conclusion , by leveraging Cr_Documentor, writing and maintaining Xml Documentation for your projects would be far more easy and less error-prone. I can’t help thanking Lutz Roeder and Travis Illig for taking it this far. It’s just wonderful !!!

 

.Net Provider Pattern - Designing decoupled and extensible Component for .Net Application
Introduction

Provider Design pattern of .Net Framework 2.0 is one of the most exciting way to design component in decoupled and extensible way. In my today’s post, I will discuss about this design pattern and how we can use it to make the components inside our applications decoupled while providing extension point for our components and finally I will discuss some of the great advantages of this design pattern. Hence , sit back tight , I will give you a quick tour on Provider pattern which I divided in following sections –

1. What is Provider Design Pattern ?
2. Provider Pattern – Nuts & Bolts in Nutshell

3. Advantages of Provider Design Pattern
4. Last few words…

 

1. What is Provider Pattern?

Provider pattern is a way in .Net Framework 2.0 to design extensible and decoupled Component. Ron Howard mentioned -

A provider is simply a contract between an API and the Business Logic/Data Abstraction Layer. The provider is the implementation of the API separate from the API itself.

Provider Pattern is a way to get rid of the coupling among the components while making the components extensible. Main reason for our today's discussion on Provider Pattern is its wonderful ability to publish the API and at the same time make the API pluggable; that is - it gives us the flexibility to choose the API that is best suited for the application rather than the one developed by API developer. And from an API developer perspective, it allows them to create an extension point for the API where clients of the framework can extend the functionality in their own way.

In the next section, we will see how we can build our component using Provider Design Pattern -

2. Provider Pattern - Nuts & Bolts in a Nutshell

The basic idea behind the provider pattern is to have multiple concrete providers and selecting one of them depending on configuration (just a change in *.config file can lead to completely different provider to perform the operation) at the runtime by avoiding writing huge amount of code and coupling among the components. Provider pattern completely abstract the decision of which provider to use out of programming interface. That way we can say that, it has some kind of dependency injection/inversion flavor, but it does not use any kind of container like Windsor or Spring.net. 

First, let’s consider our problem domain that we will be using throughout today's discussion. For the sake of simplicity, we have the following simple domain object- User and we need a persistence media to store(/Save) and retrieve(/Get) it –

User 
Figure1 : User Domain Object

So, the class responsible for communicating with the physical persistence media -

PersistenceManager has only 2 job now –

  public static void Save<T>(T obj) 
  public static T Get<T>()

Currently we are only supporting two Persistence media - SQL Server2005 and Xml (In File system). Depending on the clients’ need, we will be using any one of them at the runtime, keeping in mind that in future client might use some other persistence media like Oracle , mySql or whatever.

If you are not familiar with provider pattern , you would have solved this problem using any dependency injection container (e.g. Windsor/Spring.Net/Unity) , or introducing factory method to instantiate the desired component at the runtime; that is, either you had to introduce new code (write & manage) or new vocabulary to grasp( with dependency injection container) while providing your custom solution. Truly that would be an overhead if we would like to solve ONLY this problem. Then, why not use something from Framework when Framework is providing it (e.g. Asp.net Membership)?

Here, I will show you how you can solve it using Provider Design Pattern and .Net Framework 2.0 very easily.

Provider design pattern consist of following basic parts –


 API class (PersistenceManager) to publish API( save and get). It is also responsible to instantiate a concrete provider depending on the configuration.

Domain specific Abstract Provider (PersistenceProviderBase) aka Application ProviderBase inherited from ProviderBase class of System.Configuration.Provider namespace.

Concrete Providers (XmlPersistenceProvider and SqlPersistanceProvider) inherited from domain specific Abstract Provider.

Custom Configuration Section to configure the Providers and a class inherited from ConfigurationSection to represent it in .Net.

The following diagram shows different parts of provider design pattern that I will clarify one by one –

providerpattern
Figure2 : Basic Parts of Provider Design Pattern

Let's start with the last part, i.e. ,  Custom Configuration Section -

 Custom Configuration Section

In order to make the provider pattern pluggable and flexible, it is quite obvious that we need to implement a means by which we can configure the provider at the runtime. Application configuration is the most easy and convenient way to link the communication between our Providers and API.

First we need to add a class inherited from ConfigurationSection to handle the configuration of the providers or we can implement :

ClassDiagram3
Figure3 : Class to store Custom Configuration Section

Following is the custom section for the Persistence Provider:

Listing1.1 : Custom Configuration Section:
   1:  
   2:   <PersistenceProvider defaultProvider="XmlPersistenceProvider">
   3:     <providers>
   4:       <add name="XmlPersistenceProvider" type="ProviderPattern.XmlPersistenceProvider, ProviderPattern" PersistenceMediaConnectionString="C:\PersistenceMedia\DocumentInfos.xml"/>
   5:       <add name="SqlPersistenceProvider" type="ProviderPattern.SqlPersistenceProvider, ProviderPattern" PersistenceMediaConnectionString="[Your database connection string]"/>
   6:     </providers>
   7:   </PersistenceProvider>

Important attributes to note here:

1. defaultProvider : Refers to the default Concrete Provider.

2. PersistenceMediaConnectionString : Defined to provide extra information needed to the Concrete Provider. For example , XmlPersistenceProvider will save the information about the domain object in the path specified and SqlPersistenceProvider use the value specified as the connection string to the database.

We can also define as many other attributes as needed that can be used while initializing the concrete provider( e.g. logFilePath). Benefit is, we can come back to the configuration and change it at the runtime and Concrete Provider will be updated accordingly.

Now let's move on and explore the API class whose responsibility is to initialize the concrete provider depending on the configuration section and publish the API.

 API Class

API class is the major gateway to the concrete provider as I mentioned earlier that it communicates directly with the underlying persistence media using one of the concrete provider to perform the operation (e.g. Save/Get) that is exposes –

Listing2.1 : Save Method of API Class:

        public static void Save<T>(T obj)
        {
            if (DefaultProvider == null)
            {
                Instantiate(
PersistenceProviderConfigSection.GetPersistenceConfigSection()); } DefaultProvider.Save<T>(obj); }

Listing2.2 : Get Method of API Class:

        public static T Get<T>()
        {
            if (DefaultProvider == null)
            {
                Instantiate(PersistenceProviderConfigSection.GetPersistenceConfigSection());
            }
            return DefaultProvider.Get<T>();
        }

If we look at the PersistenceManager closely, the static Instantiate method, that instantiate the provider based on the Configuration from PersistenceProviderConfigSection. In order to do that, we have a built in support in the .Net Framework2.0 , that is, we will use ProvidersHelper class of System.Web.Configuration namespace. The ProvidersHelper.InstantiateProviders method initializes the  concrete providers by calling the Intialize() method of the Concrete Providers (I will come back to this point in the next section again).

Listing2.3 : Instantiation of the Providers :

        private static void Instantiate(PersistenceProviderConfigSection configSection)
        {
            if (Providers == null)
                SetupProvider(configSection);
        }

        private static void SetupProvider(PersistenceProviderConfigSection config)
        {
            if (config == null)
                throw new Exception("PersistenceProvider are not configured to be used with this application");

            Providers = new PersistenceProviderCollection();
            ProvidersHelper.InstantiateProviders(config.Providers, Providers, typeof(PersistenceProviderBase));
            DefaultProvider = Providers[config.DefaultProvider] as PersistenceProviderBase;
        }
 

Hence, the DefaultProvider property in the will always refers to the default Concrete provider mentioned in the configuration. Now, we will dive into the details of the Concrete provider and how it gets initialized when we call ProvidersHelper.InstantiateProviders(config.Providers, Providers, typeof(PersistenceProviderBase)).

Note: If you are thinking: why would we add a reference to System.Web.Configuration namespace if it is not a web application, then you are right ;) ? However, we can easily implement class we need to avoid adding reference - ProvidersHelper.( We will come back to this point later.)

Now, let's move to the most important 2 parts of the Provider Design Pattern that is ( you already know isn't it :) ?) - Application speciProviderBase and Concrete Providers .

Application ProviderBase and Concrete Providers

In shortcut, Application ProviderBase class/ Domain specific Provider Base provides the abstract version of the functionality exposed by the API class and the responsibilities of the concrete provider is to implement those API in their own way. As we can see from Figure 4 our Application ProviderBase - PersistenceProviderBase implements IPersistenceProvider which noting but describes the API exposed by our API class.

ClassDiagram2
Figure4 : Application ProviderBase class - PersistenceProviderBase

About the ProviderBase - a class of the Net framework's System.Configuration.Provider namespace which have all the members to be implemented by the concrete providers.

It contains properties to describe the concrete providers – Name and Description. Initialize() is used to initializes the provider.PersistenceProviderBase is the mirror of the API or Services that will be performed by Concrete Provider. It is the place to implement the members generic to the all concrete provider.

Concrete Providers overrides with the concrete implementation(Save/Get of the User) of the abstract API provided in the PersistenceProviderBase class.

ClassDiagram4
Figure5 : Concrete Providers and their members

In addition to that, in the Initalize() method, concrete providers also initialize the properties that are related to the concrete providers and configured through web.config. For example,

  • _PersistenceMediaPath of the concrete providers will be initialized with the value ofPersistenceMediaConnectionString from web.config.
  • Name and Description will be initialized.

Following is the code related to the Initialize of SqlPersistenceProvider :

Listing3.1 : Initialize() of Concrete Provider:

public override void Initialize(string name, NameValueCollection config)
{
    name = string.IsNullOrEmpty(name) ? "SqlPersistanceProvider" : name.Trim();
    base.Setup("SqlPersistanceProvider", "SqlPersistanceProvider saves the T to SQL DB", config);
    _PersistenceMediaPath = config[PersistenceMediaPathKeyName];
    
    //Call the base class to initialize
    base.Initialize(name, config);
}

 

Following diagram shows the Call Stack how the Concrete Providers' Initialize() method get called from the API class when first time it initializes the Providers:

callstack
Figure6 : Call Stack - How all the concrete providers get initialized from API class

After initialization, we are only left with the Provider-specific implementation of the abstract functionality of the PersistenceProviderBase - Save/Get. Every provider will implement in their own way. For example , if we consider XmlPersistenceProvider , it will implement the Save/Get as Listing 3.2 & 3.3, where as , SqlPersistenceProvider will store and retrieve it from Sql Server -

Listing3.2 : XmlPersistenceProvider's Save method

public override void Save<T>(T obj)
{
    string serailzedObj = SerializeHelper.Serialize(obj);
    File.WriteAllText(_PersistenceMediaPath, serailzedObj);
}

Listing3.3 : XmlPersistenceProvider's Get method

public override T Get<T>()
{
    string stringContent = File.ReadAllText(_PersistenceMediaPath);
    if (!String.IsNullOrEmpty(stringContent))
        return ((T)SerializeHelper.Deserialize(typeof(T), stringContent));
    return default(T);
}

Hence , we are done with implementation of the Provider Design Pattern. In the next section, we will look into some benefits that we will achieve by leveraging this Pattern.

3. Advantages of Provider Design Pattern

Here comes, moment of truth. Why would you implement Provider Design Pattern - to create loosely coupled components that are extensible from an application perspective.

If we go back to Listing1.1 where we defined our custom configuration section, we set XmlPersistenceProvider as the default PersistenceProvider. Now, due to any reason, client of our API wants to use SqlPersistenceProvider that we provided with our API. What needs to be done , just change in the value of the defaultProvider in the web.config file and our client can start using the SqlPersistenceProvider.

Listing4.1 : Configuration Section with defaultProvider = SqlPersistenceProvider

   1: <PersistenceProvider defaultProvider="SqlPersistenceProvider">
   2:    <providers>
   3:      <add name="XmlPersistenceProvider" type="ProviderPattern.XmlPersistenceProvider, ProviderPattern" PersistenceMediaConnectionString="C:\PersistenceMedia\DocumentInfos.xml"/>
   4:      <add name="SqlPersistenceProvider" type="ProviderPattern.SqlPersistenceProvider, ProviderPattern" PersistenceMediaConnectionString="[Your database connection string]"/>
   5:    </providers>
   6:  </PersistenceProvider>

Now, due to some reason, our Client wants to develop provider based on , let's say, MySql. That is also pretty simple. They just need to create a Concrete Provider, MySqlPersistenceProvider inheriting from Application ProviderBase(Figure7) and implementing the APIs  by overrriding. In addition, They need to add a <add name = "MySqlPersistenceProvider" ... in the Custom Configuration Section, and they are done. :) Isn't it simple ? :)

Extension_Of_Provider Pattern
Figure7 : Extending PersistenceProviders

Listing 4.2 : Configuration Section with MySqlPersistenceProvider

   1: <PersistenceProvider defaultProvider="MySqlPersistenceProvider">
   2:   <providers>
   3:     <add name="XmlPersistenceProvider" type="ProviderPattern.XmlPersistenceProvider, ProviderPattern" PersistenceMediaConnectionString="C:\PersistenceMedia\DocumentInfos.xml"/>
   4:     <add name="SqlPersistenceProvider" type="ProviderPattern.SqlPersistenceProvider, ProviderPattern" PersistenceMediaConnectionString="[Your database connection string]"/>
   5:     <add name="MySqlPersistenceProvider" type="ProviderPatternExplored.MySqlPersistenceProvider, ProviderPatternExplored" PersistenceMediaConnectionString="[Your my sql database connection string]"/>
   6:   </providers>
   7: </PersistenceProvider>

Using the same process, they can implement any PersistenceProvider they need. Moreover, in future, if we want to add any new Providers, it's just a piece of cake ;). That's make our component very extensible conforming to the Open-Close Principle of OOP.

Last but not the least; these loosely coupled and extensible components results in a less code  to manage and less vocabulary to maintain, since framework is providing the basis for the Provider Design Pattern. Moreover, it gives your team members a familiarity with the existing built-in Providers in .Net Framework.

4. Last few words…

In this example, we saw how we can leverage .Net Provider Design Pattern to make a component loosely couple and extensible.

As I mentioned earlier also, one of the catch implementing provider pattern is that, we have to use ProvidersHelper class of System.Web,Configuration while building the component. But we can easily get rid of adding reference to System.Web namespace, by implementing ProvidersHelper class very easily. (I will try to cover it in one of my next post.)

I tried to clarify the implementation details of Provider pattern in this article , however, still if there are any questions regarding this article, please feel free to ask me. I would really appreciate your feedback.

More on Unit Testing : TestContext

In Test Driven Development  as a developer we spend significant amount of time in writing unit tests. As improving coding coverage, testing all the boundary condition and ensuring the of quality code is significantly important, writing unit test effectively become one of the priority that we has to consider in software development.

In our today's discussion, we will see what is TestContext of VSTS unit testing framework and how we can use TestContext  to leverage writing effective unit tests for our application.

Prior to move forward with our today's Discussion on TestContext, I would really suggest you the following postings-

So, let's begin with a brief description on what is TestContext. Then we will go through different scenarios where we can use TestContext. :)

What is TestContext?

TestContext is a abstract class of Microsoft.VisualStudio.TestTools.UnitTesting namespace that provides various information about the current test run. Purposes that has been served by TestContext Class -

1.  To store information and provide information to the unit tests during Unit Test Run.

2.  Provide a mechanism to measure performance of your code being tested by the Unit Test.

3.  In Testing the web service it stores the additional information, like server's URL.

4.  In Asp.Net unit tests, it get holds of the Page object.

5.  For Data Driven Unit Tests , it provides access to the data rows.

The class definition of the TestContext Class -

   1: public abstract class TestContext
   2:    {
   3:        public const string AspNetDevelopmentServerPrefix = "AspNetDevelopmentServer.";
   4:  
   5:        protected TestContext();
   6:  
   7:        public virtual UnitTestOutcome CurrentTestOutcome { get; }
   8:        public abstract DbConnection DataConnection { get; }
   9:        public abstract DataRow DataRow { get; }
  10:        public abstract IDictionary Properties { get; }
  11:        public virtual System.Web.UI.Page RequestedPage { get; }
  12:        public virtual string TestDeploymentDir { get; }
  13:        public virtual string TestDir { get; }
  14:        public virtual string TestLogsDir { get; }
  15:        public virtual string TestName { get; }
  16:  
  17:        public abstract void AddResultFile(string fileName);
  18:        public abstract void BeginTimer(string timerName);
  19:        public abstract void EndTimer(string timerName);
  20:        public abstract void WriteLine(string format, params object[] args);
  21:    }

To start with the TestContext , we need to add a property in our Unit Test class as -

 

ClassDiagram1  
Figure1: TestContext Property in Unit Test class

Now if we just add a simple test and debug it - we will find that the VSTS Unit Testing Framework actually using an instance of  UnitTestAdapterContext which is derived from TestContext. This property TestContext is automatically initialized/assigned by the test run engine of VSTS when the Unit Test class is initialized after [ClassInitalize] method and before [TestInitalize] method.

image  Figure2 : UnitTestAdapterContext and its' properties in Debug Mode

Want to know more about TestContext?

It would be really hard to find the assembly  that contains UnitTestAdapterContext Class unless we search the private assemblies installed in <vs installation directory>\common7\IDE\PrivateAssemblies ; in my case which is - C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies.The assembly that contains UnitTestAppterContextClass -Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter.dll.

UnitTestAdapterContext class looks like following in reflector -

image
Figure3 : UnitTestAdapterContext in Reflector

How can we use TestContext ?

Like I mentioned in the beginning , we can use TestContext in different cases writing unit tests. Now , we are going to look at some features of TestContext class that we can use very easily in our unit tests.

 

 

Scenario 1 : Getting path of the folder that current test run created for storing input and outputs

 

It's a really handy feature of TestContext. It provides you the path of the unique folder for current test run that VSTS unit testing framework creates in every test run. In VSTS unit testing framework, every test run create a unique folder in  machine where it's running the test and generate a xml based test report ( *.trx) -

 

image

Figure 4 : Folders/Directories that are created by Test Run

Additional input or output of unit test can be stored in this folder and also can be cleaned up before exiting the unit test(if required). Furthermore, it's the safest place to put the additional stuff related to unit tests because our application have full access to this folder ( just consider the situation where unit tests are running in a Build Machine or in a remote server where application might not have access to "C:\Temp\" folder :) ).

 

So, how can we get the path of the folder of current test run? Simple -

string testDirectory = TestContext.TestDir;

We can get access to the deployment folder  and the folder that contain logs  as well -

string deploymentDirectory = TestContext.TestDeploymentDir;
string logDirectory = TestContext.TestLogsDir;

 

Scenario 2 : Generating report how much time was elapsed to complete the Unit Tests

 

TestContext Class has 2 public member BeginTimer and EndTimer which takes a string parameter as argument ( Name of the timer). Using this feature of TestContext class, how much time elapsed to run particular unit test can be measured very easily. This feature of TestContext might be useful in tracking how much time the code to be tested is consuming and whether or not it's going to meet speed criteria of nonfunctional requirements.

 

   1:  TestContext.BeginTimer("longRunningProcess");
   2:   
   3:  // Call the long running method here to test whether it meet the performance requirement
   4:  //....
   5:  //
   6:   
   7:  TestContext.EndTimer("longRunningProcess");
   8:            

Result of the timer is shown as -

image
Figure 5: Output from the Timer

Scenario 3 : Adding additional information in Test Result

 

There is another cool property in the TestContext class which gives you flexibility to provide additional information in Test Result which will be stored in Test Result file( .trx extension stored as Xml). This could be really useful to provide additional information about the Test such as Test Environment, parameter and other details that might be important to store with test result. Lets consider a particular unit test -

 

   1: [TestMethod]
   2: public void ShouldCreateUser()
   3: {
   4:     // ... Unit Test Codes....
   5: }
   6:  
   7: [TestCleanup]
   8: public void TestCleanup()
   9: {
  10:     TestContext.WriteLine("{0} : {1}", TestContext.TestName ,TestContext.CurrentTestOutcome);
  11: }

 

Using TestContext.WriteLine , we can provide additional information [ For Example - just to show, in the above example at line 10 , we are writing the test name and test result] and that is visible to the test result viewer as -

 

testoutput

Figure 6: Output from TestContext.WriteLine


Scenario 4 : TestContext in Asp.Net Unit Testing

 

TestContext provides the access to the Asp.net Page object representing the current web request while unit testing Asp.net Web Application. How? TestContext has a property - RequestPage which is actually an instance of System.Web.UI.Page object and defined as-

"...references the Page object created by the URL used to invoke the test"

TestContextInAspnet

Figure 7: TestContext.RequestPage

This property is only valid for Asp.Net Unit Testing. After getting hold of Page Object of current web request, any control of the page can be accessed using FindControl method of the Page Object. Using PrivateObject class, we can invoke the private/protected methods of the current .Aspx page represented by Page Object.


Example of an Asp.net Unit Test :

   1: [TestMethod]
   2: [HostType("Asp.Net")]
   3: [UrlToTest("http://localhost/ourwebapplication")]
   4: public void TestMethod()
   5: {
   6:     Page page = TestContext.RequestedPage;
   7:  
   8:     PrivateObject privateObject = new PrivateObject(page);
   9:     
  10:     Button button = (Button)page.FindControl("Button1");
  11:     privateObject.Invoke("Button1_Click", button, EventArgs.Empty);
  12:  
  13:     Label label = (Label)page.FindControl("Label1");
  14:  
  15:     Assert.AreEqual<string>("Hello World !!!!", label.Text);
  16: }


We have a label and button in our an .aspx web page. When a button click event occurs, the label text get changed to "Hello world !!!". And another important things to note that we are using IIS to host our web application(line 3).Now, we are going to test this feature using Asp.Net Unit Test in the sample code above.

 

So, first we get hold of our Page object(Line 6) representing our current web request(UrlToTest in Line 3) through the TestContext.RequestPage which eventually enable us to access any control of the page object(e.g. Line 10 & 13). Using the PrivateObject( line 8), we could conveniently invoke any member of the page class as well (line 11).

Hence, using TestContext, we can effective leverage our codes inside Aspx page into Test5 Coverage.


Scenario 5:
TestContext in Data Driven Unit Tests

In Data Driven Unit Test, TestContext provides access to the current DataRow for which test is running and by that way, it provides access to every DataRow of the DataSource one by one.

In the following example, we will see how the TestContext enable us to getting access to every DataRow in the DataSource -

First, lets define our Table that contains few UserContacts with valid information. So, our unit test should create every one as a UserContact of our Application. But that's not our example's goal here. In this example , We will see how TestContext enables us to access every UserContact stored in the UserContact Table so easily.

TableDefinition

Figure 7: UserContact Table Definition

Let's put some Valid User Contact Information in our Table - UserContact -

TableData

Figure 7: Data in UserContact Table

After that, let's write our unit test -

   1: [DataSource("System.Data.SqlClient", "[path to MDF]\";
   2: Integrated Security=True;User Instance=True", "UserContact", 
   3: DataAccessMethod.Sequential), TestMethod()]
   4: public void ShouldCreateUsers()
   5: { 
   6:     string userLoginName = (TestContext.DataRow["LoginName"].ToString());
   7:     string userFirstName = (TestContext.DataRow["FirstName"].ToString());
   8:     string userLastName = (TestContext.DataRow["LastName"].ToString());
   9:     string userEmailAddress = (TestContext.DataRow["EmailAddress"].ToString());
  10:     string userDepartment = (TestContext.DataRow["Department"].ToString());
  11:  
  12:     TestContext.WriteLine("Creating user - Login Name :{0} Name : {1} {2} 
  13:                           EmailAddress : {3} ", userLoginName, userFirstName, 
  14:                           userLastName, userEmailAddress);
  15:  
  16:     bool successful = UserManger.CreateUser(userLoginName, 
  17:                                           userFirstName, userLastName, 
  18:                                           userEmailAddress, userDepartment);
  19:  
  20:     Assert.IsTrue(successful);
  21: }
From the above example, we can see that (line 5  - 10 ) , TestContext is providing us access to the current DataRow for which the unit test is getting executed. We can see the output of TestContext.Writeline(line 12) and Result of the unit test for each DataRow below -

 

 

Scenario 6: TestContext.AddResultFile

 

Last but not the least, TestContext has another useful member called AddResultFile which is defined as -

void AddResultFile(string filename)

Through TestContext.AddResulFile, additional files can be added with the test result. The additional file will be stored in the unique folder created for current test run.This might be useful in some cases, for example, if we are validating our objects with some external resource, like schema - we can store the schema with our test result so that we can validate our test result later on after test run.

Conclusion

Hence, we can utilize the TestContext class in several cases to solve our problem in writing unit tests. But saying all this, I would like to emphasize on designing test cases and map it to a unit test carefully because "Harnessing the power that is provided by the tool and utilizing it effectively and every possible way" could only bring desirable result .

In our today's discussion, we went through several scenarios where we can leverage TestContext to write a better and precisely more effective unit test using the Unit Testing Framework provided with Visual Studio. Thanks for being with me so far and I would really appreciate comments or any suggestion.

I would really appreciate any comments or suggestion on this topic.
 

kick it on DotNetKicks.com
Passing Parameter to a Predicate in .Net2.0

In this post, we will see how to pass parameter to a method representing Predicate.

Let's say, we have a collection of SprintBacklogItem and we want to filter all the SprintBacklogItem with Title start's with, let say "QA" or "Dev Task" depending on a input parameter. Now from the previous post we know that , predicate only have 1 parameter of type T.

image

Then, how to pass a input parameter _HeaderToSearch in Predicate?

1. To do that, we need to a new object called ListMatcher -

public class ListMatcher 
   { 
       private string _HeaderToSearch; 
       public ListMatcher(string headerToSearch) 
       { 
           _HeaderToSearch = headerToSearch; 
       }  

       public bool Predicate(SprintBacklogItem item) 
       { 
           return item.Title.StartsWith(_HeaderToSearch, StringComparison.InvariantCultureIgnoreCase); 
       }  

   }  


2. Next , I initialized the ListMatcher object and use the HeaderToSearch  to filter the items-

ListMatcher matcher = new ListMatcher("QA"); 
this.FindAll(matcher.Predicate);


Done.:)

Posted: Apr 18 2008, 04:34 PM by Adil Akhter | with 4 comment(s)
Filed under: ,
TDD - In a Nutshell
"One Picture's  Worth Thousands Words"

 image

 Benefits( from my personal experience):
1. Development can be done much quicker. You already jot down all the test cases before writing codes. By that way, you are giving much time in thinking how to solve problem. Codes become much more standard and organized because of the brainstorming.
2. Quality of code is far better and deterministic.
3. Tests are the first class document for how your code will eventually work. Any developer/tester can go through the test cases you covered and get the idea how the system should work in different cases. J Isn’t it too cool ?
4. Easier and risk free to change the code - you just need to run the tests, you will get to know where there might be some problem. 


And so on...

 

Why Unit Testing is so important?

Why writing unit tests are so important - lets consider a development team developing a module( call it - [A])did not consider the unit testing that seriously. What happens to that module -

1. [A] produced lot of Bugs in the development phase since it was not tested adequately. And while fixing it- [A] produced severe impact on other modules too because integration was failing again and again. So, the dependent module had to change as well to stabilize whole Delivery.

2. That's not the end of misery. In the release testing, huge amount of bugs identified which also produced from the uncertain behavior of [A]  and fixing those become a hell of a job for the developers. Just to show you one old basic diagram of software development life cycle -

image

3. After the deliverable delivered to the client - Developers could not take pride for that because they were not confident whether they delivered a Good Product( from a developers perspective, I think its really crucial to deliver something from which you can take pride).

4. [A] became more susceptible and fragile day by day. And developers become really reluctant and was not comfortable to change the codes for any change request because of the code's inherent fragility.

5. Refactoring become very error-prone and troublesome.

So, after some time - Developers started calling [A] as "Dead Zone" or Legacy Code because [A] become quite impossible to manage.

Now if we go back to the days when the developers were planing or starting the development process using our Time Traveler- what would you advise them?  :)

The situation that I just described,  its not new to most of the developers developing for a long time. That's why some intelligent people in agile world sit together and come up with some basic rules and practices that we must follow to make our product worth taking pride. One of them is writing Unit Tests for your codes considering all the test criteria considering -

1. Unit Tests are the first users of your Unit who ensure that your own Creation  is working that way you wanted to. Remember - "Taking pride". It become much easier to achieve.In addition, Learning Curve become much higher -because, you get to know very explicitly what are the cases you missed while writing unit tests initially that produce bugs. That way it makes you much mature developer day by day.

2. Unit Tests are the living description how the Unit should work. Any one new to your unit as a developer , should just need some time to go through the Unit Tests to get the Idea how the unit should work.

3. Unit Tests are the tools that make integration much easier.

4.Last but not that least - Refactoring was never been so much easier if there were Unit Tests.

Any comments or suggestions on this post is most welcome.

Using Predicate & Action of .Net2.0

While I started developing software, I faced this situation over and over again where I had to iterate thorough the whole collection and perform some action on each of the element of the collection or filter elements depending on some logic. It was really annoying to  write same for/foreach loop again and again.

.Net framework2.0 resolve this issue where we can just tell the collection how to filter / how to perform some action on each element of the collection and it take care of the iteration part.  Let's check out the List<T> Class of System.Collections.Generic and what support it provides -

image

Huge support for Searching, Sorting and Filtering!!! If we look at the declaration of let's say - FindAll and ForEach  -

public List<T> FindAll(Predicate<T> match);public void ForEach(Action<T> action);

Here Predicate and Actor are the generic delegate which gives us the flexibility to provide a way to filter the collection or perform action to each and every element of the List. Let's dig deeper inside them -

Inside Predicate:

Predicate is a Generic Delegate which takes support from the new generic feature of .Net Framework2.0. It is defined -

delegate bool Predicate<T>(T obj)

As per definition of MSDN, Predicate -

"represents a method that defines a set of criteria and determines whether the specific object meets this criteria."

In short, Predicate is just a generic delegate that takes T as object and check whether the object fulfill some criteria and depending on that return true|false.

Example

In this example, by using Predicate, we are going to tell the Collection how to filter and Collection will handle the whole iteration and filtering process -

Let's say, we have a collection of SprintBacklogItem and we want to filter them depending on there State == Closed, we can do it using predicate -

1. Define a method that represents the Predicate -

private bool HasStateClosed(SprintBacklogItem item) 
        { 
            if (item.State == SprintBackLogStatesStrings.CLOSED) 
                return true; 
            return false; 
        }

This method simply checks whether the SprintBacklogItem's state is closed or not and depending on that , return true or false. Now, if we look at the declaration of the method , we are affirmative that we can use Predicate to represent this method.

2.  Following line of code filters all the closed SprintBacklogItems -

List<SprintBacklogItem> closedItems= _SprintBackLogsItems.FindAll(HasStateClosed);

Inside Action:

Similar to Predicate,

"Action is also one kind of generic delegate which represents a method that take the object as input and perform some operation on that."

Definition of Action delegate-

delegate void Action<T>(T obj);

From the signature of the delegate, it can represent the method with signature that must have one parameter passed to it and void as return type.

In List<T> , the method represented by the Action delegate takes an input obj and perform actions on that.

Example

In this example, by using Action, we are going to perform some predefined actions( initializing ActualHour = 10) on each elements of the List -

1. Define the method that will be represented by Action -

public void InitActualHour(SprintBacklogItem item) 
        { 
            item.ActualHour = 10; 
        }

2. Following line of code initialize all the elements' Actual hour to 10 of the List -

this.ForEach(InitActualHour);

Isn't it pretty cool and slick ? Instead of implementing methods for Actor and Predicate , we could have used Anonymous Delegate. I will cover that topic in my future posts. Bye for now. :)

Posted: Apr 16 2008, 06:30 PM by Adil Akhter | with 3 comment(s) |
Filed under: ,
Designing Efficient Immutable .Net2.0 Objects

What is an immutable object?

By definition immutable object is the object whose state can not be changed after it is created. That means, after creating the object, its publicly exposed members can not be changed from their initial assigned values. On the contrary, mutable objects are objects whose state can be changed at any point of time.

Every developer has to take a important decision whether to make a class mutable or immutable while designing the domain model.
While taking this decision, careful considerations can make us avoid the potential pitfall of using immutable object. 
 Why & How using immutable .Net object – is our today’s discussion. Let’s begin with How part . 

How to implement .Net Immutable Object?

 The way I would implement an immutable .Net class –           

-          Make the fields private readonly.
-          Provide a Public property with get accessor.
-          If the class is no longer needed to inherited – making it sealed. 

Like in the following example, I am implementing an immutable class  UserContact which will be inherited in User  

classdiagram1.jpg

 Here is the Implementation of the Immutable classes –     

    public class UserContact

    {

        private readonly string _Name;

        public string Name   

        {

            get { return _Name; }

        }

        private readonly string _EmailAddress;

        public string EmailAddress

        {

            get { return _EmailAddress; }

        }

        public UserContact( string name , string emailAddress)

        {

            _EmailAddress = emailAddress;

            _Name = name;

        }

    }

UserContact get inherited by User as follows [Since User class is no longer inherited – we make it sealed] -

 

    public sealed class User : UserContact

    {

        private readonly string _UserName;

        public string UserName

        {

            get { return _UserName; }

        }

        public User(string name, string email, string userName)

            : base(name, email) { }

    }


So, isn’t it really easy to implement a Truly Immutable class in .Net framework? J Now the question pops into our mind – why we will be using immutable .net objects , what would be benefits of that ? Let’s explore that –  

 

 

Why use immutable object?

 Protection:

From the definition we know, Immutable objects can not be changed after its being initialized. So, while using inside application, immutable object can flow in different layers of the application without getting worried about being altered by different layers.  

Performance:

Copying object will be much easier, we just need to copy the reference instead of copying the whole object. It would be much faster to copy reference than the whole object.

User user = new User("adil", "adil.bd@hotmail.com", "adak");
User userTemp = user; 

In case of mutable object, we would need to create defensive copy of the object and in .Net term, we need to create a Deep Copy of object otherwise, changing a property in the actual mutable object would reflect everywhere where the object is referenced. For example, let’s consider User as mutable; then changing any thing in user object will have same impact on userTemp as well which is not intended.

To avoid this situation, in case of mutable object, we need to make a Deep Copy of the object which is a costly operation. However, for immutable object, copying the reference would be enough since its state can’t be changed. 

Scalability:

Thread synchronization is an issue of concern while designing multithreaded application. Overhead of synchronizing immutable object is far less than mutable object. By default , an individual immutable object does not need to be synchronized as its state will be not be modified by any thread. However, since the immutable object will still be accessed thorough reference , it would require some synchronization. In complex sync scenarios, immutable object would perform far better then mutable version.   

Consistency: 

If we consider inheritance hierarchy, immutability provides a way for the sub-class to maintain consistency in inheritance hierarchy. Consider following mutable objects–

 

classdiagram2.jpg

When we instantiate the StudentMutable object, the AccountType is automatically set to Student Account –

public StudentMutable(string name , string email , string userName )
: base(name ,email , userName,"Student Account"){}

 Now, we can write following lines by which the AccountType property could be anything other than "Student Account” which is completely inconsistent -   

StudentMutable mutable = new StudentMutable("Adil", "Adil.bd@hotmai.com", "adil");   
mutable.AccountType = "whatever account";   

But if we use Immutable object in inheritance – the object hierarchy will always be consistent.:) 

 

 

What to consider while designing Immutable objects?

Intantiation of immutable object might be considered an operation that will be done more frequently. Then the allocation and freeing the resource for the immutable object would be the most recurrent opertaion which might result as performace overhead. Incase of regular objects , it seems that syncronization is far more costly operation from CPU perspective than allocating and freeing resource.  

For objects that require significant time to initialize , we may consider to implement Object Pool or Flyweight pattern to enhance reusability.  

Conclusion

 So , We can achive much faster and efficient code if we use Immutable object. But by saying all this , definitly we need to design accordingly and carefully so that immutable object can perform to its best. In this article , we learn how to implement immutable object in .Net and what’s its benefits and what we need to consider while implementing immutable object. In my next post , I am thinking to write something about reusing the immutable object to enhance efficiency. Thanks for visiting the the blog. Let me know your comments and feedbacks. Bye J .  

kick it on DotNetKicks.com
Visual Studio2008 Themes
del.icio.us Tags:

If you are also fond of changing the look and feel of Visual Studio using cools themes, here is some cool links for you -

1. A list of Cool themes in Scott Hanselman's blog
2. Dark Visual Studio
3. ZenBurn-based Visual Studio 2005 theme supporting HTML,CSS and XML
4. Join the Dark Side of Visual Studio by Dave Reed
5. TextMate Theme For Visual Studio, Take 2

del.icio.us Tags:

How to change your Visual Studio 2008 Theme -

1. Changing your colors in Visual Studio.NET - Black versus White By Scott Hanselman
2. Dark Visual Studio - By Brad Wilson
3. Pimp MY IDE by Jeff Atwood
4. Code Colorizing and readability by Jeff Atwood

Download LInks -

1. Download Jeff's scheme
2. Download "Zenburn" scheme
3. OrenEllenbogen_DarkSchema.rar (58 KB)
4. Is You IDE HOT or Not?

How to change your themes :

Step - 1 : Click on the Import And Export Settings :

image

Step -2:  Select Import Selected Environment settings and click on Next

image

 

Step -3: You get the option to save your current setting. I would suggest to save it.

image

Step-4: Click Browse and select the *.vssettings file and click Next -

image

Step-5: Check the boxes the setting you want to change and click finish. You are done with you brand new theme.

image

 

If any error occurs or you dont feel like using your new theme, you can always get back to your old setting by getting upto Step4 and setting your themes to import is the one you saved in step - 3 -

image

 

And you also have the option to reset all the settings [Step-1].

Have fun with the themes.

Posted: Apr 16 2008, 06:22 PM by Adil Akhter | with no comments
Filed under: ,
More Posts