Pages

Thursday, December 26, 2013

How to generate fake data for software testing

Code Project published my last work about a new .NET library MockData for generating fake data.
You can read it at http://www.codeproject.com/Tips/697006/Creating-mock-data-for-software-testing
I look forward to hearing your feedback

Friday, December 13, 2013

C# Ruby Style

Among other awesome features introduced in C# 3.0 are amazing extension methods. It looks like taking on board dynamic-language-oriented people. Now this Ruby-style can be done in C#:
1.To(7).DoSomething();



Woohoo! It is amazing ... the feature is quite powerful and if you think about that a little bit intimidating for a static-language mind. You will be definitely more comfortable with the idea of such a freedom.
How you can do it ? With a small piece of smart code
public static class Extension
    {
        public static IEnumerable<int> To(this int from, int to)
        {
            return from < to
            ? Enumerable.Range(from, to - from + 1)
            : Enumerable.Range(to, from - to + 1).Reverse();
        }

        public static void  DoSomething(this IEnumerable<int> values)

        {
            foreach (int i in values)
            {
                Console.WriteLine(string.Format("{0} Count : {1}","Do Something",i));
            }
        }
    }

And you can write

class Program
{
        static void Main(string[] args)
        {
            1.To(7).DoSomething();
             Console.ReadKey();
        }
}

Enjoy yourself 

Sunday, December 8, 2013

ViewData ViewBag and TempData in MVC

ViewData is a in built dictionary object that can be accessed and set with string type key values. It is derived from ViewDataDictionary class and is a very handy data structure when it comes to passing data from Controller to View. The data is only alive for one request and cannot persist between request. The only problem with ViewData is that the type casting is required for complex data types at the location where the data is being extracted.
ViewData["Name"] = "Hello World !";
string strValue = ViewData["Name"].ToString();

ViewBag is data structure has been created to utilize C# 4.0 possibility of having dynamic Variables.  This is written as a wrapper over the ViewData so that the type casting for complex objects will not be required if we use ViewBag ViewBag comes with all the benefits of ViewData with an additional benefit that type casting is not required.
ViewBag.Name = "Hello World !"
strint strValue = ViewBag.Name;

Now the problem with all the above ways of data transfer was that the data is only alive for current request. The data is lost if a redirection takes place i.e. one Action redirects to another action. For the scenarios where we need to persist the data between actions/redirection another dictionary object called TempData can be used. It is derived from TempDataDictionary . It is created on top of session. Its will live till the redirected view is fully loaded It requires typecasting for complex data type and check for null values to avoid error.
TempData["Name"] = "Hello World !"
string strValue = TempData["Name"] != null ? TempData["Name"].ToString() : String.Empty;

The important difference between ViewData-ViewBag  and  TempData  is the life time of the structure.

There is also the possibility to use Session. It is he way to persist the data till the current session is alive. If we need some data to be accessible from multiple controllers, actions and views then Session is the way to store and retrieve the dataIt requires typecasting for complex data type and check for null values to avoid error.
Session["Name"] = "Hello World !";
string strValue = Session["Name"] != null ? Session["Name"].ToString() : String.Empty ;

Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.

Saturday, December 7, 2013

Strategy Pattern

Directly from the Strategy Pattern Wikipedia article:

The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

Let's see how it works using C# language. In my sample i show you as we can change the Sort Algorithm using a Context class to implement this swap.

namespace StrategySample
{
public interface IStrategy
{
List<string> SortData(List<string> inputData);
}
        // We declare a class to implement QuickSort ordering algorithm
public class QuickSort : IStrategy
{
public List<string> SortData(List<string> inputData)
{
List<string> sortedData = new List<string>();
// do QuickSort algorithm to sort data
return sortedData;
}
}
       // We declare a class to implement BubbleSort ordering algorithm
public class BubbleSort : IStrategy
{
public List<string> SortData(List<string> inputData)
{
List<string> sortedData = new List<string>();
// do BubbeSort algorithm to sort data
return sortedData;
}
}
       // We declare a class to implement the context for sorting
public class SortContext
{
IStrategy _strategSort;

public SortContext(IStrategy strategy)
{
_strategSort = strategy;
}
public List<string> Sort(List<string> inputData)
{
return _strategSort.SortData(inputData);
}
}
}

Now let's see the pattern in action

static void Main(string[] args)
{
        SortContext context;
        List<string> data = new List<string>();
        List<string> sortedData =  context.Sort(data);
        // Create the inputData
data.Add("string one");
data.Add("string two");

        // We apply QuickSort algorithm
context = new SortContext(new QuickSort());
        sortedData = context.Sort(data);
foreach (var item in sortedData)
{
Console.WriteLine(item);
}

         // We apply BubbleSort algorithm
context = new SortContext(new BubbleSort());
sortedData = context.Sort(data);
foreach (var item1 in sortedData)
{
Console.WriteLine(item1);
}
}

Basically we inject the Interface implementation into the Context Strategy class and we use polymorphism to run the different behavior.

A Web Work Example

Create a new web application. Add an index.html page, a Scripts folder named Scripts and two JavaScript files inside it. Name one main.js and the other myWorker.js. 
Inside the index page, add a script reference to the latest version of jQuery at the top and a reference to scripts/main.js at the bottom before the closing </body> tag. 
Next, add an input button to test our functionality. 

<input type=button id="testWorkers" value="Test Workers" />

Finally, inside main.js, add the following code to handle document.ready and to create a simple object to contain our test code.

Start Code main.js
$(document).ready(function () {
   workerTest.init();                                                                             //#Comment A
});
window.workerTest = {
   myWorker: null,
   init: function () {
      self = this;
      self.myWorker = new
Worker("/Scripts/myWorker.js");                                                         //#Cooment B
      $("#testWorkers").live("click", 
         function () {
            self.myWorker.postMessage("Test");                                       //#Comment C
         }
      );
      self.myWorker.addEventListener("message",
         function (event) {
            alert(event.data);                                                                    //#Comment D
         }, 
      false);
   }
};
End Code main.js
Following the comment to code main.js
#Comment A -> Initializes our object using the regular jQuery ready function.
#Comment B -> Creates a new worker object and assign it as a local variable.
#Comment C -> Sends the worker a message whenever the test button is clicked.
#Comment D -> When the worker sends a message back to the host, notify the user.

In the worker object, we will show that the JavaScript begins executing as soon as the script is loaded and that it can begin immediately sending messages and responding to posts.

StartCode myWorker.js
count = 0;                                                                                         //#Comment A
init = function () {
   self.count++;                                                                                  //#Comment B
   self.postMessage("start count: " + count);                                       //#Comment C
}
self.addEventListener("message", function (event) {
   self.count++;                                                                                  //#Comment D
   setTimeout(function () {
      self.postMessage("Last Msg: " + event.data +  
         ", count: " + count);                                                                   //#Comment E
   }, 1000);
}, false);                                                                                           
init();                                                                                                 //#Comment F
End Code myWorker.js

Following the comment to code myWorker.js                                                                        
#Comment A Since we do not have access to window, we cannot assign variables to it by default. Variables here are scoped to the script file.
#Comment B Here, we update the count value to show that work has been done.
#Comment C Upon initialization, we can call the postMessage event proving that messages can be sent not in response to any host request.
#Comment D Update the count variable whenever a message is received.
#Comment E When a message is received, wait one second and respond with the message
sent and the current count value.
#Comment F At the end of the script, we call the init function to start performing work.

While the browser can certainly access the host system’s memory and processor resources, doing any heavy processing will often cause the screen to hang for a few moments. You may even encounter a browser message stating that it thinks you have a runaway process. The Web Worker specification solves this problem by allowing you to create a background worker that can do work on a different thread, thus freeing up the user interface thread to perform screen reflows and other more interactive logic.

Abstract Classes vs. Interfaces

The choice of whether to design your functionality as an interface or an abstract class can sometimes be a difficult one. Some people use abstract classes as a substitute for interfaces, but this is generally considered an anti-pattern.
Interfaces and abstract classes are different in that interfaces describe behavior, while abstract classes define partial implementations. Interfaces have the advantage that they can be implemented by any object which provides the necessary method, regardless of what classes that object inherits from. Abstract methods are typically used to provide a partial implementation.

Welcome

This blog is based on my past 18+ years of experience in software development industry. I have gone through different stages in my career starting from trainee software developer till senior management.
I do not want to keep my learnings to myself, so I had created this a small blog, I thought of revising it and adding few more learnings which may benefit many other software engineers and developers working in this lovely industry.
I'm not going to dictate any of the points, but all the practices listed here contributed a lot in my software development career, so if you think they make some sense for you then try to adopt few. If you have any +/- comments, kindly feel free to write me back