Thursday, May 31, 2012

Using async in .NET 4.0

The new async and await keyword in C# 5  is just syntactic sugar. Behind the scenes the code got rewritten to a state machine implementation. As both of .NET 4.0 and .NET 4.5 are using the same CLR, it should be possible to use the async functionality in .NET 4.0 too.

AsyncBridge

The first thing you could try is AsyncBridge. It's a NuGet package that lets you use the real VS 11 C#5 compiler to write code that uses the async and await keywords, but to target .NET 4.0.  . You just add it to your project, and the compiler will pick it up and use it to implement async/await. The only requirement is that you also have Visual Studio 11 installed on your machine.

The code is available here: https://github.com/OmerMor/AsyncBridge.

It follows the same idea as LINQBridge, which let you use C# 3 LINQ, but only require .NET 2.0.

Async Targeting Pack for Visual Studio 11

Another option you have (and an official one) is the Async Targeting Pack for Visual Studio 11. (As the long name indicates, this is a Microsoft solution Knipogende emoticon)

“The "Async Targeting Pack for Visual Studio 11" enables projects targeting .NET Framework 4.0 or Silverlight 5 to use the Async language feature in C# 5 and Visual Basic 11. This pack requires Visual Studio 11 and will not work with Visual Studio 2010.
The pack contains the API support necessary to use the 'async' and 'await' keywords in C# 5.0 and Visual Basic 11, as well as a set of Task-based adapter APIs that allow using some of the existing asynchronous APIs with the new language keywords.
This targeting pack is not required for projects targeting .NET Framework 4.5 or .NET for Metro style apps. It is only required for projects targeting Silverlight 5 and .NET Framework 4.0. Earlier platform releases are not supported.”

Wednesday, May 30, 2012

Creating a .gitignore file for .NET development

Why a .gitignore file?

By default Git will monitor all the files inside your folders.  So this means that even bin and obj folders and (if you are using Resharper, your _ReSharper files) are listed to be added to your repository. I don’t think you want to include these files inside your source control system(at least I don’t).

Creating the .gitignore file in Windows

I’m not a commandline guru, so I tried creating this file the easy way. I created a new text file inside my repository folder and tried to rename it to .gitignore.  Unfortunately no success:

image

It seems that Windows doesn’t understand dot files (and Git uses this a lot; .bashrc, .gitignore, etc…). Windows expects your files to have a name.extension convention.

So back to the Gitbash console…  but no .gitignore. Type “touch .gitignore”. This will create the .gitignore file with no content.

image

Adding the .gitignore content to support .NET development

So now we have our .gitignore file, but it is still empty.  What information should I add? Depending on the kind of development you’re doing(.NET, Java, Ruby), you probably want to add different data. Don’t loose time searching for this data yourself, instead go to https://github.com/github/gitignore and pick the content that suites your needs:

image

I’m going for the CSharp.gitignore file. Copy the content to your clipboard and open the .gitignore file in your favorite text editor (i.e., notepad, wordpad, notepad++, etc).  Paste the CSharp.gitignore content and you are good to go!

Tuesday, May 29, 2012

VSColorOutput

A colleague sent me the link to the following useful Visual Studio plugin: VSColorOutput.

“VSColorOutput is a Visual Studio 2010/2011 extension that can change the color of a line emitted to the output window based on specified rules. The rules consist of regular expressions. Rules map to classifications which in turn map to colors.”



Friday, May 25, 2012

Open Office trend: my opinion

Reading Jef Claes post on The open plan fallacy inspired me to share my opinion too. (Go read Jef’s post before you continue reading).
I don’t know how it is at other places in the world, but here in Belgium, the ‘Open Office’ idea is really popular. The idea is that everyone is sharing the same workspace. In the morning, you enter the building, take your first cup of coffee and go sit where ever you want. Everyone is sitting in the same open office. In the evening you remove everything from your desk, put your stuff inside a locker and the next day it start’s all over again. (And if you don’t like the person sitting next to you, the next day you can go and sit somewhere else).

As Jef mentions in his post the open office layout certainly has some advantages. It stimulates communication, creates more networking opportunities, optimize the usage of the available space and reduce costs. 

I have to agree with all those advantages (it’s always fun to chat with a colleague you have not seen for a while), but this comes with one cost: productivity. In my experience I have seen that teams get most effective when they have their own space, isolated from any distractions. Teams should be able to communicate freely, share ideas, do code reviews and have some fun. But in an open office layout this is hard to do without disturbing others.

I’m not advocating to introduce cubicles and all work in our isolated space but instead to create a mix of team rooms and open spaces. I do think this will increase productivity a lot…

Thursday, May 24, 2012

jQuery Dialog: don’t close on escape

The default behavior of the jQuery Dialog allows you to close a dialog by using the Escape button. For a specific use case I did not want the user to close the dialog without explicitly specifying a value.

image

The solution is to change the value of the closeOnEscape setting to false: 

$('#myConfirmDialog').dialog('option', 'closeOnEscape', false ); 

Wednesday, May 23, 2012

I’m a problem solver, not a coder

Last week I was reading the ‘Please don’t learn to code’ post by Jeff Atwood where he complaints about the intentions of Mike Bloomberg(New York City’s mayor) to learn coding. Although I think that Jeff is missing the point about what Mike Bloomberg is trying to achieve with this initiative, there are some other things inside his blog post that resonates with me.

Jeff talks about the fact that writing more code is most of the time not the desirable thing. It took me a long time to understand as a programmer that my job was not writing as much code as possible. Instead the real skill is writing as little code as possible.  (I think I have some colleagues that can agree that I’m more busy removing code, instead of writing Smile)

There are a lot of people out there that can code way better than me , but I do not care. I have evolved from someone who thought that coding was the goal to someone that believes that problem solving is my main job. And writing code is just a tool in my tool belt to solve these problems.

So goodbye ‘Bart the programmer’, here is ‘Bart the problem solver’.

mrwolf

Remark: If you don’t know Mr. Wolf, go watch Pulp Fiction!

Tuesday, May 22, 2012

TFS Build: The assembly has already loaded from a different location

When trying to run a build on a build server, the unit tests failed with the following error message:

API restriction: The assembly ‘someassembly.dll' has already loaded from a different location. It cannot be loaded from a new location within the same appdomain.

This error is caused by a combination of 2 elements. First the solution that I’m trying to build contains a web application. As a consequence the binaries are available at 2 locations; the binaries folder itself but also inside the _PublishedWebsites directory that is created beneath the Binaries folder during a team build.

The second thing is that I’m using the default Test pattern to search for Test assemblies: **\*test*.dll. This pattern indicates that the build engine will search for test assemblies containing the word ‘test’ in the binaries folder AND all subfolders.  As we have 2 places where the same assembly is found(the Binaries folder and the  _PublishedWebsites\Project\bin folder), we are getting into trouble.

defaulttestpattern

So we have to change the default search pattern from **\*test*.dll to *test*.dll. This will disable the recursive search.

changedtestpattern

Monday, May 21, 2012

Must use the rewriter when using Contract.Requires<TException>

Last week, I was trying to create a continuous integration build for a client, but the unit tests always failed. So I logged on to the build server and ran the tests from the command line. After a few tests, I received the following error message:

image

This errors tells me 2 things:

First I need to install the Code Contracts functionality on the build server. (You can download it here)

Second I have to turn on the runtime checking for the project which is using the code contracts.

codecontracts

Friday, May 18, 2012

ASP.NET: Load DLL’s from another location

By default your application DLL’s in ASP.NET application are loaded from the bin folder. But what if you want to use a different folder?
The application has some default DLL’s in the bin folder, but I want to be able to load my Module DLL’s from the bin\Modules subfolder. (Don’t ask me why Glimlach)
To do this add the following to your web.config(also works for the app.config):
<runtime> 
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
  <probing privatePath="bin;bin\Modules" /> 
 </assemblyBinding> 
</runtime>


Remark: Don’t forget to also add the bin folder to the probing path. First we forgot to do this and our default DLL’s were not loaded.

Thursday, May 17, 2012

TFS 2010: Enable work item only view

WIOV (Work Item Only View) is a restricted version of TWA (Team Web Access). It provides a limited set of operations(but you get them for free because no Team Foundation Server CAL  is needed.

But where can I find this WIOV? In TFS 2008 it was a separate web application but in 2010 there is only one application and the WIOV is controlled by the security system. On the TFS application-level there is a permission called “Use full Web Access features”. If the user connected to TWA is denied for this permission, the application switches automatically to the WIOV.

To help you a “Work Item Only View” users group is created out-of-box, which is denied for this permission already. So the only thing you need to do is start adding users to this group.

  • Log on to the Team Foundation Server
  • Open the TFS Administration Console
  • Click “Application Tier” under host name.
  • On the right hand side under Application Tier Summary, click “Administer Group Membership”.
  • Double click “Work Item Only View Users” and add necessary users here.

WIOV

Wednesday, May 16, 2012

Community Day 2012 is getting closer

Last week the registrations opened for Community Day 2012. This (completely free) event joins all the Belgian usergroups to offer you 6 tracks with over 40 deep-technical sessions and the best networking opportunities available.
Together with Kristof Mattei I will give a session about Git and GitHub for .NET developers.

Register here.
Below you can find all the details of the event:
Location: Utopolis Mechelen (Map)
Address: Spuibeekstraat 5 2800 Mechelen
Event date: Thursday June 21th
Start & end time: 8.30 - 19.00 Add Community Day 2012 to your agenda: Outlook *.ics file

Tuesday, May 15, 2012

Goodbye Visual Studio macro’s, we will miss you…or not

For the people who have missed the news:

In the next version of Visual Studio(Visual Studio 11) the macros automation feature is taken out. This includes macro record/replay, macro projects and the Macros IDE. Based on some usage data that showed that less than 1% of Visual Studio developers use this feature, they decided to not invest in this feature anymore and focus on other improvements instead.

So starting from VS 11, if you want to automate some behavior in Visual Studio, you’ll have to create a Visual Studio extension.

You have the following extension options at your disposal:

  • Visual Studio Package: This is used for the older VSPackage style pugin-ins.
  • Editor Classifier: Used for creating your own syntax highlighting
  • Editor Margin: Used to adorn the margins in an editor window
  • Editor Text Adornment: Used to adorn text within an editor window
  • Editor Viewport Adornment: Used to place editor visuals relative to the editor’s visual surface
  • [VB/C#] Item Template
  • [VB/C#] Project Template
  • VSIX Project: This is the newer plug-in model that is most commonly seen in the Visual Studio Gallery
  • Windows Forms Toolbox Control
  • WPF Toolbox Control

In addition to the language specific templates there is a generic extensibility folder containing:

  • Visual Studio Add-In: This is a wizard that lets you create add-ins using C#, VB, C++ ATL, or C++ CLR.
  • Visual Studio Package: This is another wizard that lets you choose between C#, VB, and C++.
  • Visual Studio Shell Isolated: This lets one create applications based on the Visual Studio IDE itself. An early example of this is the AddOn Studio for World of Warcraft.

More information:

Monday, May 14, 2012

CSS Lint: CSS Code Quality Tool

CSS Lint is an open source CSS code quality tool originally written by Nicholas C. Zakas and Nicole Sullivan.

Similar to JsLint for JavaScript it performs static analysis of source code and flags patterns that might be errors or otherwise cause problems for the developer.

CSS Lint points out problems with your CSS code. It does basic syntax checking as well as applying a set of rules to the code that look for problematic patterns or signs of inefficiency. The [rules] are all pluggable, so you can easily write your own or omit ones you don't want.

Let’s try it on a simple CSS class(with a small typo):

image

After clicking on the ‘LINT!’ button, we get a nice overview with all the errors found.

image

Friday, May 11, 2012

Windows 8 Metro: A better Grid application template

Brent Schooley prepared a Visual Studio template for Grid Applications that improves on the user and developer experience that Microsoft delivered in their Grid application template.

Lets compare the out-of-the-box Visual Studio templates for Metro style apps:

gridtemplate

and the Better Grid Application template:

bettergridtemplate

To install the template, put the BetterGridApplication.zip file in Libraries\Visual Studio 11\Templates\ProjectTemplates\CSharp\Windows Metro style\1033\ and then restart Visual Studio. The template should now show up in the Visual C#\Windows Metro style category in the New Project window.

Download the Better Grid Application template (.zip file, 81 KB)

Thursday, May 10, 2012

Creating a list of comma separated values using String.Join()

I’ve seen a lot of extension methods that allowed you to create a list of comma separated values.
public static string ToCSV(this IEnumerable<string> input)
{
 var temp = String.Empty;
 
 foreach (var entry in input) {
  if (String.IsNullOrEmpty(temp)) {
   temp = entry;
 }
 else 
 {
  entry += ", " + entry;
 }
 return temp;
}

I even created a similar extension method myself until I discovered the String.Join method while reading this blog post by Scott Hanselman:
var temp = String.Join(", ", input)

Wednesday, May 9, 2012

Project Liike: Exploring the Mobile Web

Project Liike is an effort by the Microsoft patterns & practices team  to produce guidance that helps organizations build mobile web experiences based off of existing web applications. There are countless devices available today and all indications suggest this number is only going to grow, without convergence. The factors to help choose between native apps and web apps are fairly well-known. Those who choose the web face numerous decisions and challenges based on their requirements. This project aims to help.

The team is building a sample application, called Mileage Stats Mobile. It will be released as open source along with all of its unit tests. This reference application, began with the source from a previous effort Project Silk. Project Silk was about building cross-browser web applications with a focus on client-side interactivity. However, it was optimized for desktop browser. Project Silk's reference application was simply called Mileage Stats.

Project Liike is about extending and enhancing Mileage Stats with a mobile experience.

Mileage Stats Mobile is just one part of Project Liike. It's a journey and a learning experience for our team to build the application. All information about this experience is published in the docs repository.

Tuesday, May 8, 2012

pServiceBus: a cross platform ESB

While looking for a cross platform ESB solution, I stumbled over the pServiceBus project on Codeplex.

“The goal of pServiceBus(Phoenix Service Bus) is to provide an API and Service Components that would make implementing an ESB Infrastructure in your environment easy. It's developed in C#, and also have API written for Javascript and Java Clients.”


Phoenix Service Bus

Maybe a good alternative for NServiceBus?

Monday, May 7, 2012

Adding AutoRegistration to the Microsoft Unity container

The default way to use an IoC container is to register all objects and their dependencies yourself. So somewhere in your code you have a long list of registrations like:
var container=new UnityContainer();
container.Register<ITypeA,TypeA>();
container.Register<ITypeB,TypeB>();
container.Register<ITypeC,TypeC>();
container.Register<ITypeD,TypeD>();
container.Register<ITypeE,TypeE>();
container.Register<ITypeF,TypeF>();
...


Most IoC containers allow you to simplify this registration process by using ‘AutoRegistrations’. Based on some rules or conventions, your assemblies are scanned for types and if these types match those rules, there are registered in the IoC container automatically.
The Microsoft Unity container does not include autoregistration out-of-the-box. However you can use  the Unity Auto Registration addon by Artem Govorov.


“Unity Auto Registration extends Unity IoC container and provides fluent syntax to configure rules for automatic type registration. Using few code lines you can scan specified assemblies and register all types that satisfy your rules. Rules for determining whether to include/exclude type/assembly are predicates (Predicate<T>) so you can use lambda syntax to specify them or direct method name. There are a few methods in If helper class (like Implements, DecoratedWith) to cover some common scenarios of type registering.”


A sample of the fluent interface:


var container = new UnityContainer();

            container
                .ConfigureAutoRegistration()
                .LoadAssemblyFrom("MyApp.dll")
                .ExcludeSystemAssemblies()
                .ExcludeAssemblies(a => a.GetName().FullName.Contains("Test"))
                .Include(If.Implements<ILogger>, Then.Register().UsingPerCallMode())
                .Include(If.ImplementsITypeName, Then.Register().WithTypeName())
                .Include(If.Implements<ICustomerRepository>, Then.Register().WithName("Sample"))
                .Include(If.Implements<IOrderRepository>,
                         Then.Register().AsSingleInterfaceOfType().UsingPerCallMode())
                .Include(If.DecoratedWith<LoggerAttribute>,
                         Then.Register()
                                .As<IDisposable>()
                                .WithTypeName()
                                .UsingLifetime<MyLifetimeManager>())
                .Exclude(t => t.Name.Contains("Trace"))
                .ApplyAutoRegistration();

Friday, May 4, 2012

Async Ajax testing using QUnit

Testing Javascript code is not that hard, but as most Javascript functionality contains some level of asychronity, testing becomes a lot harder. Let’s have a look at how we can tackle this problem.
Although other testing frameworks are available, I’m using QUnit, a powerful JavaScript unit testing framework written by members of the jQuery team.
QUnit Introduction
So how do you write unit tests with QUnit exactly? First, you need to set up a testing environment. Create an html file with the following content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Tests</title>
    <script src="../Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <link href="../Content/qunit.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/qunit.js" type="text/javascript"></script>
    <!--Add your project files-->
 <script src="../Scripts/calculator.js" type="text/javascript"></script>
 <!--Add your test files-->
 <script src="../Scripts/calculatortests.js" type="text/javascript></script>
</head>
<body>
 <h1 id="qunit-header">My Tests</h1>
 <h2 id="qunit-banner"></h2>
 <div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
 <div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>


Let’s now have a look at the calculatortests.js.

module("Add Module");

test("Add should add 2 items", function () {
 var result = Calculator.add(1, 2);
 equal(result, 3, "Result of 1+2 should be 3");
});

test("Add should fail if one item is missing", function () {
 raises(function () {
  Calculator.add(1);
 }, "Incorrect number of arguments");
});


Tests are created by calling the test() function, which constructs a test case; the first parameter is a string that will be displayed in the result, and the second parameter is a callback function that contains our assertions. This callback function will get called once QUnit is run. Test cases can be organized into different modules by calling the module function.
Let’s have a look at the output if we browse to the created html file:
image


If you want to know more about the QUnit basics, I can recommend the following tutorial(http://net.tutsplus.com/tutorials/javascript-ajax/how-to-test-your-javascript-code-with-qunit/). But we should continue and have a look at the async testing functionality.
Async testing
In the calculator object I was testing before I had the following method to add two values:
that.add = function (a, b) {
        if (arguments.length != 2)
            throw new Error("The number of arguments is incorrect");
        return a + b;
    };


Let’s now add another method that doesn’t calculate the sum on the client but let the server do all the work:
 that.remoteAdd = function (a, b, completedHandler) {
        var post = $.ajax({
            url: "/Calculator/Add/",
            data: { a: a, b: b },
            type: "POST"
        });

        post.done(function (result) {
            completedHandler(result);
        });

        post.fail(function () {
            completedHandler('error');
        });
    };

This time I’m passing an extra argument; the completedHandler that will be invoked when the Ajax call has completed. Let’s first try to write the test case in a synchronous fashion:
  test("Remote add should also add 2 items", function () {
            var result = 0;

            Calculator.remoteAdd(1, 2, function (r) {
                result = r;
            });

            equal(result, 3, "Result of 1+2 should be 3");
        });



But if we run the test, it fails because the test execution completed before the Ajax call returns and the completedHandler is invoked:

image


To make this test pass, we’ll have to change it into an asynchronous test. QUnit provides us 2 helper functions for this:
  • stop(): allows you to pause the assertions for a specified time interval
  • start(): allows you to continue test execution
Let’s see these two functions in action:
  test("Remote add should also add 2 items", function () {
            var result = 0;
            //Wait 1 sec before looking at the results
            stop(1000);

            Calculator.remoteAdd(1, 2, function (r) {
                result = r;
                equal(result, 3, "Result of 1+2 should be 3");
                //Continue the test execution
                start();
            });
        });


Stop() will not stop the test execution but will postpone the assertion(the equal check in this case) until the time interval has expired. This gives the AJAX call enough time to get the result from the server and invoke the completedHandler.
image

Thursday, May 3, 2012

Copying reports from one Report Server to another.

Microsoft released the Reporting Services Migration tool. A tool that migrates reports and other artifacts from one report server to another report server. It can also be used as a backup and restore tool for Reporting Services. The tool is available both as a command line tool, a GUI and a powershell script.

Current features and limitations
  • You can use RSMigrationTool or RSMigrationUI to backup your native report server.
  • To restore or migrate the native server, run the Migration.ps1 from a PowerShell console.
  • Source and target server must be SQL Server Reporting Services 2008 R2 or later.
  • Source server
    • Source server must be native mode using Windows authentication. (MS is working on support for SharePoint integrated mode and other authentication schemes.)
    • Permissions and roles from source server are not backed up o Configuration in source server is not backed up.
    • Reports and other artifacts in deeply nested subfolders may not be backed up. This is due to Windows OS restriction on the maximum length for the full path of the backup files and folders. (MS is working towards a solution.)
    • Linked reports are not support in SharePoint mode, hence not backed up.
    • Database connection to source server catalog is made using Windows Integrated credentials of the user running the tool.
  • Target server
    • Target server must be SharePoint integrated mode. (MS is working on support for native mode.)
    • The web application must be using Windows classic authentication mode. (MS is working on support for other authentication schemes.)
    • Target server must be correctly configured. Target document library and folder must be created. For SSRS 2012, service application must be created and configured.
    • The owner of Reporting artifacts after migration is set to the user who performed migration. (MS is working towards a solution.)
    • Subscription owners are set after they are migrated. If the owner does not have CreateAlerts/ManagedAlerts permission, the operation will fail.
    • Report parts are not linked correctly to the Report. (MS is working towards a solution.) o Database connection to target server catalog is made using Windows Integrated credentials of the user running the tool.

Although the tool lacks some important features, I’m happy to see there finally is a tool that simplifies this process.

Visual Studio error: An error was encountered while opening associated documents the last time this solution was loaded.

Last week a colleague reported the following error when opening a solution in Visual studio:

“An error was encountered while opening associated documents the last time this solution was loaded. Document load is being skipped during this solution load in order to avoid that error.”

No idea what the root cause of this issue was, but the first trick you should try is to throw away your .suo file inside your Visual Studio solution directory. This file caches a lot of project information. Throwing it away isn’t a problem because Visual Studio will create a new one for you.

Helped me in a lot of scenario’s…

Wednesday, May 2, 2012

TF30027: Team Explorer encountered an error adding the document library.

A colleague got the following error when trying to add a new subfolder to the Documents folder in Team Explorer.

clip_image002

Although the error message doesn’t reveal a lot of information, solving this error is easy.

Probably the user doesn’t have the necessary rights to add a new Document Library in Sharepoint. So login on the Sharepoint site and check if the user has the "design" permission.

Tuesday, May 1, 2012

TFS 2010 Build: Where have my test results(.trx) gone?

Last week I had some trouble opening up a test results file from our build server. Every time I clicked on the link in the Build Report I got an error back. OK I said, let’s browse to the drop folder and have a look at the test results file(*.trx) directly. However I noticed that the Test Results folder is not copied to the drop location anymore. This is a change compared to TFS 2008 where the test results are available at the drop location.
So where are my test results than?
In TFS 2008 MSTest.exe used to copy the TRX file and other files to the drop location. In TFS 2010, the test results are uploaded to the Test Case Management server. Luckily the test result files are still created at the build location. So, if you log in to the build server, you can find the .trx file there. To simplify the process I added a custom activity to my build workflow that re-introduces the copy of the Test Result files to the drop location.