RSS
 

Archive for the ‘C#’ Category

Testing LINQ to SQL repositories with Rhino Mocks

13 Oct

Today I was writing some unit tests for a repository based on the Nerd Dinner example of a LNIQ to SQL class repository. I had a Customer table in the database that had a auto increment identification column. I needed to Mock the standard LINQ to SQL functionality where the newly assigned ID is set when the SubmitChanges method has been called and the row is committed to the database.

This is easy to do by Mocking my CustomerRepository interface and using Rhino Mocks Callback method.

Based on the Nerd Dinner example I have a customer repository interface below.

public interface ICustomerRepository
{
    IQueryable GetAllCustomers();
    Customer GetCustomr(int id);
    void Add(Customer customer);
    void Delete(Customer customer);
    void Save();
}

To Mock this interface I have used a generic class factory developed by a colleague of mine that can dispense a Mock object into my customer controller with ease.

public TestCustomerController()
{
    _customerRepository = _mock.StrictMock();
    //Set up the class factory to dispense the mock objects
    GenericClassFactory.Dispenser = o => _customerRepository;
    _controller = new CustomerIdentityController();
}

Inside my controller I use the generic class factory to dispense, by default, real object or, if the dispenser is set, my mock object. This is done using the code below.

ICustomerRepository _customerRepository = GenericClassFactory.Get()

Finally I wrote my test method using Rhino Mocks. The create customer method creates a new customer object and adds it using the LINQ to SQL add method. I use the Rhino Mocks call back method to get and instance of the new client that was created by my CustomerController. After the client is added the client controller and LINQ to SQL verifies that there are no errors, which allows me to commit the new record using my repositories save method. This method uses the Callback method to to mimic the LINQ to SQL functionality by assigning a customer ID to the to the customer object which is then returned by my controller.

[TestMethod]
public void CreateCustomer_ValidData_ID_Expected()
{
    Customer customer = null;
    _customerRepository.Expect(o => o.Add(Arg.Is.NotNull))
                       .Callback((Customer c) =>
                                      {
                                          customer = c;
                                          return true;
                                      });
    _customerRepository.Expect(o => o.Save())
                       .Callback(() =>
                                      {
                                          customer.ID = 1;
                                          return true;
                                      });
    _mock.ReplayAll();
    var customerId = _controller.CreateCustomer("FirstName", "Surname");
    Assert.AreEqual(1, customerId);
}

This is nothing new but is a great way of mocking a method that does more then just return a value.

 
Comments Off

Posted in C#

 

ASP.NET MVC Custom Helper – A HttpRequest extension method

31 Aug

Recently I ran into an issue using JQuery’s AJAX library and ASP.NET MVC. Refer to my last post about using JQuery’s AJAX with ASP.NET MVC.

After deploying a solution to my web server I had a major issue where my JQuery $.post method was not working and was not giving me any errors. I immediately thought that there was an error in my server settings or something other then my code because I had no issues in my development environment.

It turned out to be an issue with routing! In my development environment the application was installed under the root directory (‘\’) where as on my server it was installed under a subfolder of the root directory (For example: ‘\test\’) thus the value I coded inside my $.post method was incorrect when deployed to my server.

In order to make it easy for me to deploy to any environment without changing my JQuery method each time I created this simple extension method for the HttpRequest class.

public static class HttpRequestHelper
{
    public static string AppendServerPath(this HttpRequest request, string path)
    {
        return request.ApplicationPath.EndsWith("/")
                   ? request.ApplicationPath + path
                   : request.ApplicationPath + "/" + path;
    }
}

So now inside my JQuery method all I have to do is call this method and append the exact path I wish to invoke.\

$.post("<%=Request.AppendServerPath("Test/Controller/DoSomething") %>", null, doSomeThing());

This also worked well inside my Site.Master where I ran into similar issues linking images, style sheets, JavaScript files, etc.

Wherever there is a link in my code I now call this extension method and know it will deploy almost everywhere.

 
 

Dynamically Populate a Select/Drop Down List using ASP.NET MVC, JQuery and Json

22 Aug

It has been a while since my last blog due to me being flat out at work during the week and snowboarding on the weekends!

Today the weather is terrible up in the alps and I managed to catch the flu so it was a good time to catch up on some personal projects. I was working on an ASP.NET MVC website for my sister and decided to use AJAX to populate a select list based on a selection in another select list. The ASP.NET MVC framework and JQuery makes it very easy to use AJAX to do this.

This is nothing new but very powerful if you want to create a nice fluent forms user interface. For the most part the process was very easy. However I ran into an issue where JQuery was treating the Json returned from the server as a string instead of an object. Thus making if difficult to retrieve the data I wanted. I will explain how I got around this later in the post.

The first thing you need to do create the server side method. This is very easy using ASP.NET MVC! Of course you would probably get your data from a database of some sort, however this is just a nice way of showing how its done. The method below gets a list of Foo objects based on the FooId parameter using LINQ’s Where method.

public class Foo
{
    public int FooId { get; set; }
    public string Name { get; set; }
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetFooList(int FooId)
{
    var fooList = new List();
    fooList.Add(new Foo { FooId = 1, Name = "One" } );
    fooList.Add(new Foo { FooId = 1, Name = "Two" } );
    fooList.Add(new Foo { FooId = 2, Name = "Three" });
    fooList.Add(new Foo { FooId = 2, Name = "Four" });
    return Json(fooList.Where(foo => foo.FooId == FooId).ToList());
}

Now for the client side code. On my page I have two select lists. One is a list of Id’s and the other is a list of names. When a user selects an id from the first select list the second is populated with the names relating to that id. The lists can be created easily using using the ASP.NET MVC Helpers or writing the HTML yourself.

Finally the JQuery code in order to add the functionality to the page. JQuery makes it easy to execute server side methods and receive Json. The code below binds the AJAX post method to the change event of the IdList select list. The post function has three variables; The sever method to execute, the parameters to pass as Json and the function to execute with the data returned from the server. You can either execute a named or a anonymous function. I chose the latter because I am not doing too much inside the function.

 $(function() {
        $("#IdList").change(function() {
            $.getJSON("/Controller/GetFooList", { FooId: $("#IdList").val() },
            function(fooList) {
                $("#NameList").empty();
                $.each(fooList, function(i, foo) {
                    $("#NameList").append(""+ foo.Name+ "");
                });
            });
        });
    });

The biggest issue I came across was, originally, the FooList Json was being represented as a string therefore the JQuery each method was iterating through each character of the string rather then each object. After a bit reading I came across the JSON.parse method in the JQuery library. This method parses the string to Json which means that the JQuery each method functions as I expected.

There we have it. Like I said nothing new here but interesting never the less.

The only thing I don’t like about this code is the append method in my JQuery. Surly there is a better way of adding options to a select element?

UPDATE 120/01/2015:  I have recently realised that using eval is bad! This is because it will evaluate ANY javascript returned from the server. Therefore there is a chance that someone with malicious intent could insert their own javascript into your request. So instead you should use jQuery’s getJSON method instead. The above code has been modified to use this function.

 
Comments Off

Posted in C#, JQuery