How to check http status code with watin

I’m about to write my own blog, which will replace this one when it’s done. When doing so there is no excuse to not do it as it should be done. So I’m using SpecFlow to define my features and WatiN to drive my browser tests. One thing I found was that there is no direct way to check the response code for request. A colleague of mine has written this post that covers how you catch navigation erros. But I would like to catch 200 codes as well so I extended it to allow for this. I don’t think it is 100 % accurate, since you can only assume that if you don’t get an error it is a 200 code, which is not true all the time. Alos, it only extends the IE browser, but that should be ok for this scenarios. My guess is that any redirect code doesn’t cause an error which will not work in my scenario. However, here is the code to do the job.

First we have the NavigationObserver from the blog that will act as an observer of the browser and will catch errors and also when the navigate complete.

The thoughts behind this is that when an error occurs, we catch it in the error handler and set the flag that an error has occured. In the complete event we check if the flag is set, if the flag is set we won’t change the status code, and if it isn’t checked we assumes that we have an 200 status code. To make it easier to use this observer I have implemented the following extension to the WatiN IE browser.

If you use this custom browser instead of the standard IE you should be able to check some status codes. I might do some work with the code to get it to cover more scenarios.

Creating custom unobtrusive file extension validation in ASP.NET MVC 3 and jQuery

Just recently I was given the task to move a part of an ASP.NET WebForm to ASP.NET MVC since we are moving over to ASP.NET MVC. The part that I would move over had a form that contained a file upload controller and there were some custom implemented JavaScript hacks to verify that the file had the right file extension. I thought I could do better using data annotations, unobtrusive jQuery and implement a custom validator that also work on the client side so this post is about writing custom validation on the server and unobtrusive validation for ASP.NET MVC 3 on the client.

Server side validation

The first step to get this working is to get the server side validation to work since you allways want server side validation to make sure the user hasn’t bypassed your client side validation. The attribute we need to implement will look something like:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileExtensionsAttribute : ValidationAttribute
{
    private List<string> ValidExtensions { get; set; }

    public FileExtensionsAttribute(string fileExtensions)
    {
        ValidExtensions = fileExtensions.Split('|').ToList();
    }

    public override bool IsValid(object value)
    {
        HttpPostedFileBase file = value as HttpPostedFileBase;
        if (file != null)
        {
            var fileName = file.FileName;
            var isValidExtension = ValidExtensions.Any(y => fileName.EndsWith(y));
            return isValidExtension;
        }
        return true;
    }
}

You apply the property like such

[FileExtensions("txt|doc")]
public HttPostedFileBase File { get; set; }

When this attribute is applied to a property or field of type HttpPostedFileBase and is given a string with extensions separated by “|” it will take those extensions and validate the HttpPostedFileBase property that it is applied to. As you can see I am returning true if the file is null, and that is because if a file should be required should have the Require attribute as well. But all this is still on the server and we want to bring it to the client which is the next step.

Before we continue with the next step, which is Unobtrusive client side validation, I thought I would show you a simple editor template to make it easier to get the correct markup for the HttpPostedFileBase:

 @model System.Web.HttpPostedFileBase
 @Html.TextBoxFor(model => model, new {type = "file"})

Save the file as HttpPostedFileBase.cshtml in the folder Views/Shared/EditorTemplates. When you have saved the file you will be able to write @Html.EditorFor(model => model.FileProperty) and you will get the right html.

Unobtrusive client side validation

Unobtrusive JavaScript is not formally defined but it basically says that you should separate your logic (JavaScript) from your view (the html code) and then bind JavaScript after the page has loaded. This way you don’t get any JavaScript code in your view and if you do it correctly the page will still be supported in browsers that don’t support JavaScript.

One thing about client side validation on the web is that you should NOT rely on it, it should only be there to make a better user experience. Enough said, let get to the point.

There are four steps that you need to do to implement unobtrusive client side validation:

  • Enable unobtrusive validation and add the scripts.
  • Implement a ModelClientValidationRule that is part of the bridge to the JavaScript.
  • Implement the rule in JavaScript.
  • Implement an adapter that is the second part of the bridge to the JavaScript rule.

Enable unobtrusive validation and add the scripts.

This step is the easiest one. You can enable unobtrusive validation in two ways, either in code:

Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);

or in web.config:

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

When you have enabled it you need to include the scripts jquery.validate.js, jquery.validate.unobtrusive.js and of course your own script that will contain the custom validation code.

Implementing the ModelClientValidationRule

The code for the ModelClientValidationRule is:

public class ModelClientFileExtensionValidationRule : ModelClientValidationRule
{
    public ModelClientFileExtensionValidationRule(string errorMessage, List<string> fileExtensions)
    {
        ErrorMessage = errorMessage;
        ValidationType = "fileextensions";
        ValidationParameters.Add("fileextensions", string.Join(",", fileExtensions));
    }
}

It is somewhat straightforward; the ErrorMessage is the message that is shown on the client, the ValidationType is what it says it is, that is, the type of the validation. When the ModelClientValidationRule is done we need to add it to the ValidationAttribute:

public class FileExtensionsAttribute : ValidationAttribute, IClientValidatable
{
    ... // Same as before

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientFileExtensionValidationRule(ErrorMessage, ValidExtensions);
        yield return rule;
    }
}
}

Implementing the adapter

The JavaScript adapter is in this case basically the definition of the rule. It doesn’t necessary have the actual logic that do the testing, but it sets up everything that needs to be tested.

$(function () {
    jQuery.validator.unobtrusive.adapters.add('fileextensions', ['fileextensions'], function (options) {
        // Set up test parameters
        var params = {
            fileextensions: options.params.fileextensions.split(',')
        };

        // Match parameters to the method to execute
        options.rules['fileextensions'] = params;
        if (options.message) {
            // If there is a message, set it for the rule
            options.messages['fileextensions'] = options.message;
        }
    });
} (jQuery));

The code above is executed when the document is ready and adds an “adapter” to the unobtrusive framework. The first paramter is the name of the adapter in this case is “fileextensions” and it should match the ValidationType in the ModelClientFileExtensionValidationRule. In the ModelClientFileExtensionValidationRule we defined a ValidationParameter that was named “fileextensions”, that is why we have an array with “fileextensions” in it as second parameter. The second parameter should contain the names of all the parameters that are added to the ValidationParameters property. The third parameter is the function that basically configures the rule, note that it doesn’t execute the rule.

Implementing the rule in JavaScript

Adding a rule to the a test is as simple as adding the adapter. The code below includes both the adapter and the rule.

$(function () {
    jQuery.validator.unobtrusive.adapters.add('fileextensions', ['fileextensions'], function (options) {
        var params = {
            fileextensions: options.params.fileextensions.split(',')
        };

        options.rules['fileextensions'] = params;
        if (options.message) {
            options.messages['fileextensions'] = options.message;
        }
    });

    jQuery.validator.addMethod("fileextensions", function (value, element, param) {
        var extension = getFileExtension(value);
        var validExtension = $.inArray(extension, param.fileextensions) !== -1;
        return validExtension;
    });

    function getFileExtension(fileName) {
        var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
        if (extension != undefined) {
            return extension[0];
        }
        return extension;
    };
} (jQuery));

It is the row jQuery.validator.addMethod(...) that is relevant here. We add a rule that we define with the name “fileextensions”. The parameters to the rule are the value that is to be validated, the element that is being validated and the parameters that we set up in the adapter. In our case the validation is really straightforward, first we get the file extension using the helper method getFileExtension, then we check if the extension is present in the list for file extensions that on the fileextensions property on the param parameter and return the result.

I think this is all there is to it. If you have any question or comments just use the form below.

Securing your ASP.NET MVC 3 application

The following blog post is most likely well covered on the internet, but I thought I would write about it anyway just so I now where to find it next time I need it. As you probably have figured the topic that will be handled in this post is securing your ASP.NET MVC 3 application. When talking about security there are two things we need to consider; authentication and authorization. This post will handle the authentication part since authorization is specific to your application and most of the time it will be enought just to use the AuthorizeAttribute.

Authentication done right in ASP.NET MVC 3

Authentication is the first step in my short security chain, first I authenticate the user to assign an identity, roles or claims to the user. If I’m not developing a simple web site where every user has access to every page I most often want to restrict access to all pages except those that I have explicitly white listed for anonymous access. So how do I go along and implementing white listing i ASP.NET MVC 3? It turns out that it is really easy since ASP.NET MVC 3 introduced global action filters which you can apply to all controllers and actions in the application, compared to local action filters which you apply only to a controller or action. When you have a global action filter in place you can apply a local action filter to those actions or controllers that you do want anonymous users have access to, like the log in action. The global action filter that I will use to restrict the access to the application look like:

public class RequireAuthenticationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
                                    typeof(AllowAnonymousAttribute), true);
        if (!skipAuthorization)
        {
            base.OnAuthorization(filterContext);
        }
    }
}

It is pretty straight forward but here are some comments about it. Everywhere it says Authorization really means Authentication if you ask me, but it is handled the same way in the framework. The OnAuthorization method checks if a local filter called AllowAnonymousAttribute (which is coming next) is defined on either the action or on the controller. If the local filter is defined we want to allow anonymous access and can therefor skip authentication, that is, the call to base.OnAuthorization. The code for the AllowAnonymousAttribute is probably one of the most simple class you have ever seen:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class AllowAnonymousAttribute : Attribute
{
}

All the class do is defining an attribute that I can apply to classes (controllers) or methods (actions). It doesn’t have to have any functionality since all I do in the RequireAuthenticationAttribute is checking if the AllowAnonymousAttribute is present.

To apply this global action filter you need to add the filters to your global action filters collection in your global.asax file. So in your global.asax file you need it to look something like this:

protected void Application_Start()
{
    ...
    RegisterGlobalFilters(GlobalFilters.Filters);
    ...
}

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new RequireAuthenticationAttribute());
    ...
}

In the Application_Start method I make a call to my RegisterGlobalFilters method and register the RequireAuthenticationAttribute so if you try to access any page, that is handled by MVC, you will be denied access to it since you are not authenticated. That is the exact behavior we want, but now it is time to start white listing actions. The actions I want to white list are the LogOn and Register actions in my AccountController:

public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult LogOn()
    {
        ...
    }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        ...
    }

    [AllowAnonymous]
    public ActionResult Register()
    {
        ...
    }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Register(RegisterModel model)
    {
        ...
    }

    ...
    ...
}

If you now try to access the application again you should be redirected to the log on page if you have a default ASP.NET MVC 3 application.

That is all there is to it basically. Applying this in a filter instead of having this functionality in a base controller as you would do in ASP.NET MVC 2 is much more “correct”. When you have it in a global filter it is basically impossible to do a mistake compared to when you are forced to inherit a specific controller which you might forget.

Automatic creation of repository when using gitolite

The last couple of days I’ve been playing around with git and setup my own git server using first gitosis and then gitolite. When playing around I created a lot of different test repositories to make sure everything work. To stop repeating myself I created three minor bash functions to make it easier to add repositories in gitocline. The script I ended up with are the following:

ar() {
    if [ "$1" == "" ] ; then echo "[E] One arg is needed!"; return 1; 
else
        cd ~/<some path to your>/gitolite-admin/conf
        echo -e "" >> gitolite.conf
        echo -e "repo ${1}" >> gitolite.conf
        echo -e "RW+ = <your gitolite username>" >> gitolite.conf
        cd ..
        git commit -am "Added repo ${1}"
        git push
    fi  
}

sr() {
    if [ "$1" == "" ] ; then echo "[E] One arg is needed!"; return 1; 
    else
        mkdir <path to where you have your repositories>/${1}
        cd <path to where you have your repositories>/${1}
        git init
        git remote add origin gitolite@e2n.no:${1}
        touch README
        git add .
        git commit -am "Initial commit"
        git push origin master
    fi
}

cr() {
    if [ "$1" == "" ] ; then echo "[E] One arg is needed!"; return 1; 
    else
        ar ${1}
        sr ${1}
    fi
}

It is somewhat static code, but I’m not that likely to change where I have the folders on my local computer anyway. I should probably mention that these three functions are stored in the .bashrc file and that I assumes you have checked out the gitolite-admin repository. Let us walk through the three functions.

  • ar (short for add repository): will navigate to the configuration folder for gitolite and add the repository plus read and write access for a user name (should probably use a group instead). It will also commit the changes and push them to the server to create the repository.
  • sr (short for set up repository): will first create a folder for the repository, then initialize git in that folder, add a remote to your new repository and make an initial commit and push.
  • cr (short for create repository): will execute both the above functions.

This will allow us to create a repository and set it up on our local machine by running

$ cr repository_name

That’s all.

Continous deploy using Teamcity and Appharbor

First of all, this is how I did it and I might have done some parts not according to how the people at JetBrains think I should do it, but I didn’t find another way to do it. So if someone has some improvements just write a comment or two.

TeamCity, from JetBrains, is by far the easiest to use continous integration software I have used for .NET-projects. Just recently I found appharbor, which is a cloud hosting service like heroku but for .NET, I immediately began thinking about how I could combine these two services using github. So my goal with this post is to walk you through how we can set up a TeamCity server to trigger builds from checkins to github and automatically pushes the result to appharbor.

  1. Setup github repository
  2. Setup appharbor application
  3. Configure git repository on build server
  4. Configure TeamCity

1. Setup github repository

I could probably walk you through the process in setting up your github repository, but it is probably easier to just follow the instructions on github.

2. Setup appharbor application

Creating an application at appharbor is just as easy as setting up a repository at github. All you do is create an account on appharbor and then click the “applications” link and “Create new”.

3. Configure git repository on build server

This is one of the trickier parts and it has two steps we need to do. First, create repository so we can do a simple pull from github and push to appharbor, and configure the repository so we can do a push to appharbor without the need of providing a password. The first couple of steps is quite easy to understand and they are:

#> git clone ...path to github repository... YourRespositoryDir
#> cd YourRespositoryDir
#> git remote add appharbor ....path to appharbor application...

So what have you done here? First we clone the github repository so we can access the code, you can use the read-only url since we will not push to github from our buildserver. After that we set up one additional remote that is the remote to our appharbor where we will push the code.

The second step in the process of configuring the local git repository is to provide some kind of mechanism so we don’t have to provide the password manually when we run

#> git push appharbor master

Usually that will force you to provide the password manually since you can’t configure appharbor to use ssh stuff (I call it stuff since it is not of importance here). How can we provide a password without typing it? It turns out that git has a configure option called core.askpass which, if set, will call whatever program assigned to that property and take whatever that is written to the standard output and use it as password. Lucky for you I have created such a program that is quite useful for scenarios where you might have multiple builds environments and you can find the source to it here. To use it just download and build an executable for you and copy it to where you think it belongs. Run the following git command

git config core.askpass ... path to the executable...

Now git will ask that program of the password so how do you get your password in there? It is not trivial since we want to be safe and simple. To register a password you run the following command:

c:\pathtoexe\EasyPass.exe -a <project name> <password>

That will create an encrypted password using the Windows Data Protection API (DPAPI) (wikipedia link since the one on msdn is quite old) and store it in a file on the running users isolated storage. You can register multiple password, but only one per project name. To get the password from the program you need to set the ProjectName environment variable, as of the moment it is hard coded that the environment variable must be named ProjectName but I might add functionality so you can define the name of the environment variable later on. So if you run the following three commands in a row:

c:\pathtoexe\EasyPass.exe -a Proj1 password1
c:\pathtoexe\set ProjectName=Proj1
c:\pathtoexe\EasyPass.exe

You will get “password1″ as output to the console. There are a couple of additional options you can use:

  • -i – will give you an “interactive” mode so you don’t have to type “EasyPass” every time (use “q” to quit the “interactive” mode)
  • -a <project name> <password> – as above but you can also use it to update a password for a project
  • -l – will list all your registered project, their password and the encrypted string
  • -d <project name> – delete the project matching the project name
  • -g <project name> – will give you the password for the specified project without setting the environment variable.

Now we are getting close to the end of this step but there is one more thing to do. I am assuming that you have a standard installation running TeamCity, and this means that the user that will execute the git command will be the System User and not you. This means, since we are using DPAPI and isolated storage, that we must register all the passwords using the System User accound. To do that we use PsTools. When you have installed PsTools you run PsExec -s cmd.exe in the command prompt which will start a new instance of the command prompt but under the System User account. Now when we “are” the System User go to where you have the EasyPass.exe and register the password using the -a option as before. Note that you don’t have to specify an the environment variable, we will do that from TeamCity.

Now we are all set to start configuring TeamCity.

4. Configure TeamCity

I assume we are using a default installation, next-next-next-finish installation, of TeamCity, and that is why we needed to find a way to register passwords as the System User. There are three steps that needs to be done to get it working, where the first step will not be covered that much since I am using standard TeamCity functionality.

First of we need to configure the Version Control Settings for our Build Configuration. What you need to do is the following:

  • Create a VCS root that has your remote repository (github) as your fetch url
  • Set your VCS Checkout Mode to Do not checkout file automatically
    • We don’t want to checkout the file using the standard way since we don’t get the complete git information just the code (I might do something wrong here), we only want our build to be triggered by checkins to our repository then we will handle everyting from that point and on.

The second step is to create the first build step that will get the code for you, and for that we use PowerShell. So create a build step with the following input:

  • Set runner type to PowerShell
  • Set name to Checkout Code (or whatever)
  • Set the working directory to the path to your repository that you configured in Step 2
  • Set script to Source Code
  • Set the script execution mode to Put script into PowerShell stdin with “-Command -” arguments
  • Set script source to the following code

 

$gitExec = "c:\Program Files (x86)\Git\bin\git.exe"
$arguments = "pull origin master"
start-process -wait $gitExec $arguments

That will pull the code from github if your repository is configured correct.

The last step is to push the code to appharbor (of course you could have multiple build steps in between or even additional build configurations that you want to run). This step will also be using PowerShell, so the first four steps is the same as above, the only difference is the script source which should be:

$gitExec = "c:\Program Files (x86)\Git\bin\git.exe"
$arguments = "push appharbor master"
[Environment]::SetEnvironmentVariable("ProjectName", "Your project name you registered the password with", "Process")
start-process -wait $gitExec $arguments

The code above will set the environment variable ProjectName to the one you have registered your password with, so when git is asking for the password it will get the right one. The it will push the code to appharbor. It is basically not much more to it, if you want to know more about the PowerShell I am not the guy to ask but ask google.

Now there is one final step, and that is to add a build trigger that triggers on VCS changes. That is all there is to it, now you can go on setting up your continous deployment environment.

If someone from JetBrains is reading this and thinking about how this could be made easier I have some suggestions:

  • Some kind of password manager integration for handling appharbor passwords
  • Even better git integration, that get all the information from the git server and not just the code

How to get your WCF Web Api app running on AppHarbor

This is not a post in how you deploy to AppHarbor, how you write your first WCF Web Api app or how to resolve local 404 errors with PUT and DELETE. This is a post of what you should do if everything is working locally but you still get 404 errors on AppHarbor, that is the error I got when I deployed my first WCF Web Api app to AppHarbor. After discussing with the support at AppHarbor and posting to StackOverflow the guys at AppHarbor find the answer. The simple solution is that you need to have the following in your web.config to get the app running on AppHarbor.

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

AppHarbor might be able to resolve this so you don’t need this in your web.config, but at the moment you do. Enjoy!

Creating step definition report i SpecFlow on .NET 4.0

I manage to bring SpecFlow to the project and everyone was really impressed. However, I wasn’t 100 % satisfied with SpecFlow since I wasn’t able to get the step definition report at first. I found the problem to be that my test project was written in .NET 4.0, and needs to be so, but the tools was compiled in .NET 3.5. This caused some reflection problems when the specflow stepdefinitionreport MyProject.csproj was executed and the report wasn’t generated. It worked fine with the execution report. I downloaded the SpecFlow code from github and compiled it using .NET 4.0 instead of .NET 3.5 and got it working, but that is not a good solution since I want to use NuGet to manage my updates of SpecFlow. So after searching around and asking my way on twitter I got an answer by @gasparnagy that pointed me to this Google groups thread where I found a better solution. So the solution I ended up with was to force specflow.exe to use the .NET 4.0 runtime by using the config file below:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <startup> 
         <supportedRuntime version="v4.0.30319" /> 
    </startup> 
</configuration> 

Just copy the config above and create a specflow.exe.config file and put it next to your specflow.exe and you will be able to create the step definition report.

Extending the NuGet Package Manager Console

If you read my previous post about how to create a NuGet package this is a follow up on that post. I will in this post, most example code, show you how to extend the Package Manager Console in Visual Studio with a NuGet package. More precisely I will extend the Console with the feature of asking http://www.classnamer.com to generate a class name for me since sometimes when I develop I run out of imagination and at those points it can be good to get generated class names like CryptographicUserLogger :).

The post consist of two parts; the first part shows you the code we will run in order to get the class name and initialize the scripts. So let’s get started.

Creating a PowerShell extension script

Since this is my first PowerShell ever the code might not be the best code ever, but that is not the point. The first part is to write the actual module that will do all the work. The code for the module ClassNamer.psm1 look like:

function Get-ClassName {
    $ie = new-object -com InternetExplorer.Application
    $ie.navigate("http://www.classnamer.com/")
    if (!$ie) { Write-Host "variable is null" }
    while ($ie.Busy -eq $true) 
    { 
        Start-Sleep -Milliseconds 1000; 
    } 

    $doc = $ie.Document
    if (!$doc) 
    { 
        Write-Host "variable is null"
        return "SorryCantGiveYouAGenericClass" 
    }
    $answer = $doc.getElementByID("classname") 
    return $answer.innerHtml
}

Export-ModuleMember Get-ClassName

There is two part of this code, the function definition and the export command which I guess define which functions that are public from this module. The code is pretty straight forward, but here is a short description of the Get-ClassName function:

  1. Create a IE object
  2. Browse to get the page
  3. Sleep while busy (should probably add a max loop counter)
  4. Get the doc, which is the DOM of the web page
  5. Query the doc object of the relevant element and extract the value

The next part is to write the script that will get the module imported, init.ps1, to the Package Manager Console. I basically copied the code from Phil Haack’s blog post about the same topic. The code looks like:

param($installPath, $toolsPath, $package, $project)

Import-Module (Join-Path $toolsPath ClassNamer.psm1)

When the above script is run it will import the module ClassNamer.psm1. Now all we need to do is to put both the PowerShell files in a tools folder and in the same folder as where we have tools folder we run the command nuget spec ClassNamer. The command will generate a ClassNamer.nuspec file for us with the default metadata. When we run nuget pack on the ClassNamer.nuspec file it will create a package with that contains the tools folder, and when we install the package in Visual Studio the init.ps1 script will be run by NuGet and install our module. If done correctly you will be able to get something like the image below when you’ve installed the package and run the new Get-ClassName command:

ClassNamer screen shot

How to upgrade MSSQL Tools Express to Complete

Now I’ve had this issue one or two times but this is the first time I actually managed to solve it. The scenario is that I had SQL Server 2008 R2 Express install, which is missing the profiler tools. So I thought I’ll just upgrade to standard since we have licenses at my company. That is easier said than done, when upgrading to standard the tools is not updated only the server, so now you have an updated server but basic tools. To update the tools you need to uninstall the tools first, but the trick is to how. So here is how you uninstall the tools:

  1. Open the control panel and then Program and Features
  2. Find “Microsoft SQL Server 2008 R2 (xx bit)”
  3. Right click and choose “Uninstall/Change”
  4. Choose “Remove”
  5. Follow the wizard until you get to “Select Instance”
  6. In the drop down choose “<<Remove shared features only>>” and click “Next >”
  7. Select “Management Tools – Basic” and then continue and finish the wizard to uninstall it

Now when you have uninstalled the basic tools it is time to install the complete tools, so insert the DVD or mount the iso-file and run Start Setup.exe.

  1. Click in “Installation” and choose “New installation or add features to an existing installation”
  2. Click “OK” in the “Setup Support Rules” screen
  3. Click “Install” in the “Setup Support Files” screen to install the support files
  4. Click “Next >” in the second “Setup Support Rules” screen
  5. Select “New installation or add features” and click “Next >”
  6. Choose license and click “Next >”
  7. Accept license and click “Next >”
  8. Choose “SQL Server Feature Installation” and click “Next >”
  9. Check the “Management Tools – Complete” and finish the wizard to install the complete tools

If you follow the steps above you should now have installed the complete tool set to SQL Server including SQL Profiler.

Linq tip of the day – Aggregate

One thing that I have noticed is that people tend to not be aware of the Aggregate function that exist for linq. If you learn how to use the Aggregate function it will be useful for you in many scenarios. One scenario where I have found it useful many times is in logging scenarios, especially when you want to log some output from a list or array as the example below:

var list = new string[]{"These", "values", "need", "to", "be", "logged", "in", "reverse"};
var output = list.Aggregate((aggregate, next) => next + " " + aggregate);
Console.WriteLine(output); //prints "reverse in logged be to need values These"

Another useful scenario is when you want to do some mathematical calculations on a series of numbers with a starting condition, like a checking account in the example below:

var currentBalance = 100000;
var withdrawals = new int[] { 1000, 2034, 16243, 2423, 44234 };
var updatedBalance = withdrawals.Aggregate(currentBalance, (aggregate, next) => currentBalance - next);
Console.WriteLine(updatedBalance);

The following is a little bit more complicated but I think it really shows the strength of the Aggregate function. Let say you have some kind of rule engine that validates some kind of object. Now you what to run all these rules against your object, and at the same time update the object so it stores a collection of violated rules. I think that a realistict scenario and the following code show how you can solve the validation using Aggregate.

class Program
{
    static void Main(string[] args)
    {
        var rules = new List<Rule> { new RemoveARule(), new RemoveXRule(), new RemoveZRule() };
        var input = new MySuperSecretEntity();
        var output = rules.Aggregate(input, (aggregate, rule) => rule.Validate(aggregate));
        // input.ViolatedRules now contain a set of violated rules
        var violatedRules = input.ViolatedRules.Aggregate("", (aggregate, next) => aggregate + ", " + next.ToString());

        Console.WriteLine(violatedRules); // Prints the type of the two violated rules
        Console.ReadLine();
    }
}

class MySuperSecretEntity
{
    public string DoILookFine = "This is the string that will be validated against a set of rules!!!";
    public List<Rule> ViolatedRules { get; set; }

    public MySuperSecretEntity()
    {
        ViolatedRules = new List<Rule>();
    }
}

abstract class Rule
{
    protected string MustContainLetter { get; set; }

    public MySuperSecretEntity Validate(MySuperSecretEntity input)
    {
        var isValid = input.DoILookFine.Contains(MustContainLetter);
        if (!isValid) input.ViolatedRules.Add(this);
        return input;
    }
}

class RemoveARule : Rule
{
    public RemoveARule()
    {
        MustContainLetter = "a";
    }
}

class RemoveXRule : Rule
{
    public RemoveXRule()
    {
        MustContainLetter = "x";
    }
}

class RemoveZRule : Rule
{
    public RemoveZRule()
    {
        MustContainLetter = "z";
    }
}

That was my .Net/linq tip of the day.