Finding the path to the running assembly

There are several ways to get the path to the running assembly in c#.
I used to do something like

Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

However when running unit tests etc this would cause pain and some old dirty solutions included injecting a hardcoded path for testing.

I recently found a much better way to do this when googling around on the Internet:

Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
String path = System.IO.Path.GetDirectoryName(uri.LocalPath);

I can´t remember where I found but now it is here anyway :)

Generating xsd schema from class

I always forget the syntax so here it is for reference

Lets say we want to generate a schema for the class User in the assembly SomeCodez.dll

C:\Somepath\SomeCoedz\bin\Debug>xsd.exe -t:User SomeCodez.dll /o:c:\temp\

NSubstitute and functions calls in setup

I am getting a behaviour I didnt expect from NSubstitute when setting up my mocks to call a function. A simplified version of this

[Test]
public void NSubstituteTest()
{
    var mockedFoo = Substitute.For <IFoo>();

    mockedFoo.GenerateString(Arg.Any<string>()).Returns(x => GetValue(x.Args()[0]));
    mockedFoo.GenerateString("0").Returns("hi");


    string result1 = mockedFoo.GenerateString("0");
    string result2 = mockedFoo.GenerateString("1");

    Assert.AreEqual("hi", result1);
    Assert.AreEqual("1", result2);
}

private string GetValue(object val)
{
    string returnValue = val != null ? val.ToString() : "I am null";
    System.Diagnostics.Trace.WriteLine(returnValue);
    return returnValue;
}

The test passes but I get the output: 0 1

This indicates that the call to mockedFoo.GenerateString(“0″); actually results in a call to the GetValue() function.

If I do the same with Moq:

[Test]
public void MoqTest()
{
    var mockedFoo = new Mock<IFoo >();

    mockedFoo.Setup(x => x.GenerateString(It.IsAny<string>())).Returns((object s) => GetValue(s));
    mockedFoo.Setup(x => x.GenerateString("0")).Returns("hi");


    string result1 = mockedFoo.Object.GenerateString("0");
    string result2 = mockedFoo.Object.GenerateString("1");

    Assert.AreEqual("hi", result1);
    Assert.AreEqual("1", result2);
}

Then my tests also passes but I get the result: 1

Indicating the function was not called.

After posting a question on stack overflow I got the answer:
This is a side-effect of how NSubstitute works: to get that particular syntax it needs to actually call the method to get a reference to that method.

Thinking of it it is natural but after using lambda based mocking frameworks like Moq I was caught by surprise.

Uploading files with asp.net mvc–Request.Files is null

I have used asp.net mvc since beta and uploaded files without any problems until yesterday.

I kept getting null from Request.Files (Actually I use HttpPostedFile as inparameter to the action). Nevertheless both Request.Files and the inparamer was null.

In the form:

<% using (Html.BeginForm("UploadFile", "Product", FormMethod.Post, 
                                    new {enctype = "multipart/form-data"})) {%> 
File
<%} %>

In the controller:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
	if (file != null && file.ContentLength > 0)
	{
		var fileName = Path.GetFileName(file.FileName);
		var path = Path.Combine(Server.MapPath("~/App_Data/upload"), fileName);
		file.SaveAs(path); 
	}
	return RedirectToAction("Edit", "Product");
}

Can you spot the error? Well it took me quite some time to figure it out:
The <input type="file" id="file" /> needs to hade a name. Changing it to <input type="file" id="file" name=file" /> solves the problem.

Defensive coding with code contracts

I find defensive coding a really great way to improve the quality of a codebase.

Code contracts is an implementation of Design by contract (dbc). Dbc was introduced in 1986 by Bertrand Mayer for use with Eiffel.

The concept is simple, check that the input to a method is valid and that the return values are valid. What valid means is set up in pre- and post conditions. As simple as it sounds – in most projects I have seen this is sparsely used. I am not sure why. perhaps many developers are to lazy? I know I can be sometimes. It is easy to fall into the old bad habit of thinking “this code will change, I will improve it later”. As we all know – LATER IS NEVER.

A primitive and often used way of implementing dbc is obviously using an if statement and throwing an exception. Sometimes this is referred to as a guard.

public long Divide(int x, int y)
{
    if(y == 0)
        throw new ArgumentEcxeption();

    return x/y;
}

This tends to get rather verbose over time. I have used this project on CodeProject in a few projects and found it helpful. The code looks a lot better.

public long Divide(int x, int y)
{
    Check.Require(y != 0);

    long result = x / y;
    
    Check.Ensure(result < 15); // whatever you want to check...
    return result;
}

The code is much cleaner, this however relies on a static class and a bunch of flags – not very flexible but fully understandable.

Microsoft has developed their own integrated solution called Code Contracts. If you use Visual Studio (for Code Contracts Standard Edition) or Visual Studio 2008 Team System or Visual Studio 2010 Premium Edition or Visual Studio 2010 Ultimate Edition (Premium Edition) you can download it at http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx

The use of Code Contracts is very similar to the last solution:

public long Divide(int x, int y)
{
    Contract.Requires(y != 0);
    Contract.Ensures(result < 15); // whatever you want to check...
    
    return x / y;
}

After installing Code Contracts you get a new tab in project settings:

procject_properties

Runtime contract checking enables checking of the contracts.

If you have the right version of Visual studio you also get to check static contract checking. This is in my opinion a killer feature. It means that you will get warnings at compile time if a call to a method violates the contract or if the result of a method violates the post condition. It will also give suggestions on where you should put contracts and check for nulls etc.

The downsides I see with Code Contracts is that it is a separate download from Microsoft and that sometimes creates problems when maintaining legacy applications. The pain to get all new and old add-ons and libraries to get a project up and running is sometimes a big problem. I always prefer a project I can include in the build and include in version control and build on build servers. However – I have not yet integrated Code Contracts with a build server. it would be very nice to get a report in Teamcity.

It also tends to get a bit verbose when coming to more complicated stuff as interfaces and inheritance, most things are solved using attributes.

There are a bunch of other stuff you can do with Code Contracts like turning on / off checking on methods via attributes and tweak settings.

I believe that if we start using defensive coding more rigorously we will produce higher quality software and save ourselves some headache. Furthermore I see this as a really good compliment to TDD, if we don’t have to write tests for all the things that should not happen we can focus on verifying behavior which I find more interesting, fun and productive!

Where is my SharePoint 2010 configuration database?

When SharePoint 2010 can’t connect to the configuration database you get either a 500 error or an error telling you that SharePoint could not find the configuration database.

To find out where the database is you can look at the registry key at:
HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Shared Tools/Web Server Extensions/14.0/Secure/ConfigDB/dsn

The logs are located at c:\Program Files\Common Files\Microsoft Shared\web server extensions\14\LOGS
but they didn’t give anything useful away to me.

Running NUnit with Rake from TeamCity

I ran into some trouble when I tried to get TeamCity to run my unit tests from a rake script.

After some google:ing around and trial error I got the folowing working with both command line and TeamCity:

TEAMCITY_NUNIT_RUNNER = ENV["teamcity.dotnet.nunitlauncher"]
NUNIT_EXE = "tools/NUnit/nunit-console.exe"
OUTPUT_PATH = "output"

desc "Unit tests"
task :test do
    puts "##teamcity['progressStart' 'Running unit tests']" 
    #Select the correct test runner
    if(TEAMCITY_NUNIT_RUNNER == nil)
        system "#{NUNIT_EXE} Tholbox6.Tests/bin/debug/Tholbox6.Tests.dll /framework=4.0.30319 /nologo /xml=#{OUTPUT_PATH}/TestResults.xml"
    else
        system "#{TEAMCITY_NUNIT_RUNNER} v4.0 x86 NUnit-2.5.5 Tholbox6.Tests/Tholbox6.Tests.csproj"
    end
	puts "##teamcity['progressFinish' 'unit tests']" 
end

It is important to change the switches around for NUnit depending on your platform and framework version, note that the notation for that is different for nunit-console and the TeamCity nunit runner.
We use Albacore for some really nice handling of tasks for .Net but I couldn’t get the NUnit runner in Albacore to play nice with TeamCity. If I get some spare time I’ll investigate it and see if I can contribute in any way.

Trouble installing gems like irake?

I found myself in some trouble installing some gems using IronRuby and igem, including rake, the errormessage wasn’t really clear to me.

After some google-ing around I found the swithches to get a better one:

igem install rake –verbose –debug

I guess I could had poked around the gem help commands too but hey – whatever gets me the results.

Anyway, the problem was that I didn’t have write permissions in two folders:

C:\Program Files (x86)\IronRuby 1.1\bin

and

C:\Program Files (x86)\IronRuby 1.1\Lib\ironruby\gems

One way to mock Request.QueryString and Request.Form

I often find it convenient to test Asp.Net MVC application on the controllers. One thing I find myself repeat over and over again is mocking the HttpContext and setting Request.QueryString and Request.Form values. It brings great value to the tests being able to test how the model binders behave given certains posted values or how the controller logic reacts to querystring parameters.

Most of the time I use Moq and here is some code to achieve the mocking:

[Test] 
public void Some_Clever_Test() 
{ 
  var querystring = new NameValueCollection {{"something", "got_value"}}; 
  var formvalues = new NameValueCollection {{"pageid", "1"}}; 
  ControllerContext context = TestHelpers.GetControllerContext("GET", querystring, formvalues); 
  var controller = GetController(context); 
  ActionResult actionResult = controller.Index(); 
  var model = actionResult.Model <productpageviewmodel>();  // A nice helper I found somewhere
  Assert.That(model, Is.Not.Null); // Perhaps a more clever assert here... 
} 

TestHelpers.GetControllerContext looks like this:

public static class TestHelpers 
{ 
  public static ControllerContext GetControllerContext(string httpmethod, NameValueCollection querystring = null, NameValueCollection form = null) 
  { 
    var user = new Mock <iprincipal&gt(); 
    user.Setup(u => u.Identity.Name).Returns("testid"); 
    var request = new Mock <httprequestbase>(); 
    request.Setup(r => r.HttpMethod).Returns(httpmethod); 
    request.Setup(r => r.PathInfo).Returns(string.Empty); 
    var mockHttpContext = new Mock<httpcontextbase>();     
    mockHttpContext.Setup(c => c.Request).Returns(request.Object);     
    mockHttpContext.Setup(c => c.User).Returns(user.Object);     
    mockHttpContext.Setup(c => c.Request.QueryString).Returns(querystring);     
    mockHttpContext.Setup(c => c.Request.Form).Returns(form); 
    return new ControllerContext(mockHttpContext.Object, new RouteData(), 
                                            new Mock<controllerbase>().Object); 
  } 
} 

This can be extended to be a bit more clever but its a start.

Saving changes is not permitted in SQL Server

The solution for errormessage:

Saving changes is not permitted, The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table thar can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

Go to Tools –> Options –> Designers –> Table and database designers

Uncheck the checkbox: “Prevent saving changes that require the table to be re-created”

prevent_changes