Gunnar Peipman's ASP.NET blog

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






March 2010 - Posts

Quick example: why coding standards must be in place

One quick example why coding standards must be in place. Take a look at the following code – property names are changed but not anything else.

public string Property1 { get; set; }


public string Property2






public string Property3


    get; set;


And yes – it is real-world example.

Windows Phone 7 Series development: reading RSS feeds

Windows Phone 7 Series One limitation on Windows Phone 7 is related to System.Net namespace classes. There is no convenient way to read data from web. There is no WebClient class. There is no GetResponse() method – we have to do it all asynchronously because compact framework has limited set of classes we can use in our applications to communicate with internet. In this posting I will show you how to read RSS-feeds on Windows Phone 7.

NB! This is my draft code and it may contain some design flaws and some questionable solutions. This code is intended to use as test-drive for Windows Phone 7 CTP developer tools and I don’t suppose you are going to use this code in production environment.

Current state of my RSS-reader

My Windows Phone 7 RSS-readerCurrently my RSS-reader for Windows Phone 7 is very simple, primitive and uses almost all defaults that come out-of-box with Windows Phone 7 CTP developer tools.

My first goal before going on with nicer user interface design was making RSS-reading work because instead of convenient classes from .NET Framework we have to use very limited classes from .NET Framework CE. This is why I took the reading of RSS-feeds as my first task.

There are currently more things to solve regarding user-interface. As I am pretty new to all this Silverlight stuff I am not very sure if I can modify default controls easily or should I write my own controls that have better look and that work faster.

The image on right shows you how my RSS-reader looks like right now. Upper side of screen is filled with list that shows headlines from this blog. The bottom part of screen is used to show description of selected posting. You can click on the image to see it in original size.

In my next posting I will show you some improvements of my RSS-reader user interface that make it look nicer. But currently it is nice enough to make sure that RSS-feeds are read correctly.

FeedItem class

As this is most straight-forward part of the following code I will show you RSS-feed items class first. I think we have to stop on it because it is simple one.

public class FeedItem


    public string Title { get; set; }

    public string Description { get; set; }

    public DateTime PublishDate { get; set; }

    public List<string> Categories { get; set; }

    public string Link { get; set; }


    public FeedItem()


        Categories = new List<string>();




RssClient takes feed URL and when asked it loads all items from feed and gives them back to caller through ItemsReceived event. Why it works this way? Because we can make responses only using asynchronous methods. I will show you in next section how to use this class.

Although the code here is not very good but it works like expected. I will refactor this code later because it needs some more efforts and investigating. But let’s hope I find excellent solution. :)

public class RssClient


    private readonly string _rssUrl;


    public delegate void ItemsReceivedDelegate(RssClient client, IList<FeedItem> items);

    public event ItemsReceivedDelegate ItemsReceived;


    public RssClient(string rssUrl)


        _rssUrl = rssUrl;



    public void LoadItems()


        var request = (HttpWebRequest)WebRequest.Create(_rssUrl);

        var result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);



    void ResponseCallback(IAsyncResult result)


        var request = (HttpWebRequest)result.AsyncState;

        var response = request.EndGetResponse(result);


        var stream = response.GetResponseStream();

        var reader = XmlReader.Create(stream);

        var items = new List<FeedItem>(50);


        FeedItem item = null;

        var pointerMoved = false;


        while (!reader.EOF)


            if (pointerMoved)


                pointerMoved = false;




                if (!reader.Read())




            var nodeName = reader.Name;

            var nodeType = reader.NodeType;


            if (nodeName == "item")


                if (nodeType == XmlNodeType.Element)

                    item = new FeedItem();

                else if (nodeType == XmlNodeType.EndElement)

                    if (item != null)



                        item = null;






            if (nodeType != XmlNodeType.Element)



            if (item == null)




            var nodeValue = reader.ReadElementContentAsString();

            // we just moved internal pointer

            pointerMoved = true;


            if (nodeName == "title")

                item.Title = nodeValue;

            else if (nodeName == "description")

                item.Description =  Regex.Replace(nodeValue,@"<(.|\n)*?>",string.Empty);

            else if (nodeName == "feedburner:origLink")

                item.Link = nodeValue;

            else if (nodeName == "pubDate")


                if (!string.IsNullOrEmpty(nodeValue))

                    item.PublishDate = DateTime.Parse(nodeValue);


            else if (nodeName == "category")




        if (ItemsReceived != null)

            ItemsReceived(this, items);



This method is pretty long but it works. Now let’s try to use it in Windows Phone 7 application.

Using RssClient

And this is the fragment of code behing the main page of my application start screen. You can see how RssClient is initialized and how items are bound to list that shows them.

public MainPage()




    SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

    listBox1.Width = Width;


    var rssClient = new RssClient("");

    rssClient.ItemsReceived += new RssClient.ItemsReceivedDelegate(rssClient_ItemsReceived);




void rssClient_ItemsReceived(RssClient client, IList<FeedItem> items)




        listBox1.ItemsSource = items;




As you can see it was not very hard task to read RSS-feed and populate list with feed entries. Although we are not able to use more powerful classes that are part of full version on .NET Framework we can still live with limited set of classes that .NET Framework CE provides.

Windows Phone 7 Series development: first impressions

After hard week in work I got some free time to play with Windows Phone 7 CTP developer tools. Although my first test application is still unfinished I think it is good moment to share my first experiences to you. In this posting I will give you quick overview of Windows Phone 7 developer tools from developer perspective.

If you are familiar with Visual Studio 2010 then you will feel comfortable because Windows Phone 7 CTP developer tools base on Visual Studio 2010 Express.

Project templates

There are five project templates available. Three of them are based on Silverlight and two on XNA Game Studio:

  1. Windows Phone Application (Silverlight)
  2. Windows Phone List Application (Silverlight)
  3. Windows Phone Class Library (Silverlight)
  4. Windows Phone Game (XNA Game Studio)
  5. Windows Phone Game Library (XNA Game Studio)

Currently I am writing to test applications. One of them is based on Windows Phone Application and the other on Windows Phone List Application project template. After creating these projects you see the following views in Visual Studio.

Windows Phone Application
Windows Phone Application. Click on image to enlarge.

Windows Phone List Application
Windows Phone List Application. Click on image to enlarge. 

I suggest you to use some of these templates to get started more easily.

Windows Phone 7 emulator

Windows Phone 7 Emulator You can run your Windows Phone 7 applications on Windows Phone 7 emulator that comes with developer tools CTP. If you run your application then emulator is started automatically and you can try out how your application works in phone-like emulator.

You can see screenshot of emulator on right. Currently there is opened Windows Phone List Application as it is created by default. Click on image to enlarge it.

Emulator is a little bit slow and uncomfortable but it works pretty well. This far I have caused only couple of crashes during my experiments. In these cases emulator works but Visual Studio gets stuck because it cannot communicate with emulator.

One important note. Emulator is based on virtual machine although you can see only phone screen and options toolbar. If you want to run emulator you must close all virtual machines running on your machine and run Visual Studio 2010 as administrator. Once you run emulator you can keep it open because you can stop your application in Visual Studio, modify, compile and re-deploy it without restarting emulator.

Designing user interfaces

Windows Phone CTP ToolboxYou can design user interface of your application in Visual Studio. When you open XAML-files it is displayed in window with two panels. Left panel shows you device screen and works as visual design environment while right panel shows you XAML mark-up and let’s you modify XML if you need it. As it is one of my very first Silverlight applications I felt more comfortable with XAML editor because property names in property boxes of visual designer confused me a little bit.

Designer panel is not very good because it is visually hard to follow. It has black background that makes dark borders of controls very hard to see. If you have monitor with very high contrast then it is may be not a real problem. I have usual monitor and I have problem. :)

Putting controls on design surface, dragging and resizing them is also pretty painful. Some controls are drawn correctly but for some controls you have to set width and height in XML so they can be resized. After some practicing it is not so annoying anymore.

On the right you can see toolbox with some controllers. This is all you get out of the box. But it is sufficient to get started. After getting some experiences you can create your own controls or use existing ones from other vendors or developers.

If it is your first time to do stuff with Silverlight then keep Google open – you need it hard. After getting over the first shock you get the point very quickly and start developing at normal speed. :)

Writing source code

Writing source code is the most familiar part of this action. Good old Visual Studio code editor with all nice features it has. But here you get also some surprises:

  1. The anatomy of Silverlight controls is a little bit different than the one of user controls in web and forms projects.
  2. Windows Phone 7 doesn’t run on full version of Windows (I bet it is some version of Windows CE or something like this) then there is less system classes you can use.
  3. Some familiar classes have less methods that in full version of .NET Framework and in these cases you have to write all the code by yourself or find libraries or source code from somewhere.

These problems are really not so much problems than limitations and you get easily over them.


Windows Phone 7 CTP developer tools help you do a lot of things on Windows Phone 7. Although I expected better performance from tools I think that current performance is not a problem. This far my first test project is going very well and Google has answer for almost every question.

Windows Phone 7 is mobile device and therefore it has less hardware resources than desktop computers. This is why toolset is so limited. The more you need memory the more slower is device and as you may guess it needs the more battery. If you are writing apps for mobile devices then make your best to get your application use as few resources as possible and act as fast as possible.

Exam 70-541 - TS: Microsoft Windows SharePoint Services 3.0 - Application Development

Today I passed Microsoft exam 70-541: Microsoft Windows SharePoint Services 3.0 - Application Development. This exam gives you MCTS certificate. In this posting I will talk about the exam and also give some suggestions about books to read when preparing for exam.

About exam

This exam was good one I think. The questions were not hard and also not too easy. Just enough to make sure you really know what you do when working with SharePoint. Or at least to make sure you how things work. After couple of years active SharePoint coding this exam needs no additional preparation. The questions covered very different topics like alerts, features, web parts, site definitions, event receivers, workflows, web services and deployments.

There are 59 questions in the exam (this information is available in internet) and you have time a little bit more than two hours. It took me about 40 minutes to get questions answered and reviewed. I strongly suggest you to study the parts of WSS 3.0 you don’t know yet and write some code to find out how to use these things through SharePoint API.

Good reading

Inside Microsoft Windows SharePoint Services 3.0 For guys with less experience there are some good books to suggest. Take one or both of these books because there are no official study materials or training kits available for this exam.

One of my colleagues who is less experienced than me suggested Inside Microsoft Windows SharePoint Services 3.0 by Ted Pattison and Daniel Larson. He told me that he found this book most useful for him to pass this exam.

Developer's Guide to the Windows SharePoint Services v3 PlatformWhen I started with SharePoint Services 3.0 my first book was Developer’s Guide To The Windows SharePoint Services v3 Platform by Todd C. Bleeker. It helped me getting started and later it was my main handbook for some time.

Of course, there are many other good books and I suggest you to take what you find. Of course, before buying something I suggest you to discuss with guys who have read the book before. And make sure you mention that you are preparing for exam.


If you are experienced SharePoint developer then this exam needs no preparation. Okay, some preparation is always good but if you don’t have time you are still able to pass this exam. If you are not experienced SharePoint developer then study before taking this exam – it is not easy stuff for novices. But if you pass this exam you can proudly say – yes, I know something about SharePoint! :)

Posted: Mar 25 2010, 10:56 PM by DigiMortal | with 3 comment(s)
Filed under:
Entity Framework 4.0: Creating objects of correct type when using lazy loading

In my posting about Entity Framework 4.0 and POCOs I introduced lazy loading in EF applications. EF uses proxy classes for lazy loading and this means we have new types that come and go dynamically in runtime. We don’t have these types available when we write code but we cannot forget that EF may expect us to use dynamically generated types. In this posting I will give you simple hint how to use correct types in your code.

The background of lazy loading and proxy classes

As a first thing I will explain you in short what is proxy class. Business classes when designed correctly have no knowledge about their birth and death – they don’t know how they are created and they don’t know how their data is persisted. This is the responsibility of object runtime.

When we use lazy loading we need a little bit different classes that know how to load data for properties when code accesses the property first time. As we cannot add this functionality to our business classes (they may be stored through more than one data access technology or by more than one Data Access Layer (DAL)) we create proxy classes that extend our business classes. If we have class called Product and product has lazy loaded property called Customer then we need proxy class, let’s say ProductProxy, that has same public signature as Product so we can use it INSTEAD OF product in our code.

ProductProxy overrides Customer property. If customer is not asked then customer is null. But if we ask for Customer property then overridden property of ProductProxy loads it from database. This is how lazy loading works.

Problem – two types for same thing

As lazy loading may introduce dynamically generated proxy types we don’t know in our application code which type is returned. We cannot be sure that we have Product not ProductProxy returned. This leads us to the following question: how can we create Product of correct type if we don’t know the correct type? In EF solution is simple.

Solution – use factory methods

If you are using repositories and you are not using factories (imho it is pretty pointless with mapper) you can add factory methods to your EF based repositories. Take a look at this class.

public class Event


    public int ID { get; set; }
    public string Title { get; set; }
    public string Location { get; set; }
    public virtual Party Organizer { get; set; }

    public DateTime Date { get; set; }


We have virtual member called Organizer. This property is virtual because we want to use lazy loading on this class so Organizer is loaded only when we ask it.

EF provides us with method called CreateObject<T>(). CreateObject<T>() is member of ObjectContext class and it creates the object based on given type. In runtime proxy type for Event is created for us automatically and when we call CreateObject<T>() for Event it returns as object of Event proxy type.

The factory method for events repository is as follows.

public Event CreateEvent()


    var evt = _context.CreateObject<Event>();

    return evt;


And we are done. Instead of creating factory classes we created factory methods that guarantee that created objects are of correct type.


Although lazy loading introduces some new objects we cannot use at design time because they live only in runtime we can write code without worrying about exact implementation type of object. This holds true until we have clean code and we don’t make any decisions based on object type. EF4.0 provides us with very simple factory method that create and return objects of correct type. All we had to do was adding factory methods to our repositories.

Advanced donut caching: using dynamically loaded controls

Yesterday I solved one caching problem with local community portal. I enabled output cache on SharePoint Server 2007 to make site faster. Although caching works fine I needed to do some additional work because there are some controls that show different content to different users. In this example I will show you how to use “donut caching” with user controls – powerful way to drive some content around cache.

About donut caching

Donut caching means that although you are caching your content you have some holes in it so you can still affect the output that goes to user. By example you can cache front page on your site and still show welcome message that contains correct user name.

To get better idea about donut caching I suggest you to read ScottGu posting Tip/Trick: Implement "Donut Caching" with the ASP.NET 2.0 Output Cache Substitution Feature.

Basically donut caching uses ASP.NET substitution control. In output this control is replaced by string you return from static method bound to substitution control. Again, take a look at ScottGu blog posting I referred above.


Yeah, hello, Scott! :) If you look at Scott’s example it is pretty plain and easy by its output. All it does is it writes out current user name as string. Here are examples of my login area for anonymous and authenticated users:

My anonymous log-in control   My authenticated log-in control

It is clear that outputting mark-up for these views as string is pretty lame to implement in code at string level. Every little change in design will end up with new version of controls library because some parts of design “live” there.

Solution: using user controls

I worked out easy solution to my problem. I used cache substitution and user controls together. I have three user controls:

  • LogInControl – this is the proxy control that checks which “real” control to load.
  • AnonymousLogInControl – template and logic for anonymous users login area.
  • AuthenticatedLogInControl – template and logic for authenticated users login area. This is the control we render for each user separately because it contains user name and user profile fill percent.

Anonymous control is not very interesting because it is only about keeping mark-up in separate file. Interesting parts are LogInControl and AuthenticatedLogInControl.

Creating proxy control

The first thing was to create control that has substitution area where “real” control is loaded. This proxy control should also be available to decide which control to load. The definition of control is very primitive.

<%@ Control EnableViewState="false" Inherits="MyPortal.Profiles.LogInControl" %>
<asp:Substitution runat="server" MethodName="ShowLogInBox" />

But code is a little bit tricky. Based on current user instance we decide which login control to load. Then we create page instance and load our control through it. When control is loaded we will call DataBind() method. In this method we evaluate all fields in loaded control (it was best choice as Load and other events will not be fired). Take a look at the code.

public static string ShowLogInBox(HttpContext context)


    var user = SPContext.Current.Web.CurrentUser;

    string controlName;


    if (user != null)

        controlName = "AuthenticatedLogInControl.ascx";


        controlName = "AnonymousLogInControl.ascx";


    var path = "~/_controltemplates/" + controlName;

    var output = new StringBuilder(10000);


    using(var page = new Page())

    using(var ctl = page.LoadControl(path))

    using(var writer = new StringWriter(output))

    using(var htmlWriter = new HtmlTextWriter(writer))





    return output.ToString();


When control is bound to data we ask to render it its contents to StringBuilder. You need to implement your data binding logic in DataBind() method override. Now we have the output of control as string and we can return it from our method. Of course, notice how correct I am with resources disposing. :)

The method that returns contents for substitution control is static method that has no connection with control instance because hen page is read from cache there are no instances of controls available.


As you saw it was not very hard to use donut caching with user controls. Instead of writing mark-up of controls to static method that is bound to substitution control we can still use our user controls.

Entity Framework 4.0: Optimal and horrible SQL

Lately I had Entity Framework 4.0 session where I introduced new features of Entity Framework. During session I found out with audience how Entity Framework 4.0 can generate optimized SQL. After session I also showed guys one horrible example about how awful SQL can be generated by Entity Framework. In this posting I will cover both examples.

Optimal SQL

Before going to code take a look at following model. There is class called Event and I will use this class in my query.

My events model

Here is the LINQ To Entities query that uses small anonymous type.

var query = from e in _context.Events

            select new { Id = e.Id, Title = e.Title };


Running this code gives us the following SQL.

    [Extent1].[event_id] AS [event_id], 
    [Extent1].[title] AS [title] 
FROM [dbo].[events] AS [Extent1]

This is really small – no additional fields in SELECT clause. Nice, isn’t it?

Horrible SQL

Ayende Rahien blog shows us darker side of Entiry Framework 4.0 queries. You can find comparison betwenn NHibernate, LINQ To SQL and LINQ To Entities from posting What happens behind the scenes: NHibernate, Linq to SQL, Entity Framework scenario analysis. In this posting I will show you the resulting query and let you think how much better it can be done.

Horrible SQL from Ayende Rahien blog

Well, it is not something we want to see running in our servers. I hope that EF team improves generated SQL to acceptable level before Visual Studio 2010 is released.

There is also morale of this example: you should always check out the queries that O/R-mapper generates. Behind the curtains it may silently generate queries that perform badly and in this case you need to optimize you data querying strategy.


Entity Framework 4.0 is new product with a lot of new features and it is clear that not everything is 100% super in its first release. But it still great step forward and I hope that on 12.04.2010 we have new promising O/R-mapper available to use in our projects. If you want to read more about Entity Framework 4.0 and Visual Studio 2010 then please feel free to follow this link to list of my Visual Studio 2010 and .NET Framework 4.0 postings.

Exam 70-448 - TS: Microsoft SQL Server 2008, Business Intelligence Development and Maintenance

The another exam I passed was 70-448 - TS: Microsoft SQL Server 2008, Business Intelligence Development and Maintenance. This exam covers Business Intelligence (BI) solutions development and maintenance on SQL Server 2008 platform. It was not easy exam, but if you study then you can do it.

70-448-self-paced-training-kit To get prepared for 70-488 it is strongly recommended to read self-paced training kit and also make through all examples it contains. If you don’t have strong experiences on Microsoft BI platform and SQL Server then this exam is hard to pass when you just go there and hope to pass somehow. Self-paced training kit is interesting reading and you learn a lot of new stuff for sure when preparing for exam.

Questions in exam are divided into topics as follows:

Exam 70-448 gives you Microsoft Certified Technology Specialist certificate.

Exam 70-630 - TS: Microsoft Office SharePoint Server 2007, Configuring

It has been really quiet here but I wasted no time. I passed exam 70-630 - TS: Microsoft Office SharePoint Server 2007, Configuring and in this posting I will give you a short overview of this very-very easy exam.

 Inside Microsoft® Office SharePoint® Server 2007 If you are not new to SharePoint Server 2007 and you have some development experiences then this is the easiest exam from Microsoft you have ever seen. There are 51 questions in this exam and two or four of them were not familiar to me. I took me about one hour to prepare for this exam and I got 964 of 1000.

Okay, I have some years of experience as SharePoint developer but these questions seemed still too easy for me to be real. I mean based on this exam you cannot accurately say if somebody is able to configure SharePoint Server or not. I think this exam should be very easy also to SharePoint Server administrators who have at least some experience with supporting and maintaining production systems running on SharePoint Server 2007.

Those who does not feel strong on SharePoint Server configuring my read a book suggested by Microsoft Learning site: Inside Microsoft® Office SharePoint® Server 2007.

Exam 70-630 gives you Microsoft Certified Technology Specialist certificate

Posted: Mar 13 2010, 05:16 PM by DigiMortal | with 4 comment(s)
Filed under:
Who is code wanderer?

In every area of life there are people with some bad habits or misbehaviors that affect the work process. Software development is also not free of this kind of people. Today I will introduce you code wanderer.

Who is code wanderer?

Code wandering is more like bad habit than serious diagnose. Code wanderers tend to review and “fix” source code in files written by others. When code wanderer has some free moments he starts to open the code files he or she has never seen before and starts making little fixes to these files.

Why is code wanderer dangerous?

These fixes seem correct and are usually first choice to do when considering nice code. But as changes are made by coder who has no idea about the code he or she “fixes” then “fixing” usually ends up with messing up working code written by others. Often these “fixes” are not found immediately because they doesn’t introduce errors detected by compilers. So these “fixes” find easily way to production environments because there is also very good chance that “fixed” code goes through all tests without any problems.

How to stop code wanderer?

The first thing is to talk with person and explain him or her why those changes are dangerous. It is also good to establish rules that state clearly why, when and how can somebody change the code written by other people. If this does not work it is possible to isolate this person so he or she can post his or her changes to code repository as patches and somebody reviews those changes before applying them.

More Posts Next page »