Un-Installing Ghost Doc

While this might be so obvious to many of you, I found it quite difficult to un-install an older version of Ghost Doc. Don’t get me wrong I care about this as this is one of my favourite tools.

Simply navigate to
C:\Program Files (x86)\SubMain\GhostDoc\
and run
(may be you would not need to navigate to this folder – have not tried yet..)

msiexec /x {134A5765-D59B-4160-8C70-B84BF9F53DF9}

Debugging, Visualizing and Querying data using LINQ

One of the challenging things that I have confronted in my day-to-day work is writing complex LINQ queries. I’m sure there are lot of developers out there who have experienced the same when writing complex LINQ queries. This is a simple article to assist for those developers to debug, visualize and query using LINQ to SQL.

Those who new to LINQ to SQL, it is a database development model in the context of an Object Oriented Programming Model. LINQ is a broad topic. If you need to know more about LINQ, there lots of great articles in the web including some excellent sources from MSDN. .NET Framework 4.0 has also made significant enhancements to its LINQ model. This includes improvements to areas such as performances, query stabality, usability, LINQ to SQL class designer and much more. You can find some of those improvement in here.

LINQ to SQL translates the queries you write into parameterized SQL queries (in text form) and send them to the SQL server for processing. Sometimes debugging LINQ queries can be problematic. If you want to know more about debugging LINQ queries please refer to this article.

There are other ways to output LINQ to SQL queries so you can see the entire query that get executed. For example you can output to a debug window, file, or to a memory. Some examples are described in the below articles.

LINQ to SQL log to debug window.

View LINQ to SQL..

VS2010 has a Historical Debugger  which can also be used to view and debug LINQ queries. More info is here.

 

Debug Visualisers

LINQ to SQL Debug Visualiser enables you to view and execute the LINQ queries on the fly. It was a part of beta releases of VS2008, but for some reason MS has dropped it from the RTM release. I cannot see this is integrated into VS2010 either. It is a separate download. You can download it from here.

Take a look at this article on LINQ to SQL Debug Visualizer, which explains how it is integrated and used within Visual Studio. VS LINQ to SQL Debug Visualizer has its own limitations to it. For example it does not diplay the complete query. It is hard to edit and execute while debugging. This article discribe some of limitations.

There is another similar tool that you can download from VS Gallary. This tool should work with any database as well as MS SQL. You can find more information here.

 

LINQPad 

I think this is an excellent tool to write and test your LINQ queries. It is a great tool to help you build any type of queries with LINQ. Standard edition is free and I recon every developer should have it. You save lot of time by having these tools which allows you to be more productive when writng queries

LINQ

You can also connect to a SQL Server DB (Express or Compact Edition) and with a connection to your LINQ Data component (if you have built one) you can perform queries right against your data with LINQ – that’s excellent!  The standard edition is free to download and it supports .NET 4.0 as well. Standard edition does not have the Autocompletion feature.  For more information on Autocompletion please click here.

There is also great webcast that explains the new features of LINQPad with respect to the Entity framework.

More importantly it is a great tool to learn and improve your skills on LINQ to SQL. You can download this tool from here.

Getting Started with T4MVC

This post is about T4MVC and how you would use it within your MVC application. T4MVC is a great way to generate strongly typed helpers so you can eliminate the use of literal strings when referring to Actions, Controller, and Views within your MVC application.

How to install T4MVC?

You have 2 options.

a.    Download from MvcContrib CodePlex project.http://mvccontrib.codeplex.com/releases/view/41582

b.    Use NuGet

http://nuget.codeplex.com/wikipage?title=Getting%20Started

 

NuGet Approach      

Open VS2010. Tools,  Library Package Manager, and Package Manager Console. Execute the following command.

PM> install-package T4MVC

This should install 2 files under your app’s root folder.

T4MVC.tt and T4MVC.tt.settings.t4 – These files contain necessary entries which allow you to use T4 strongly typed helpers.

 

Once you install T4MVC, you might also notice couple errors appeared in the Error List window. (Please see below)  image

As you see, there are no auto generated files being added to the solution yet. You would continue to get these errors if you decided to build the solution.

To remove these errors, you need to run Custom Tool on the T4MVC.tt file. (Right click on the file and select “Run Custom Tool”).Now you should be able to see additional auto generated files added to the solution.

 

T4MVC in Action

Below are few examples of the usage of T4MVC.

image (1)

 

As you see T4MVC generates the strings accordingly.

Where to find more information?

T4MVC templates are part of MVCContrib project and developed by David Ebbo. If you would like to know more information please visit the link below.

http://mvccontrib.codeplex.com/wikipage?title=T4MVC_doc&referringTitle=T4MVC

Glimpse

Few years back, Phil Haack introduced a Routing Debugger. You might have also seen this niceMvc Route Debugger Visualizer.

What I’m about to show you is a really cool tool, which allows you to debug ASP.NET MVC applications. It is called Glimpse. Glimpse includes not only route debugging support but also many other features. As you know Firebug is a debugging tool for client, and Glimpse does it for the server. Glimpse only works with the version MVC3. It can support MVC2, however you need to have MVC3 installed. It should support ASP.NET Web Forms as well but the current release (beta version) has dependencies to MVC.  I haven’t tried the Glimpse Web Forms debugging yet, but it is supported.

NuGet:

PM> Install-Package Glimpse

glimpse

 

 

 

 

 

 

 

You can configure Glimpse by navigating to

http://localhost:/Glimpse/config

Below is how you see Glimpse while debugging information.

glimpse2

You can debug : Application settings, routes, session variables, trace data.

If it is an Ajax request, then the server embeds the JSON in the content of the page. And many more…

You can see a nice video and more information here.

So if you haven’t started using this, I suggest you download it, as it will definitely assist your development work!

Simple test helper – MVC Action has decorated with a certain attribute

Below is a useful helper, which allows you to verify whether an Action is decorated with a certain attribute. This is very simple to implement, but you can use something like below.
Test helper:

public static class ActionAttributeTestHelper
{
	public static bool DoesMethodActionContainAttribute<TController, TActionResult, TAttribute>(Expression<Func<TController, TActionResult>> mExpression)
	{
		Expression<Func<TController, TActionResult>> methodExp = mExpression;
		var methodCall = (MethodCallExpression)methodExp.Body;
		var methodInfo = methodCall.Method;
		return methodInfo.GetCustomAttributes(false).Any(a => a is TAttribute);
	}
}



public class SutController : Controller
{
	[Authorize]
	public ActionResult ActionWithAttributeNoParameter()
	{
	   return View();
	}

	public ActionResult ActionWithNoAttribute()
	{
	   return View();
	}

	[Authorize]
	public ActionResult ActionWithAttributeWithParamter(int i)
	{
	   return View();
	}

	[Authorize]
	[HttpGet]
	[OutputCache]
	public ActionResult ActionWithMultipleAttributes()
	{
	   return View();
	}
}

Unit Tests:

public class SutControllerTest
{
	[TestMethod]
	public void ActionWithAttributeNoParameter_ReturnsTrue()
	{
		// Arrange
		var sut = new SutController();

		//Act
		var doesTheMethodContainAttribute = ActionAttributeTestHelper.DoesMethodActionContainAttribute<SutController, ActionResult, AuthorizeAttribute>((x) => sut.ActionWithAttributeNoParameter());

		//Assert
		Assert.IsTrue(doesTheMethodContainAttribute);
	}

	[TestMethod]
	public void ActionWithNoAttribute_ReturnsFalse()
	{
		// Arrange
		var sut = new SutController();

		//Act
		var doesTheMethodContainAttribute = ActionAttributeTestHelper.DoesMethodActionContainAttribute<SutController, ActionResult, AuthorizeAttribute>((x) => sut.ActionWithNoAttribute());

		//Assert
		Assert.IsFalse(doesTheMethodContainAttribute);
	}

	[TestMethod]
	public void ActionWithAttributeWithParamter_ReturnsTrue()
	{
		// Arrange
		int anyNumber = 7;
		var sut = new SutController();

		//Act
		var doesTheMethodContainAttribute = ActionAttributeTestHelper.DoesMethodActionContainAttribute<SutController, ActionResult, AuthorizeAttribute>((x) => sut.ActionWithAttributeWithParamter(anyNumber));

		//Assert
		Assert.IsTrue(doesTheMethodContainAttribute);
	}

	[TestMethod]
	public void ActionWithMultipleAttributes_ReturnsTrue()
	{
		// Arrange
		var sut = new SutController();

		//Act
		var doesTheMethodContainAuthAttribute = ActionAttributeTestHelper.DoesMethodActionContainAttribute<SutController, ActionResult, AuthorizeAttribute>((x) => sut.ActionWithMultipleAttributes());

		var doesTheMethodContainHttpGetAttribute = ActionAttributeTestHelper.DoesMethodActionContainAttribute<SutController, ActionResult, HttpGetAttribute>((x) => sut.ActionWithMultipleAttributes());

		var doesTheMethodContainOutputCacheAttribute = ActionAttributeTestHelper.DoesMethodActionContainAttribute<SutController, ActionResult, OutputCacheAttribute>((x) => sut.ActionWithMultipleAttributes());

		//Assert
		Assert.IsTrue(doesTheMethodContainAuthAttribute);
		Assert.IsTrue(doesTheMethodContainHttpGetAttribute);
		Assert.IsTrue(doesTheMethodContainOutputCacheAttribute);
	}
}

Setup on the same method using MOQ

Someone asked me about this today and I thought of it is a useful tip to write a small post. See the below code. If you know how to setup the same method in such a way that it would not override during the test execution, you can stop reading the rest of the post. If not please see the below example.

    public class SomeClass
    {
        private readonly ISomeInterface _someInterface;

        public SomeClass(ISomeInterface someInterface){
            _someInterface = someInterface;
        }

        public string SomeMethod()
        {
            string str1 = "str1";
            string str2 = "str2";
            
           var r1 = _someInterface.DoSomething(str1, str2);
            var r2 = _someInterface.DoSomething(string.Empty, string.Empty);
            
            return "something";
        }
    }

Notice that the same method call twice with different parameters. In our Unit Test, if we were to stub these two methods, the second/last setup method overrides the first one. In other words both r1 and r2 has the value of “bar”. This is not what we expect as we want setup methods to behave differently and return different values for r1 and r2.

Couple of ways you can achieve this with Moq.

a. Using It.Is

You can specify a predicate that matches a specified criteria.

[TestMethod]
public void TestMethod3()
{
       var stub = new Mock<ISomeInterface>();
        stub.Setup(x => x.DoSomething(It.Is<string>
                     (s => !string.IsNullOrEmpty(s)), It.Is<string>
                     (s => !string.IsNullOrEmpty(s)))).Returns("foo");
        stub.Setup(x => x.DoSomething(It.Is<string>
                     (s => string.IsNullOrEmpty(s)), It.Is<string>
                     (s => string.IsNullOrEmpty(s)))).Returns("bar");
            
        var sut = new SomeClass(stub.Object);
        var r = sut.SomeMethod();
     }

b. This is the one that I like most as it only needs one setup and slightly quicker
Provide the delegate on the “Returns” that match the criteria.

[TestMethod]
 public void TestMethod2()
 {
       var stub = new Mock<ISomeInterface>();
       stub.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<string>()))
                .Returns<string, string>((x, y) => {
                     if (x != string.Empty && y != string.Empty){ return "foo";}
                     if (x == string.Empty && y == string.Empty){ return "bar";}         
                     return string.Empty;
           });

       var sut = new SomeClass(stub.Object);

       var r = sut.SomeMethod();

   }

Refactoring Windows8 style app for Testability

Couple of months ago, I wrote an article to the 2nd / September issue of the DNC Magazine on improving the testability of Win8 metro app. It is a pleasure to see that this article has come out nicely in the Magazine.

This article explains how we refactor an existing metro app and improving its testability while using the MVVM (Model View ViewModel) pattern. I also introduce the MoqRT framework and how to overcome challengers of testing metro style apps. This also includes some of the cool features in VS2012 Unit Testing support.

There are some other great articles and including a very interesting interview with Jon Skeet.

Go ahead and subscribe (it is FREE) and you will love it.

http://www.dotnetcurry.com/magazine/dnc-magazine-issue2.aspx

Also available
http://www.dotnetcurry.com/showarticle.aspx?ID=884