Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.






November 2010 - Posts

Quick introduction to Pex

PexPex and Moles is new testing and code analysis technology that is created by Microsoft Research. Pex is powerful tool that helps you analyze your code, detect error situations and generate parameterized unit tests. In this posting I will give you quick and illustrated overview of Pex.

For business use Pex requires MSDN Library subscription. For academic use it is free right now. You can download Pex and Moles from Pex and Moles homepage.

Pex generates unit tests to test your code on the fly. It analyzes paths in your code and checks for different constraints and tries different parameters with tests to break your code. Parameter values are not randomly generated but meaningfully selected. This means that Pex is not about flooding and finding bugs randomly. After code analysis and testing Pex shows you results in Visual Studio IDE.

Now let’s try to do something simple that illustrates how Pex works.

Primitive test class

Let’s create new Class Library project using Visual Studio and let’s create there class called calculate. Here is my class.

public class Calculate
    public static decimal Speed(decimal s, decimal t)
        return s / t;

If you look at this class you can see that method Speed() is easy to crash – just give zero as value to argument t. Now let’s see what Pex thinks about our class.

Analyzing code with Pex

To run Pex on our code we have to right click on project and select Run Pex from context menu.

Run Pex

Now you are asked for test framework.

Pex: Select a Test Framework

I selected nUnit but you can find also other frameworks there like Visual Studio tests and xUnit.

After clicking OK Pex starts analyzing and testing your code. It takes a little time so we have to wait a little bit.


Pex shows us analysis results in two windows: Pex Explorer and Pex Exploration Results. Pex Explorer is good if we have more classes and it we want to navigate between them and test results. Pex Explorer is very similar to windows we have seen when running tests on our code.

Pex Explorer

Pex Exploration Results window shows us Pex results in more detail.

Pex Exploration Results

If we click on some line the details pane is opened that gives us better overview about what Pex did in this point.

Pex Exploration Results: Details of test

In details windows we can also see test that Pex generated if we open details section.

As we can see then Pex discovered one more problematic situation – our code is not safe against overflows. In similar manner Pex is able to analyze more complex methods and gives us very good hints about weak sides of our code.


Pex is interesting tool that helps developers on analyzing code and generating parameterized unit tests. Pex is not about replacing tests or making them less important. Pex is about providing additional value to developers who are interested in their code quality and unit tests. Tests will never go away and Pex is here to help us find more tests we need to have to improve our code quality. Also you may consider Pex as helping tool that helps us on generating tests we want to add to our test libraries.

ASP.NET MVC: Comparing same view on ASP.NET and Razor view engine

I ported views of my ASP.NET MVC application from ASP.NET to Razor. Although Razor is very new it is very promising view engine because of shorter and cleaner syntax. In this posting I will show you same view on ASP.NET and Razor view engine. I like Razor one more but what do you think?

My contacts table on ASP.NET view engine is here. You can open both images on separate windows and switch between them to see differences.

Contacts index on ASP.NET

And here is the same view in Razor. Notice that ASP.NET MVC 3 RC has support for Razor syntax highlight. Click on image to view it at original size.

Contacts index on Razor

If you see these images at original size you see the effect.

For me Razor view is easier to read because there is less noise caused by template symbols. I think this view is not complex one. If there are more loops and conditionals in our view then I am sure ASP.NET version of it looks messier.

ASP.NET: How to avoid ArgumentNullException in StructureMap controller factory

I am using StructureMap as my IoC container. In my ASP.NET MVC web application I have controller factory based on StructureMap. I found interesting problem – when running my web application on development web server I get ArgumentNullException with every request to some controller action. In this posting I will describe why it is happening and how to avoid it.

Here is the early version of my controller factory. I found it from Shiju Varghese’s blog posting ASP.NET MVC Tip: Dependency Injection with StructureMap.

public class StructureMapControllerFactory : 
    protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType)
            var controller = ObjectFactory.GetInstance(controllerType);
            return controller as Controller;

Well… here’s the little gotcha. There is condition when controllerType is null. You can read more from Stack Overflow thread StructureMap error when invalid controller. ASP.NET development web server (and also IIS with wildcard mapping) handle all requests through ASP.NET handlers. One thing that is asked for every controller action by some browsers is favicon. As ASP.NET MVC cannot detect controller – there is no controller for favicon – the type of controller is null. So, we need a little bugfix to controller factory.

public class StructureMapControllerFactory : 
    protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType)
        if (controllerType == null)
            return null;
            var controller = ObjectFactory.GetInstance(controllerType);
            return controller as Controller;

You may say that it should be handled by routing and you are right – you can do it. But handling all types of requests through routing is not good idea. If you read Stack Overflow thread referred above you can see that same problem occurs if user makes typo to controller name when inserting URL to browser manually. My solution here is better because it handles all such cases when controller type is null and causes less errors to handle and log.

CodePlex supports Windows Live Writer!

I am documenting local community portal that is hosted in CodePlex. Wikis have always been annoying for me when it comes to creating a good content. So, I was preparing for boring evening full of wiki mark-up and messing with good format, manual image uploads etc. But CodePlex surprised me today – it’s wiki supports Windows Live Writer!

As tonight is not the last night when I am documenting my work I was specially glad I got this heavy boost to my documenting action. I will save a lot of time I think as I am pretty quick when I’m using Windows Live Writer. Take a look at the following screenshot.

CodePlex wiki page in Windows Live Writer
Click on image to see it at original size.

Yes, it is one of my CodePlex pages opened in Windows Live Writer. Cool! I think creating public documentation to CodePlex is now easier than ever. I hope that now devs have more motivation to write better documentation as it is way easier and less time consuming than before. I saw winnings in time after finishing to longer documentation chapters. Believe me – documenting is now fun in CodePlex!

How to get Live Writer connected to CodePlex?

Follow these simple steps (stolen from Using Windows Live Writer page from CodePlex):

  • add new blog account and select Other service as it’s type,
  • insert URL of your CodePlex project as address of new blog,
  • username and passwords are same you are using to log in to CodePlex,
  • don’t download layouts as it doesn’t work yet.

After last okay you are are ready to start writing documentation using Windows Live Writer.

NB! I am using Windows Live Writer 2011. After adding new blog account the new account is not displayed in ribbon dropdowns. If you also see something like this then close Windows Live Writer and run it again. For me it worked.

Content management tips and tricks

Here are some things I found useful to share – CodePlex wiki is not exactly the same thing as blog.

  • Unique titles are mandatory. Page titles must be unique because page title is practically primary key of wiki page. If you have already page with same title as your new one then select other title for your new text.
  • You can edit existing pages. If your Live Writer has no good old Open dialog available in mess called ribbon you can get this dialog opened easily – just press CTRL+O. Select your CodePlex page and Live Writer downloads titles directly from CodePlex. Select page and open it. You can save your changes by pushing Publish button on toolbar.
  • You can use images. Yes, you can insert images to your CodePlex wiki postings and you have to do nothing manually to get them online. Just press Publish after you are done with writing and your images go with your post.

If you want to document API-s or write code examples you can use different plugins suggested on CodePlex Live Writer page. If you don’t find plugin that fits your needs you can go to CodePlex, open some page in HTML view and click on Insert code snipet icon. Code inserting dialog makes syntax highlight for you.

CodePlex: Insert Code Snipet dialog
Click on image to see it at original size.

Paste your code to left area, select language and press Preview button. Now select all code from right area and paste it to Windows Live Writer. Not as elegant as using plugins but it works.


After couple of documentation pages I was amazed how fast I can move on with documenting when I don’t have to use this weird wiki mark-up and manual image uploads. Windows Live Writer is my killer tool when it goes to writing something for web. Now I can do also my CodePlex writing with Windows Live Writer and I can focus more on the quality of my documents. And this IS cool!

ASP.NET MVC 3: Updating controller factories to RC

With ASP.NET MVC 3 RC there is change in IControllerFactory interface. This interface includes new method called GetControllerSessionBehavior(). This method returns value from SessionStateBehavior enum. ASP.NET MVC uses this method to find out how to handle session for given controller.

If you don’t plan to do any advanced stuff with session state then the easiest way to get your controller factories work again is to add the following method to them.

public SessionStateBehavior GetControllerSessionBehavior
(RequestContext requestContext, string controllerName)
    return SessionStateBehavior.Default;

Now your controller factories should compile again.

Posted: Nov 23 2010, 03:25 AM by DigiMortal | with 3 comment(s)
Filed under: ,
SharePoint: Setting master page for publishing sites

I am upgrading local community portal from SharePoint Server 2007 to SharePoint Server 2010. I also have to write deployment scripts so other guys can also use our codebase. One thing my deployment script has to do is to force correct master pages to sites. There is one little trick you should know when setting master pages for publishing webs. Here’s how I got things work.

The problem

Publishing site have two master pages – one is custom master page that is used to show site for visitors and the other is system master page that is used with site settings etc. SharePoint publishing infrastructure allows webs to inherit master page settings from parent web. If you do something like this:

$web.CustomMasterUrl = "/_catalogs/masterpage/My.master"

then it sometimes works and sometimes it doesn’t.

How is master page inheritance defined?

SharePoint Publishing infrastructure extends SharePoint existing sites. Yes, it extends, it doesn’t replace anything. If we need to keep custom information about web we have to use web’s properties collection. Let’s see what we have there.

__InheritsMasterUrl:  True
vti_defaultlanguage:  en-us
vti_approvallevels:  Approved Rejected Pending\ Review
__ImagesListId:  a20437ed-9fe4-41f1-8e58-7a41218f7928
__PublishingFeatureActivated:  True
vti_associategroups:  8;4;4;7;6;9;10;11;12;13;14
NavigationPropertiesSet:  True
vti_customuploadpage:  /_layouts/UploadEx.aspx
vti_filedialogpostprocessorid:  {f68e6d4e-383a-4c8d-ba4d-d2139f164281}
__DocumentsListId:  a5c43bc5-92f3-4e3e-ae9d-91228756bc53
__InheritsCustomMasterUrl:  True
__CurrentNavigationIncludeTypes:  3
vti_associatevisitorgroup:  7
__InheritWebTemplates:  True
__NavigationShowSiblings:  True
__GlobalNavigationIncludeTypes:  3
__PageLayouts:  __inherit
vti_associateownergroup:  6
__DefaultPageLayout:  __inherit
__InheritsThemedCssFolderUrl:  True
__NewPageUrlToken:  __inherit
__InheritsAlternateCssUrl:  True
__PagesListId:  5a169de8-6d00-444a-882a-3a47f10422fd
vti_associatemembergroup:  8
vti_categories:  Travel Expense\ Report Business Competition Goals/Objectives Ideas Miscellaneous Waiting VIP In\ Process Planning Schedule

Okay, seems like we are on our way. Take a look at the property that I made bold. This property affects the checkbox selection on the following screenshot fragment (taken from master page settings screen).

Master page inheritance settings

You may set custom master to whatever you want but if you don’t change inheritance rule too then SharePoint still uses master page of parent web.

My solution

Here is my solution and that works for me. Besides setting master page for web I also set __InheritsCustomMasterUrl to False.

$site = new-object Microsoft.SharePoint.SPSite("$siteUrl")
$web = $site.OpenWeb("/news/blogs/")

# break custom master inheritance and set correct master
$web.AllProperties["__InheritsCustomMasterUrl"] = "False"
$web.CustomMasterUrl = "/_catalogs/masterpage/My.master"


One thing more to mention – this is PowerShell script here. Don’t be confused! :)


As with many other things the behavior of SharePoint is unintuitive. You can find a lot of different sources from web where people suggest you to set custom master page and they don’t know that it doesn’t work without additional cool porn I just described here. Changing properties like this directly is technical design flaw in SharePoint and things like these should be done through PublishingWeb or another class one day when SharePoint API evolves.

Posted: Nov 23 2010, 02:53 AM by DigiMortal | with 2 comment(s)
Filed under:
Creating Twitpic client using ASP.NET and OData

Open Data Protocol (OData) is one of new HTTP based protocols for updating and querying data. It is simple protocol and it makes use of other protocols like HTTP, ATOM and JSON. One of sites that allows to consume their data over OData protocol is Twitpic – the picture service for Twitter. In this posting I will show you how to build simple Twitpic client using ASP.NET.

Source code

You can find source code of this example from Visual Studio 2010 experiments repository at GitHub.

Source code @ GitHub Source code repository

Simple image editor belongs to Experiments.OData solution, project name is Experiments.OData.TwitPicClient.

Sample application

My sample application is simple. It has some usernames on left side that user can select. There is also textbox to filter images. If user inserts something to textbox then string inserted to textbox is searched from message part of pictures. Results are shown like on the following screenshot.

My twitpic client
Click on image to see it at original size.

Maximum number of images returned by one request is limited to ten. You can change the limit or remove it. It is hear just to show you how queries can be done.

Querying Twitpic

I wrote this application on Visual Studio 2010. To get Twitpic data there I did nothing special – just added service reference to Twitpic OData service that is located at Visual Studio understands the format and generates all classes for you so you can start using the service immediately.

Now let’s see the how to query OData service. This is the Page_Load method of my default page. Note how I built LINQ query step-by-step here.

protected override void OnLoad(EventArgs e)
    var uri = new Uri("");
    var user = Request.QueryString["user"];
    if (string.IsNullOrWhiteSpace(user))
        user = "gpeipman";
    var client = new TwitpicData.TwitpicData(uri);
    client.IgnoreMissingProperties = false;
    client.IgnoreResourceNotFoundException = false;
    var images =  from u in client.Users
                  from i in u.Images
                  where u.UserName == user                          
                  select i;
    if (!string.IsNullOrWhiteSpace(filterField.Text))
        var searchString = filterField.Text.ToLower();
        images = from i in images
                 where i.Message.ToLower().Contains(searchString)
                 select i;
    images = images.OrderByDescending(i => i.Timestamp);
    picsByLabel.Text = user;
    imagesRepeater.DataSource = images.Take(10);

My query is built by following steps:

  • create query that joins user and images and add condition for username,
  • if search textbox was filled then add search condition to query,
  • sort data by timestamp to descending order,
  • make query to return only first ten results.

Now let’s see the OData query that is sent to Twitpic OData service. You can click on image to see it at original size.

My OData query in Fiddler2
Click on image to see it at original size.

This is the query that our service client sent to OData service (I searched belgrade from my pictures):


If you look at the request string you can see that all conditions I set through LINQ are represented in this URL. The URL is not very short but it has simple syntax and it is easy to read. Answer to our query is pure XML that is mapped to our object model when answer is arrived. There is nothing complex as you can see.


Getting our Twitpic client work and done was extremely simple task. We did nothing special – just added reference to service and wrote one simple LINQ query that we gave to repeater that shows data. As we saw from monitoring proxy server report then the answer is a little bit messy but still easy XML that we can read also using some XML library if we don’t have any better option. You can find more OData services from OData producers page.

Sinergija10 - We were all in (Beograd, Srbija)

Sinergija10 - We're all inThis week I visited conference called Sinergija10 that took place in Belgrade, Serbia. Thanks to Microsoft Estonia who organized my trip there! Sinergija10 was very good surprise to me and I am really considering it as one of Microsoft’s top conferences in Europe. Yes, I think it is at least same cool conference as TechEd EMEA. Here is my overview of event and some of my thoughts about Sinergija and communities in area. For guys who are planning to visit Europe events I think Sinergija is event to visit for sure.

What is Sinergija?

Sinergija is conference about Microsoft technologies. First Sinergija took place six years ago. Although Sinergija is Serbian event there were some sessions in english. The other sessions had slides in english so if you don’t speak serbian you can still understand what’s going on. Speakers were great and beside local ones there were guys like Stephen Forte, Dean Vitner and Richard Campbell. Also some names known maybe more in Europe like Rafal Luckawiecki and Doncho Angelov.

I visited about ten sessions and only one of them was way too easy and primitive for promised level. All the other sessions were pretty strong and really interesting. I have to say that I got more from these sessions than I was able to get in TechEd. And this is one of the reasons I consider Sinergija as very good conference. If you are thinking about events to visit in Europe then make sure you try out Sinergija – it rocks very hard.

The event took place in Belgrade, Serbia. There is conference center called Sava Centar in Belgrade. It is not far from city center and old town. I was hosted in Continental Beograd hotel that is near conference center. You can go from hotel to conference center through passage way and if weather is bad you don’t have to go out from buildings. So practically you don’t have any longer walks between conference place and hotel. That’s very convenient and saves you a lot of time.

Continental Hotel Beograd

And here is the gift by organizers. This bag is pretty strong one and it is very convenient to carry even if it is heavy and full of stuff like laptop, some books and some more technology I usually take with me when travelling.

Sinergija10 bag

Why is Balkans cool area?

Balkans is cool because all countries there are on the fast development. These countries are different than rich and expensive Euro zone countries. Prices are very good and you can meet people who you don’t see in TechEd. I like balkans communities because they are active ones – there are a lot of great developers you can communicate with and for me it was very interesting to talk with these guys.

Here, in Estonia, we don’t have something so mind-blowing guys who are eager to talk with other guys on development topics. And what’s more cool – if you have questions then ask – you are totally surprised how much good information and advices these guys are able to give you.

Belgrade is nice city that is not ruined by industrial revolution time awful buildings. There are those Soviet time buildings but not so much. I saw there cool new architecture, very well planned business areas with nice houses. This picture is taken near hotel. There is nice new block of houses that look very nice.

Nice new buildings in Belgrade

Belgrade old town is beautiful and people seem glad and cool. I also suggest you to visit other cities and countries in this area. And if you go there then try to make contacts with local developers before so you can maybe participate in some local event too.

Sessions and networking at Sinergija

Sessions are not only for developers but also for IT-PROs. Here is the agenda of Sinergija10. Click on days at top of agenda to see what sessions were at what day. I think this agenda speaks more than my words here. I visited the following sesssions:

  • Technical keynote (John Craddock, Rafal Lukawiecki, Saša Juric, Wim Dierickx)
  • Windows Phone 7 Application Life Cycle (Doncho Angelov)
  • Team Development with Microsoft Scrum 1.0 (Doncho Angelov)
  • Let's talk Scrum with the Scrum guys (Stephen Forte)
  • Extending Visual Studio 2010 Code Editor using Facebook API (Tomislav Bronzin)
  • The Scaling Habits of ASP.NET Applications (Richard Campbell)
  • Deep Dive into Razor Extensibility (Sonja Keserovic)
  • The world of Model-View-ViewModel (Miroslav Miroslavov)
  • SQL Server performance problems first aid kit (Dean Vitner)
  • Unit testing solid fundamentals (Milan Vukoje)
  • Advanced Unit Testing – real life examples and mistakes (Milan Vukoje)
  • Pex and Moles (Boban Mikšin)

Specially strong ones were sessions by Dean Vitner and Richard Campbell. And, of course, Stephen Forte with his Scrum topics. He is also on following photo.

Stephen Forte @ Sinergija10

We had also two events at evenings. There was CEE region MVP-s meeting and Sinergija10 party with very loud music and free drinks. Both of these events were good places to communicate with other developers and find new contacts. At least I found some great new contacts that are interesting to me.


If God, Fate, Microsoft or other forces give me a chance to go back there I will go for sure. And also I would like to visit developer events in Bulgarian and Ukraine. Believe me, it is worth to go there and meet these people. It was very good for me to see also all these cool MVP-s out there and U also want to say thanks to our MVP lead Alessandro Teglia for cool MVP meeting we had there. I am very happy I got chance to visit Sinergija and I hope I will be back there next year.

Free e-book: Moving to Visual Studio 2010

moving-to-microsoft-visual-studio-2010Those who are still using older versions of Visual Studio may find the free e-book “Moving to Microsoft Visual Studio 2010” useful when deciding if it is time to move to Visual Studio 2010 or not. The book is written by Ken Haines, Pascal Paré and Patrice Pelland who all work in Microsoft Consumer and Online Division.

I moved to Visual Studio 2010 as soon as I got the first version of it and if I’m correct it was even before first public beta. After couple of days playing with Visual Studio 2010 it was clear to me that I want to stay on this platform and I will start using it in real projects as soon as first stable version is out. But there are still a lot of guys who still plan the move or who are thinking about it. I hope this book will help you make your decision.

Table of Contents

I Moving from Microsoft Visual Studio 2003 to Visual Studio 2010
1. From 2003 to 2010: Business Logic and Data
2. From 2003 to 2010: Designing the Look and Feel
3. From 2003 to 2010: Debugging an Application
4. From 2003 to 2010: Deploying an Application

II Moving from Microsoft Visual Studio 2005 to Visual Studio 2010
5. From 2005 to 2010: Business Logic and Data
6. From 2005 to 2010: Designing the Look and Feel
7. From 2005 to 2010: Debugging an Application

III Moving from Microsoft Visual Studio 2008 to Visual Studio 2010
8. From 2008 to 2010: Business Logic and Data
9. From 2008 to 2010: Designing the Look and Feel
10. From 2008 to 2010: Debugging an Application

How to dump object properties

I needed a quick’n’dirty way to inspect objects returned from external source. I wrote simple object properties dumping mechanism you can use to investigate unknown objects. It is really quick and really dirty.

using System.Collections.Generic;
using System.IO;
namespace UlmeTeenused
    public class ObjectDump
        public static void Write(TextWriter writer, object obj)
            if (obj == null)
                writer.WriteLine("Object is null");
            writer.Write("Hash: ");
            writer.Write("Type: ");
            var props = GetProperties(obj);
            if (props.Count > 0)
            foreach (var prop in props)
                writer.Write(": ");
        private static Dictionary<string, string> GetProperties(object obj)
            var props = new Dictionary<string, string>();
            if (obj == null)
                return props;
            var type = obj.GetType();
            foreach (var prop in type.GetProperties())
                var val = prop.GetValue(obj, new object[] { });
                var valStr = val == null ? "" : val.ToString();
                props.Add(prop.Name, valStr);
            return props;

If you are using console application you can create properties dump using the following code.


The result is something like this.

Object properties dump

And we are done. This code is not intended to use in live environments. Use it when you are investigating different mysteries created by someone else. :)

Posted: Nov 02 2010, 04:58 AM by DigiMortal | with 9 comment(s)
Filed under:
More Posts Next page »