I will be breaking down the post in to two sections.
First I will mention how to accomplish above mentioned task using handlers and I will then go on and discuss the underlying concepts and basic theories for the beginners in the next section.


How to get it done!!!


What are the core parts we will need to perform a cross domain request using JavaScript?

  •     A Mechanism to call the URL that sends data to the calling page.
  •     A padded JSON object (or a JSONP object)
    •    If the calling URL don’t support cross domain calls, functionality to wrap or pad the returned JSON object with a call back function.
  •    A method to handle the call back.
OK! Let’s take this one step at a time.
In this example I will be using JQuery AJAX facilities to call the URL in the other domain.


jQuery.ajax
({
url: "http://www.crosseddomain.com/testPage.html,
dataType: "jsonp",
type: "GET",
cache: true,
jsonpCallback: 'handleResponse'
});

jsonpCallback option allows us to specify the call back method which will handle the returned data upon the response is received.
We specify cache as true to avoid the random time stamp value JQuery appends on the request.
dataType is set to jsonp so the call back function will be added to the request.
When the entire configuration is done correctly the page will send a request like http://www.crosseddomain.com/testPage.html&callback=handleResponse through the network.
Now all we have to do is write a function to handle the returned value, the function name should be the value we passed for the jsonpCallback option
function handleResponse(response) {
//your custom logic goes here
}

That will work only if the testPage.html wraps the response with the call back. Or in other words if the requested page is responsible for making the request cross domain compatible by converting the JSON object in to a JSONP object by adding the call back function around it.
What shall we do when we are given a URL that does not support cross domain script calls? How to make it JSONP compatible?


Normal JSON objects will not work across cross domains because of the same origin policy, which restricts browser side programming languages from accessing scripts in another site or a domain. (I will talk about these theory parts in detail on my next blog, so stay tuned).
So obviously it does not restrict server side programming languages like C# from accessing URLs in separate domains. 


Keeping that in mind, we can send the request for the URL from server side, after receiving the normal response we can wrap it with the call back function and we can send it to the page where the call originated from.


To get this done we will use a generic web handler or an ashx file.


For demonstration purposes, the handler will be expecting some string data from the requesting page and it will send a dummy JSON object that contains user inputted data with some custom data from the server side. (To make things simple I will not add the code to do an actual web request, rather I will just hard code the JSON string).


I will add a text box to the page and will get the user input in each key press. After a response is received the call back function will display retrieved data in a label.


The HTML markup will be 

    <div>
        Enter your text : <input type="text" id="suggest" name="Suggestion" />
    div>
    <label id="results">
    label>

And the JQuery request will look something like this.

         $(document).ready(function () {
            $("#suggest").keyup(function () {           
                var data = $("#suggest").val();
                jQuery.ajax({
                    url: "http://localhost:18395/RequestHandler.ashx?data=" + data,
                    dataType: "jsonp",
                    type: "GET",
                    cache: true,
                    jsonpCallback: 'handleResponse'
                });

            });
        });

The RequestHandler.ashx file code is mentioned below.

    public class RequestHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var data = context.Request.QueryString["data"];
            var callback = context.Request.QueryString["callback"];
            var response = context.Response;
            response.Clear();
            response.ContentType = "application/json";
            var sampleJson = "{\"firstName\":\"Dhanushka\",\"lastName\":\"Athukorala\",\"dataReceived\":\"" + data + "\"}";
            var paddedResponse = string.Format("{0}({1})", callback, sampleJson);
            response.Write(paddedResponse);
            response.Flush();
        }
       
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

So let’s see what’s happening in the code behind file.
  • We retrieve data passed from the user from the query string (data variable)
  • Call back function name is also retrieved from the query string (callback variable)
  • A JSON object is created (this is the line where you have to call a URL and get data, you can use the functionalities implemented in HttpWebRequest, HttpWebResponse to accomplish this)
  • We wrap the final JSON object with the call back function so it will be in the format callback(JSON) making it a JSONP object (paddedResponse variable) 
  • The JSONP object is written to the response making it available for the calling page.
Now when the response is flushed it will return back to the calling page. Here the script tag of that page will execute received data or the JSONP object, or in other words it will call the call back method with a JSON object.

The code for our call back method is mentioned below.

        function handleResponse(response) {
            var data = eval(response);
            var firstName = data.firstName;
            var lastName = data.lastName;
            var sentData = data.dataReceived;
            $("#results").html("First Name : " + firstName + "
Last Name : "
+ lastName + "
Sent Data : "
+ sentData);
        }

This call back method will process the returned JSON string and will print the containing information in the results label

So in a nut shell the codes we need are

Script tag and the HTML

Handler code

And the out put will be 

Hope it helps.

I will explain the underlying principals of cross domain communication with scripts in the second part of this blog.

Cheers!!


I got my blogger hat on after a very long time. With all the week end lectures and office works cramping up my schedule, there was virtually no time left for me to blog about anything. I came across pretty interesting topics and subjects over my past few non blogging months and will try to share them with you in the coming days.
Ok let’s get started…

Let’s say we are writing a SQL query to retrieve the names of the customers who are above 20, we will write something like this

select cust.name
from customers cust
where cust.age>20

But when it comes to LINQ, as we all know the syntax is totally inverted.
The same query will look like this when we do it on a list of Customer objects.

IEnumerable<string> olderCustomersQuery = from cust in customers
                                          where cust.Age > 20
                                          select cust.Name;


But WHY!!!

To understand we need to get back to basics.

There are two ways to build up a LINQ expression, Extension methods and Query operators. The one mentioned above falls in to the latter part.
Let’s see how to write the same example using extension methods.

IEnumerable<string> olderCustomersExtension = customers
                                              .Where(cust => cust.Age > 20)
                                              .Select(cust => cust.Name);


All these extension methods are available on any class that implements the generic IQueryable or IEnumerable<T> interfaces.


So what’s up with the ordering of the method calls, why do we need to call the “Where” extension method before calling “Select”.

The answer is simple.

Where filters data that are returned from a data source.
While Select narrows down the information that shown in the final projection by specifying which properties to retrieve.

So when I say customers.Select(cust => cust.Name) it just gives me a list of strings so customers.Select(cust => cust.Name).Where(cust => cust.Age > 20) will not be possible because now the Where clause don’t get a customer object to query on.


Because of that when we are writing LINQ expressions we should use the extension methods in the correct order, otherwise you may get unexpected query results or compilation errors.

Although the LINQ extension methods and types that are defined in System.Linq namespace are very powerful, the syntax can be quite cumbersome, and it is easy to introduce subtle errors that are difficult to spot and correct. 
To avoid these drawbacks designers of C# have provided an alternative approach to the use of LINQ, through a series of LINQ query operators that are part of the C# language.

There is an equivalent query operator for each LINQ extension method.

Because these query operators are built to compliment the functionality of the equalant extension methods. They should also follow the above mentioned practices and rules to avoid any kind of side effects on the data that will be retrieved by the LINQ expression.

Hope this clears things up!!


We all know that data manipulation using tables have been made very easy by LINQ to SQL right! For an example a sample data retrieval and update query using LINQ will look something like this.

I'll just note down the steps involved so rookies will have an idea of what I'm talking about

  1. Add a new LINQ to SQL class file (.dbml) to your project
  2. Then drag and drop a table you want to query using the server explorer of VS (lets name the new file as Demo.dbml)
Here is some sample code to get you started with

var context = new DemoDataContext(); //get the data context you want to query
//retreive data from the table
var records = from tableTest in dc.DemoTable
              where tableTest.condition == -1
              select tableTest;


Now let's play with them a bit

foreach (var record in records){
  try

   {
    var rowInfo = context.DemoTable.Single(ob => ob.Id == rec.Id);
    var someValue=GetValue();
    rowInfo.condition = someValue > 0 ? 1 : 0; //Change a value of a property
    context.SubmitChanges();//Save the changed data to the table
   }
  catch (Exception ex)

  {
    Console.WriteLine(ex.Message);
    continue;

  }
}

That's really straight forward right! We can use the same set of steps to manipulate data using SQL Views. But there seems to be some sort of a bug in VS2010 when using LINQ to SQL class files. When we drag and drop a table to a dbml file the primary key of the table is identified and is set correctly. But if we use a VIEW that incorporates a set of tables using UNIONS this does not happen. Making it impossible to save or update data in the underlying table because of the missing primary key. You will run the same code for a view but no data will get saved.
 To avoid such a bizarre situation you need to manually set the primary key of the view using properties. To do that select the view that you needs to work on and in its attributes set click on its primary key column and go to its properties. And set the Primary Key property to true.

Now you will be able to work with your views without any problems.

I came across a very useful plug-in few days back for drawing Gantt charts using JQuery. You can find all the information plus the files you need to download from here (https://github.com/thegrubbsian/jquery.ganttView).

As I described previously from a blog when we drew JQuery charts, we can use the power of JSON to get serialized data from the server side to populate the needed data model. In this case the the data model looked something like this.

var ganttData =
[
    {
        id: 1, name: "Feature 1"
        series: 
        [
            { name: "Planned", start: new Date(2010,00,01), end: new Date(2010,00,03) },
            { name: "Actual", start: new Date(2010,00,02), end: new Date(2010,00,05) }
        ]
    },
    {
        id: 2, name: "Feature 2" 

        series: 
        [
            { name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
            { name: "Actual", start: new Date(2010,00,06), end: new Date(2010,00,17) },
            { name: "Projected", start: new Date(2010,00,06), end: new Date(2010,00,17) }
        ]
    }
]

 
In order to tackle this, my server side data model should look something like this.

public class ContainerModel

{
   public String id { get; set; }
   public String name { get; set; }
   public List<DataModel> series { get; set; }

}
public class DataModel
{
   public string name { get; set; }
   public DateTime start { get; set; }
   public DateTime end { get; set; }

}
 

Let's write a sample method to populate the data model with some dummy data.

public static List<ContainerModel> PopulateData(){
  var startDate = new DateTime(2010, 5, 12);
  var endDate = new DateTime(2010, 12, 5);


  var planned = new DataModel { name = "Planned", start = startDate, end = endDate };
  var actual = new DataModel { name = "Actual", start = startDate, end = endDate };
  var projected = new DataModel { name = "Projected", start = startDate, end = endDate };


  var dataSet = new List<ContainerModel>();
  for (int k = 0; k < 10; k++)
{
    var container = new ContainerModel
{
                          id = k.ToString(),
                          name = string.Format("Feature {0}", k),
                          series = new List<DataModel> { planned, actual, projected }
                        };
    dataSet.Add(container); 

  }
  return dataSet;

}

And these methods were used to serialize the data model to JSON so we can use it from the JavaScript side.

private static  string ToJson(this object obj){
  var serializer = new DataContractJsonSerializer(obj.GetType());
  var ms = new MemoryStream();

  serializer.WriteObject(ms, obj);
  var json = Encoding.Default.GetString(ms.ToArray());
  return json;

}

public static string GetJason(List<ContainerModel> dataModel)
{
  return dataModel.ToJson();

}


Let's write a web method so we can use a JQuery AJAX call back to retrieve the prepared data.
I have embedded the above mentioned PopulateData, ToJson, GetJason methods in to a Helper class for more code clarity

[WebMethod]
public static string GetData()
{
  var modelData = Helper.PopulateData();
  var jsonData = Helper.GetJason(modelData);
  return jsonData;

}

Now all our server side codes are completed, but then come the fun part. As you can see in the above mentioned data model the dates are represented as JavaScript Date objects
{ name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
But date returned by Json is a string that looks something like this "/Date(1273602600000+0530)/" .
In order to convert that JSON serialized millisecond date string to a JavaScript Date object, we can use JavaScript substring function with eval
startDate = eval("new " + start.substring(1, start.length - 7) + ")");
Resulting in returning a JavaScript Date object with a value like
"Wed May 12 2010 00:00:00 GMT+0530 (Sri Lanka Standard Time)"

So let's replace the DateUtils Class in the jQuery.ganttView.js with this one

var DateUtils = {
  daysBetweenBothString: function (start, end){
    var startDate, endDate;

    startDate = eval("new " + start.substring(1, start.length - 7) + ")");
    endDate = eval("new " + end.substring(1, end.length - 7) + ")");
    var count = 0, date = startDate.clone();
    while (date.compareTo(endDate) == -1) { count = count + 1; date.addDays(1); }
    return count;

  },
  daysBetweenEndString: function (start, end){
   endDate = eval("new " + end.substring(1, end.length - 7) + ")");
    var count = 0, date = start.clone();
    while (date.compareTo(endDate) == -1) { count = count + 1; date.addDays(1); }
    return count;

  },
  daysBetween: function (start, end){
    var count = 0, date = start.clone();
    while (date.compareTo(end) == -1) { count = count + 1; date.addDays(1); }
    return count;

  },
  isWeekend: function (date){
    return date.getDay() % 6 == 0;

  }
};

And the addBlocks method with this

addBlocks: function (div, data, cellWidth, start){
  var rows = jQuery("div.ganttview-blocks div.ganttview-block-container", div);
  var rowIdx = 0;
  for (var i = 0; i < data.length; i++) {
   for (var j = 0; j < data[i].series.length; j++) {
   var size = DateUtils.daysBetweenBothString(data[i].series[j].start, data[i].series[j].end);
   var offset = DateUtils.daysBetweenEndString(start, data[i].series[j].start);
   var blockDiv = jQuery("<div>", {
     "class": "ganttview-block",
     "title": data[i].series[j].name + ", " + size + " days",
     "css": {
     "width": ((size * cellWidth) - 9) + "px",
     "margin-left": ((offset * cellWidth) + 3) + "px"

    }});
  if (data[i].series[j].color){

   blockDiv.css("background-color", data[i].series[j].color);
  }
  blockDiv.append($("<div>", { "class": "ganttview-block-text" }).text(size));
  jQuery(rows[rowIdx]).append(blockDiv);
  rowIdx = rowIdx + 1;
  }
  }
}

Now you can use this modified version of the JS file to support your JSON serialized data object.
In the aspx page (in this case Default.aspx ) where we need to draw the chart insert the following script

<script type="text/javascript">
$(document).ready(function (){
var ganttData = [];

$("#btnGetData").live("click", function (e){
  var button = $(this);

  function onDataReceived(series){

    ganttData = series.d;
    $("#ganttChart").ganttView({
    data: $.parseJSON(ganttData),
    start: new Date(2010, 05, 01),
    end: new Date(2010, 12, 31),
    slideWidth: 900
   });
  }
  var dataUrl = "Default.aspx/GetData";

  $.ajax({
   type: "POST",
   url: dataUrl,
   data: "{}",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: onDataReceived
  });
  });
});
</script>

And add the following div tag to the page so the JS file can inject the rendered Chart inside it
<div id="ganttChart"></div>
Accompanied with the button to trigger the AJAX call back
<div><input id="btnGetData" type="button" value="Get Data" /></div>

Now you are all set for your first JQuery Gantt Chart.




 

I came across a pretty interesting series of articles when I was reading through Eric Lippert's MSDN blog today. Here are some of the things i grasped from him.

What is the first thing that comes to your mind when someone asks from you "What is the difference between value types and reference types?" Well I bet you will reply saying that value types are allocated in the stack and reference types are allocated in heap, right! Well you are correct that's what the C# documentation tells us. Then why don't we just call them stack types and heap types instead of value and reference. Well that's because that is not true most of the time.

Let's take the following class as an example.

public class Demo
{
   private int ValueOne = 10;

   public int GetValue()

   {
    return ValueOne;

   }
}


Here the variable "ValueOne" is defined inside the "Demo" class. Here although "ValueOne" is a value type integer variable it is an integral part of the "Demo" s instance memory. So it is allocated inside the heap.

Let's have a look at how this happens.

Before we dwell in to it, let's see what does the terms "short lived" and "long lived" stands for in context of variables

When a method is called an activation period is defined for that method, which can be defined as the time between the start of the method execution and its successful return or a throwing of an exception. Code in the method may require allocation of storage in memory for its variables. Let's look at a simple example

public int GetSum()
{
   int x = 10;
   int y = 20;


   int sum = Add(x, y);


   return sum;

}

public int Add(int i, int j)

{
   return i + j;

}



Here when the method GetSum calls method Add, the use of the storage locations for the parameters passed to Add and the value returned by Add is required by GetSum. This means that the required life time of the storage location is actually longer than the activation period of the method, thus making it a long lived variable or storage.

So what does long/short lived stands for "If the required life time of a variable/storage is longer than its current method execution's activation period that variable is classified as a long lived variable otherwise a short lived one"

So how can value type variables get allocated inside the heap? Let's get to it one step at a time

  • There are three types of values in C#. Instances of value types, Instances of reference types and References.
  • There are storage locations in memory that can store values they are stack, heap and registers.
  • Every value that is managed by some kind of a program stores their values in these storage locations, as well as every reference other than a null reference.
  • Every storage location in memory which has some content in them has a life time.(short/long lived)
  • Long lived storage locations are always heap locations and short lived storage locations are always in stack or registers.
  • If the compiler cannot come to a clear decision if the variable is short lived or long lived that variable is considered as a long lived variable and is always stored in heap.
What happens is that during the compile time analysis if a local or a temporary variable is found to be un-used after the methods activation time it is stored on stack or register otherwise on heap. Depending on this model we can see that references and instances of value types are the same as far as their storage is concerned, but they can go on to either of those above mentioned storage locations depending on their life time.

So that leaves us with an explanation that actually does not explain any concrete thing.

Then what is the main, clearly distinctive difference between them. The best explanation is that "Value types are always copied by value and Reference types are always copied by reference" and we can also go on to say that "Value types semantically represents a value and Reference types are a semantic reference to something".

Yesterday I came across an interesting situation. There are some times when you need to break a string in to two parts depending on their character type.
Lets say you have a string like "Welfare Fund - 1000.00" and you need to break the string part and the number part in to two different strings. Well the first thing that comes to mind is iterate the string till you get a number and break it to apart upon hitting on a number type character, right!!
Well then what about a string like "Welfare Fund : 2009 - 3000.00"
Here as you can see, there are numbers in the string part as well.

The solution is simple, all you have to do is iterate through the string by starting from its end, till you reach a blank space. Here is the a method to accomplish that task

public static List<string> BreakString(string stringToBreak)
        {
            var charArr = stringToBreak.ToCharArray();
            var stringAppender = new StringBuilder();
            var intAppender = new StringBuilder();
            var isSeparated = false;
            for (int i = charArr.Length - 1; i > -1; i--)
            {
                if (isSeparated)
                    stringAppender.Append(charArr[i]);
                else
                {
                    isSeparated = charArr[i] == ' ';
                    if (!isSeparated)
                        intAppender.Append(charArr[i]);
                }
            }
            var returnValues = new List<string> { ReverseString(stringAppender.ToString()), ReverseString(intAppender.ToString()) };
            return returnValues;
        }

public static string ReverseString(string s)
        {
            var arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

You can call it as follows

var input = "Welfare Fund - 1000.00";
var result = BreakString(input);

There are some pretty good Mock object frameworks available out there for .net like NMock, EasyMock, TypeMock, etc... But I think every one will ultimately wind up using Rhino Mock at the end because of its easy to grasp rich feature set. So lets see how we can use Rhino to to mock a layered architecture for unit testing purposes.

I will try to mock the repository and the service layer in the following code in an easy to understand manner

Here are my sample repository and service interfaces (I have used NHibernate and Windsor Castle in this project as the ORM solutionl)

Repository Interface

 public interface IInventoryRepository : IRepository
    {
        List<RecordItem> Get(List<int> ids);
        List<RecordItem> Get(List<int> ids, string orderByColumn, string orderType);
    }


Service Interface

public interface IInventoryService  
    {
        List<ServiceItem> Get(List<int> ids, int truncLength);
        List<ServiceItem> Get(List<int> ids, string orderByColumn, string orderType, int truncLength);
    }

As I have described in my previous post lest use Nbuilder to mock the test objects that needs to be returned when the methods in the repository are called

Mock return for List<RecordItem> Get(List<int> ids)
private static List<RecordItem> CreateRecordItems()
        {
            var items = Builder<RecordItem>.CreateListOfSize(10).WhereAll().Have(x => x.Title = "sample title").WhereAll().Have(x => x.AuthorName = "Dhanushka").Build().ToList();
            for (int i = 1; i < items.Count + 1; i++)
            {
                EntityIdSetter.SetIdOf(items[i - 1], i);
            }
            return items;
        }

Mock return for List<RecordItem> Get(List<int> ids, string orderByColumn, string orderType)
 private static List<RecordItem> CreateRecordItemsDesc()
        {
            var items = Builder<RecordItem>.CreateListOfSize(10).WhereAll().Have(x => x.Title = "sample title").WhereAll().Have(x => x.AuthorName = "Dhanushka").Build().ToList();
            var j = items.Count;
            for (int i = 1; i < items.Count + 1; i++)
            {
                EntityIdSetter.SetIdOf(items[i - 1], j);
                j--;
            }
            return items;
        }

Now lets use Rhino Mock to mock the Method Calls to the repository

public static IInventoryRepository CreateMockInventoryRepository()
        {
            var mocks = new MockRepository();
//specify the repository to mock
            var mockedRepository = mocks.StrictMock<IInventoryRepository>();


//specify what to return when a specific method is called in the mocked repository
            Expect.Call(mockedRepository.Stub(x => x.Get(Arg<List<int>>.Is.Anything)).Return(CreateRecordItems()));
            Expect.Call(mockedRepository.Stub(x => x.Get(Arg<List<int>>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Equal("asc"))).Return(CreateRecordItems()));
            Expect.Call(mockedRepository.Stub(x =>x.Get(Arg<List<int>>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Equal("desc"))).Return(CreateRecordItemsDesc()));

//mock the current data base context
            var mockedDbContext = mocks.StrictMock<IDbContext>();
            Expect.Call(mockedDbContext.CommitChanges);
            SetupResult.For(mockedRepository.DbContext).Return(mockedDbContext);

            mocks.Replay(mockedRepository);

            return mockedRepository;
        }

As you can see this method mocks the repository with specification for method calls return values and reveal the mocked repository to the outer world.

Now lets used this mocked repository to mock the service layer


public static IInventoryService   CreateMockClipboardService()
        {
            var serviceMock =new InventoryService(InventoryRepositoryMock.CreateMockInventoryRepository());
            return serviceMock;
        }

Here the dependency injection is used with Windsor Castle to inject the service with the mocked repository layer.

Now to write a sample test using NUnit all you have to do is
[TestFixture]
    public class ServiceTest
    {
        private IInventoryService  _service;

        [SetUp]
        public void SetUp()
        {
            _service = new InventoryService(InventoryRepositoryMock.CreateMockInventoryRepository());
        }

        [Test]
        public void GetWithoutSortTest()
        {
            var idList = new List<int> {1, 2, 3, 4};
            const int truncLength = 100;
            var itemsReturned = _service.Get(idList, truncLength);

            var expectedItemType = typeof (ServiceItem);
            const string expectedAuthor = "Dhanushka";
            const string expectedTitle = "sample title";

            Assert.That(itemsReturned.Count, Is.GreaterThan(0),"no items returned");
            Assert.That(itemsReturned[0], Is.TypeOf(expectedItemType),"incorrect return type");
            Assert.That(itemsReturned[0].Author,Is.EqualTo(expectedAuthor),"unexpected author returned");
            Assert.That(itemsReturned[0].Title,Is.EqualTo(expectedTitle),"unexpected title returned");

        }
   }

Now we have a simple unit test in our hand that uses a mocked service and repository layer

Most of us use some sort of a mocking library when doing unit tests in order to mock our service and repository layers right!
Well I am a big fan of Rhino Mock and I have used it in almost all of my testing projects.
But one thing that remains to be a pain in the ass is creating test objects to be returned when the mocked repository is called. Well not any more!!!

Using NBulder we can avoid hard coding test objects for mocking purposes.

Here are some sample codes to get you started with

Let's say you want to mock a a repository call that returns an item, just write
var item = Builder<RepositoyType>.CreateNew().Build();
//set the id property of each items (Nhibernate is used with Windsor Castle in this occasion)
EntityIdSetter.SetIdOf(item, 1);

To mock a method call that returns a list of record objects.
var items = Builder<RepositoyType>.CreateListOfSize(10).WhereAll().Have(x => x.Title = "sample title").WhereAll().Have(x => x.AuthorName = "Dhanushka").Build().ToList();
 for (int i = 1; i < items.Count + 1; i++)
{
    EntityIdSetter.SetIdOf(items[i - 1], i);
}

As you can see from the above example we can even set specific values for the attributes for returned objects as well.

And there are many more helper functions you can use to accomplish almost all the test object creation needs you hope for.

Happy Coding!!

I came across an interesting issue today. I used the ResetPassword method provided by C# membership class to reset the password of a user and found out that although it allows us to define the password strength using a regular expression in the web.config file, it does not guarantee that the generated password adheres to the rules defined by the expression. Microsoft says and I quote
"The random password created by the ResetPassword method is not guaranteed to pass the regular expression in the PasswordStrengthRegularExpression property. However, the random password will meet the criteria established by the MinRequiredPasswordLength and MinRequiredNonAlphanumericCharacters properties."

So to tackle the issue, I used the Regex class. The revised code is shown below

var isNotMatch = true;
                    while(isNotMatch)
                    {
                        resetpwd = manager.ResetPassword();
                        var matcher=new Regex(Membership.PasswordStrengthRegularExpression);
                        isNotMatch = !(matcher.IsMatch(resetpwd));
                    }
This code snippet will force the ResetPassword to fire until a password adhering to the rules defined by the regular expression is generated.

I came across an interesting problem when using java script "setSttribute" method with IE. Apparently it does not work with IE versions 5.5 to 7 when we try to use it to set a style to an element.

For all the browsers including IE8 and above this code will work fine when we a want to set a a style attribute to an element using java script.

var elemntToTest=document.createElement('a');
elemntToTest.setAttribute('href', '#');
elemntToTest.setAttribute('style', 'padding:3px');

but in IE 5.5-7 you will need to set the style like this.

elemntToTest.style.cssText = "padding:3px;";

Now it will work fine in all the browsers.

Hope this work around helps!!!