Brendan Enrick

Daily Software Development

String Formatting BoundFields in Silverlight

Hi my name is Brendan E. While working with a Bindable Silverlight control I ran into a little bit of trouble because I have a dependence commonly found among Visual Studio developers. I am addicted to intellisense. When a property isn’t in intellisense I make the failing assumption that it does not exist.

So even though I have posted specifically about how we developers should be smart enough to know that we can’t always trust intellisense, I still make the mistake of trusting it.

I am binding to a control and it slipped my mind to use the DataFormatString property, because it didn’t show up in intellisense for me. So of course I look around for what else I might use. I bing a few times about what I am trying to do. When I find the answer I feel like an idiot once again. This must be how all addicts feel. I just need my intellisense.

So I was trying to format my bound field as a percentage. To do that I just needed to add the following code.



Hooray! I’ve got working code now. So I repeat again. Don’t trust intellisense. Just because it says it isn’t there doesn't mean it isn’t there.

Transactional Data Persistence with OpenAccess

OpenAccess is an Object Relational Mapper (ORM) from Telerik, and as you might have noticed from my earlier post about building an OpenAccess enabled project on a build server, I am currently working with OpenAccess on one of my projects. I figure that since I am using this Object Relational Mapper that I should post regularly about using it so that others starting to use OpenAccess have a shorter learning curve.

Making modifications to persisted data needs to be done transactionally so that any issues which arise during the persistence can be responded to and handled correctly. For example if you are going to be updating a customer and that customer’s address then you will want to make sure that the save is an all or nothing situation since it could be bad if the address was saved but not the customer. With a transaction you have the ability to rollback so that you can be at the initial state once again. By doing this we can then handle the error and not have the transaction halfway committed.

OpenAccess has support for transactions using its ObjectScope. To begin a transaction you simply need to access the Transaction peroperty of the IObjectScope and call its Begin method. To complete the transaction you call the Transaction’s Commit method.

using (IObjectScope objectScope = MyScopeProvider.GetNewObjectScope())
    // Perform the persistence logic here

So this is pretty easy, right? Well what about rolling back the transaction if we have a problem. So the simple thing to do is to wrap a try-catch block around the transaction. Then in the catch portion we will need to make sure that if the transaction is still active that we roll everything back to the previous state. (We also handle the exception, but that’s your job not mine.)

using (IObjectScope objectScope = MyScopeProvider.GetNewObjectScope())
        // Perform the persistence logic here
        // UPDATE: This explicit rollback is only
        // required if you're crazy and don't trust
        // that things will wrap up nicely on their own.
        if (objectScope.Transaction.IsActive) 
        // Make sure you handle the exception here
        // failing silently is often a problem

So all we did is check to see if the Transaction is Active and if it is still active rollback the transaction. Wasn’t that easy?

Building an MVC Gaming Statistics Site – Setting Up the Project

Now that ASP.NET MVC has been around for a while there have been plenty of articles written about how leverage the technology to create powerful, lightweight web applications which are highly customizable and testable. I’ve discussed the advantages of using ASP.NET Forms and ASP.NET MVC plenty of times in the past, but just so no one thinks I am a forms hater I will say that I still create forms applications. Both MVC and Forms can coexist and they both have their advantages.

I will say that there is of course a learning curve for MVC. You don’t instantly know it just because you’ve used web forms. So yes, it will be like learning any new technology. However, I am writing this so that a transition can be easier. Rather than doing some demo application that doesn’t take into consideration real-life situations and circumstances I’ll be posting about an application I’ve been working on.

Background Information and Reason for Creating the Site

I am a member of the Boardgamers Of Greater Akron (BOGA), which if you hadn’t guessed from the name is a group of people who gather together the second Friday of every month to play board games. As games are completed the stats from the games are recorded onto sheets of paper and these stats will later be entered into a database.

Initially the founder of the group had been entering these game logs into the system using a local web forms application using the standard data entry controls. The entire site took about half an hour to an hour to create, so as you can guess it was kind of clunky and hard to use. From the data, I was able to write a bunch of SQL queries that were then used to calculate the stats from these games.

Creating the Solution, MVC Project, and Web Tests Project

I like to start by creating a solution first. I don’t want Visual Studio to create the solution for me because it will do a lot of stuff for me. I want to have control of the structure of my application, so I am going to create that first. This will let me organize my software project. To create a solution just create a new project of type Blank Solution. You can find that in the Other Project Types –> Visual Studio Solutions category.


I named the solution based on the domain of the application. This is important to do since I don’t plan on referencing the domain in any of the projects in this solution. Since names get long and difficult to work with sometimes I am going to stick with shorter ones. I’ll alter their default namespaces so it is a little bit easier to deal with.

Before we can write any code we have to have a project in which to write this code, so how about if we create a new MVC project. I’ll name it based on the domain of our application, so I’ll go with Web. Since the


Since we created this as an MVC site we will be prompted with the option to create a test project. Your Test Framework options will be populated with the test frameworks that you have installed that Visual Studio knows about. In this case I am just going to go with the Visual Studio Unit Test Framework since it defaulted to that. The differences between this and NUnit are negligible anyway.


After you wait for Visual Studio to create the projects for you the following will appear in the Solution Explorer. The first step is deleting the AuthoringTests.txt file. Not sure why that needed to be included every single time a project is created. Maybe there is some way to turn it off just so I don’t have to delete it. Well it doesn’t matter anyway.


I might also delete the App.config file, but there really isn’t much there to worry about. The use of the App.config in testing should be discouraged. If you’re having to put something in there then you have too much dependency on that. Keep in mind that the App.config in a test project should only include test configuration information. If it is using anything that is normally in the production configuration then you’ve got something you need to fix.

Creating the Core and Infrastructure Projects

Our next step is to create a project where we will keep the core logic of our application. This is business layer, but I don’t like that name because business logic often ends up getting mingled with infrastructure concerns. I am naming the next project Core to mean that this is central to the application. Only the things that are core parts of the application go here.




So as usual I need to make a couple of modifications. First I delete the silly Class1.cs file and then move the Models from the web project and move it here. I would say that the domain objects that we are going to be dealing with deserve to be in our core application.



The Infrastructure is the next step. If you expect to have multiple infrastructure concerns that you want to separate into separate libraries go with a more specific name for this project. Since I expect to only deal with database concerns I will stick with a generic name> If I ever need to change things I am not too concerned since renaming things is actually really easy if I structure my application nicely and use refactoring tools to help.


Once I create this I will of course delete the Class1.cs file and I will end up with a pretty full Solution Explorer now. I’ve got most of the projects in place now. I could have started small here, but I know I am going to need these projects.


Creating the Unit and Integration Test Projects

Since I like to keep the unit and integration tests separated from the production code it is nice to keep them in a separate library. This means that the tests need not be included with the rest of the application in deployed scenarios. The only problem I can think of is keeping the tests in their own library could make them just another navigation headache. However, since I use ReSharper I have a navigation tool which allows me to quickly get to anything based on its name, so I am not concerned with that issue.

Since I am using MSTest for my testing framework I can use the Visual Studio Test template. If you’re using something else like NUnit you will just create a normal class library and include a reference to the NUnit dll.


Since we created this from the UnitTest project template it added in the reference to the dll required to use MSTest. However, we will also need to eliminate these files which were created for us.


The next step is an integration test library. These tests are very important in the project as they help us ensure that everything is working well together. We want all the individual pieces working, but knowing that they interact is just as important. We keep them separate because the integration tests can often be long-running and we want to be able to execute the unit tests first. They will run faster and if there are any issues we will know sooner. Creating the integration test project will be done the same way we created the unit test one.


And as usual we have a few files that we do not need. Time to delete them.




I will soon discuss setting up the build process using NAnt and the continuous integration process using As you may have noticed I think the structure of software projects and the initial setup are very important. Without build systems in place I think the development process can be very limiting.


Fun With Web Forms Controls and LINQ

Since LINQ has come out I’ve been very fascinated with it. LINQ to SQL is kind of cool, but working with in-memory collections is my favorite. Sure anything we can do with LINQ we could have done before, but now it’s easy. While not exactly the most practical and certainly not the most efficient method of handling things, working with a page’s Controls collection can be a lot of fun.

So perhaps I want to change the text of all of the TextBoxes on a page. I can easily grab that collection like this.

IEnumerable<TextBox> textBoxes = Page.Controls.
    Where(c => c.GetType() == typeof(TextBox)).Select(t => (TextBox)t);

Well sort of except that some controls will not be in that collection because this is a tree structure so I’ll make a recursive method which will get me all of the controls on the page.

public IEnumerable<Control> AllControls(Control root)
    if (root != null)
        if (root.Controls.Count < 1)
            yield return root;
        foreach (Control c in root.Controls)
            if (c.Controls.Count < 1)
                yield return c;
                foreach (var control in AllControls(c))
                    yield return control;

Now we can work with a page having nested controls. Fun eh? Here is how you can get all of those controls and set the Text property of TextBox ones to their own IDs.

IEnumerable<TextBox> boxes = AllControls(Page).
    Where(c => c.GetType() == typeof(TextBox)).Select(t => ((TextBox)t));
foreach (var textBox in boxes)
    textBox.Text = textBox.ID;

Try it out with a page with textboxes in a login view. It works. Enjoy. Have fun!

Your IoC Container is Showing

Learning to keep things about your application hidden is important. Your code should be exposed to as few things as possible. Using tools like Ninject, Structuremap, etc. is great, but you should try to keep them at arm’s length.

If you want to keep your Inversion of Control (IoC) container hidden you can put a nice wrapper around it. In an application I am currently working with I started by using an IoC container that was very simple. Just enough so that I didn’t have to use the poor man’s dependency injection.

I start with these ten minute home-grown IoC containers for a few reasons. One reason is that they’re quick and easy. Another is that I wanted the developer I was working with to understand how IoC containers work, so having him deal with the inner-workings on an IoC container will give him that knowledge. Also I really don’t always make a decision on which IoC container to use until I see what features will be needed for an application. If one of them will give me an issue I don’t want to be using it. To say it in a nice way, I don’t like trying to force the square peg into the round hole.

Your own container

To start you’ll really want to have a class you can use to give you access to the container you’re using. This is the face of IoC in your application. It isn’t necessarily an IoC container since we’re really just going to have it pass the calls through.

We need to create a simple class. We will call it IoC for this example. I like that name since it is extremely short, so when we use it we aren’t making our lines excessively long.

public class IoC


Resolving Dependencies

The main task we use an IoC container for is to resolve our dependencies. We want to get objects of certain types from it. So we need some kind of Resolve or Get method on the class. In this case I am going to use a static method. Calm down! Static methods can be used sparingly. We just have to be careful with them and keep them very simple.

public class IoC
    public static T Resolve<T>()
        throw new NotImplementedException();

So I need to have something to resolve these dependencies for me. We want to depend on Interfaces and abstractions only, so I will create an interface for a dependency resolver. Then this static method can call through to that interface. This IoC class is really just here for convenience so I don’t have to pass around an instance of my interface everywhere.

public interface IResolver
    T Resolve<T>();


So now I can add this interface into my IoC class. I want to have a static instance of this interface and I want to have a method that will allow me to set the IResolver.


public class IoC
    private static IResolver _resolver;
    public static T Resolve<T>()
        return _resolver.Resolve<T>();
    public static void Initialize(IResolver resolver)
        _resolver = resolver;

Now we’ve got our IoC class finished up. Sure it doesn’t do anything yet, but we can test with this thing by initializing it with a mock, fake, stub, cake, etc.

Using Your Favorite IoC Container

Now that we have this nice interface in place we are set to wire things up. We can use anything we want to actually do the registering and resolving of our dependencies. If you’re ambitious go write your own. If not go grab something else. I’ll use Ninject in this example.

So I will create a concrete implementation of the IResolver interface and I will call it the NinjectResolver. This class will act as my go between for working with Ninject. I make this class inherit from the StandardModule from Ninject and implement my IResolver interface.

public class NinjectResolver : StandardModule, IResolver
    private readonly StandardKernel _kernel;
    public NinjectResolver()
        _kernel = new StandardKernel(this);
    public T Resolve<T>()
        return _kernel.Get<T>();
    public override void Load()


I am using the StandardKernel from Ninject, and am overriding the Load method from the StandardModule class. In the Load method I am registering the dependencies with the IoC container. Then when I want to get instances of the dependencies from the container I will be calling the IResolver.Resolve<>() method and it will just pass through to the StandardKernel.Get<>() method. Pretty simple actually.

Putting Everything Together

Now when my application initializes I just create an instance of the NinjectResolver and call its Load method. After that I pass this in to the IoC class using the Initialize method. Now we go celebrate because we can use this simple code to get an instance of IAmAnInterface in the form of ConcreteClass.

IAmAnInterface impl = IoC.Resolve<IAmAnInterface>()


I hope you’ve enjoyed today’s IoC fun. Please pass forward yesterday’s homework. Tonight your assignment is to figure out how to register your own dependencies without using Ninject. I recommend taking a look at the Dictionary class or something similar.

Viewing Disassembled IL with ILDASM

For those of you who are simply computer geeks I present to you an easy way to view the generated intermediate language code that is generated when you’re using the .NET Framework. So if you’ve ever wanted to see what is generated from your compiler, so you can see what code gets executed at run-time you just need to take a few simple steps.

Open up the Visual Studio Command Prompt. You can find this command prompt in the Start Menu inside of the tools folder for Visual Studio.


From here you will be able to open up ILDASM’s graphical user interface. Open it by typing “ILDASM”. It’s a very simple program.


From here you will want to open up the assembled file you want to view. This could be a class library or an executable. In this example I will use a “Hello World” console application.


The console application really only has one class. ILDASM_World.Program, which can be seen in the image. You can see the ILDASM_World namespace is where the class is located. Inside of the class we have a constructor (this is the default one I did not write the code for it). See this is neat, because we can see that a default constructor was created for us and we can see exactly what it does.

The Main method listed there is a standard one with a Console.Writeline(“Hello World!”); line written in it.

When we open up the method to view it we see the following IL is generated when we compile.


Now what is really cool here is that I bet pretty much every person reading this can figure out exactly what that code is doing. I think that people could have figured it out without my having to explain it. It is really cool to see. There are a lot of awesome tricks you can see here. Also if you’re ever wondering what is going to happen when you compile something I recommend looking here. You’ll be able to see exactly what actually happens.

This will assist you when you’re writing your code since you’ll be able to make a more educated decision on which approach to take with your code if you see what will be generated behind the scenes.

Your homework is to try this with loops and with a goto.

Overloading Implicit Conversions with Generics in C#

Overloading operators in a language is an excellent tool in every developer’s tool belt. It allows us to design our code in ways feeling far more natural. For example if we didn’t implement operator overloading for addition of numbers we would have some strange code. Could you imagine if we still wrote this kind of stuff?

int x = 5;
int y = 4;
int z = x.Add(y);

When we teach addition the non-computer way we learn it as “5 + 4 = 9”. The language reverses things and we switch the expression into “9 = 5 + 4”, but this is no big deal since we’re still using our operators. Some things happen behind the scenes so often we really don’t even think about them. Implicit conversions of numbers happens all the time. If we have a method that returns an integer we can certainly assign that value to a double. Why? Since we don’t lose any information doing that conversion it is just able to happen. We know that it is easy to store an integer value in a double so it is allowed.

One thing that I’ve always loved about the Nullable objects in C# is their ability to trick many of their newer users. A lot of people really don’t know about Nullable objects. I think they are fooled by the type? syntax into thinking it is something special. When the only thing special is the syntax. Beneath the surface we are actually just using Nullable<type>. My favorite part about the object is that they were nice enough to overload the implicit conversion from your type T into the Nullable<T>. The nullable object is just a cleverly hidden use of C# generics.

If you use .NET Reflector to examine the code for their implementation you will see this method.

public static implicit operator T?(T value)
    return new T?(value);


Sure that seems kind of boring. This is basically like a constructor in that it creates a new instance of the Nullable type and accepts an object of type T. The power comes from the fact that the user doesn’t need to realize he is changing types. It lets us do this.

int regularInteger = 3
int? nullableInteger = regularInteger;


Now to make things a little bit clearer I will change how their operator works so we don’t use their “?” shorthand. We will qualify things in the code so it is clear how the generic is working for us.

public static implicit operator Nullable<T>(T value)
    return new Nullable<T>(value);


So now if you want to use this for your generic object you can do the same thing as above. All you need is a constructor for your object that takes in a value of T, and then you write this method with your class name instead of Nullable. There is one thing to keep in mind though. There is one thing that could catch you off guard if your generic object contains state. That is that using this operator will create a new object.

If your generic is being exposed using a property, Value, like with Nullable then you could just set Value equal to the object. That approach is not as elegant, so if you can avoid having to set the value of the Value property I recommend it.

You can also perform an implicit conversion the other way, but that can potentially lose information if your object has state. If it does not then it is safe to perform that one. To achieve it just switch things around so you have this instead.

public static implicit operator T(Nullable<T> value)
    return value.Value;

So have fun assigning objects to the implicitly-converting, generic objects.

If you have questions or concerns or you just plain think I am wrong. Tell me about it! :-)

Build OpenAccess Project Using MSBuild on a Machine Without OpenAccess Installed

OpenAccess ORM is a powerful ORM tool that integrates very well into Visual Studio. It uses wizards and is tightly integrated, which makes it easy to pick up and start using. However, this same asset also provides a challenge when using this tool along with MSBuild on a machine without OpenAccess installed. There are some adjustments that needs to be made, since it is designed to be used with Visual Studio, so we have to add a couple of extra bits to get MSBuild to be able to build a project correctly.

So if you’re using the OpenAccess ORM tool and you want to use a build server you’ll need to make a couple of configuration changes to allow you to achieve this. Since I use a continuous integration server on pretty much every project I work on, I ran into this issue. There are a few things you need to do to get this working.

The first step to getting this working is to get the required dlls copied to a local directory. This is important because the build server will need to have these references for the project. To get these files all you need to do is look to see where the reference is coming from in your projects. In my case the location is.

C:\Program Files (x86)\Telerik\OpenAccess ORM\bin

So I copied the files being referenced by my project from here and put them into a lib folder in a relative directory for my project. I then removed all of the references to the libraries in their install directories and added the references back in this time pointing to the local directory.


Once you have everything local you’ll want to make sure you got all of the required libraries by building your solution. The build should succeed.

When working with OpenAccess, it is important to know that the assembly used for persistence is going to be Enhanced by OpenAccess ORM. After Visual Studio builds that project it kicks off VEnhance.exe to inject IL into the library with added functionality.

This is the step that we next need to add in to our build so that we can achieve the desired result.

Find the VEnhance.exe file on your development machine. It should be located in a directory similar to this one.

C:\Program Files (x86)\Telerik\OpenAccess ORM\sdk

Copy that directory somewhere local to your project. We will need it in a minute. You also need to copy your Telerik.OpenAccess.dll into the local directory you created with the VEnhance.exe file. The executable will need that dll to be there in order for it to do the enhancement.

We will need to create a targets file which we will import into our project file. You can copy the one I have listed here and customize it to your needs. It is basically just the instructions to tell your project how to call the VEnhance executable. You will need to change the relative directory to your OpenAccessToolsDirectory in this targets file to reflect where you put the VEnhance.exe file.


<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="">
 <Target Name="EnhanceAssembly" Condition="'$(_AssemblyTimestampBeforeCompile)'!='$(_AssemblyTimestampAfterCompile)'">
   <Copy SourceFiles="$(TargetPath)" DestinationFiles ="$(TargetPath).notenhanced"/>
   <Copy SourceFiles="$(PdbFile)" DestinationFiles ="$(PdbFile).notenhanced"/>
   <Exec IgnoreExitCode="false"
         Command="&quot;$(OpenAccessToolsDirectory)\venhance.exe&quot; -verboseMode:1 -signAssembly &quot;-keyFile:$(ProjectDir)$(AssemblyOriginatorKeyFile)&quot; &quot;-assembly:$(TargetPath)&quot;"
         Condition="'$(AssemblyOriginatorKeyFile)'!=''" />
   <Exec IgnoreExitCode="false"
         Command="&quot;$(OpenAccessToolsDirectory)\venhance.exe&quot; -verboseMode:1 &quot;-assembly:$(TargetPath)&quot;"
         Condition="'$(AssemblyOriginatorKeyFile)'==''" />
   <Copy SourceFiles="$(TargetPath)" DestinationFolder ="$(IntermediateOutputPath)"/>
   <Copy SourceFiles="$(PdbFile)" DestinationFolder ="$(IntermediateOutputPath)"/>
 <Target Name="PeVerify" Condition="'$(_AssemblyTimestampBeforeCompile)'!='$(_AssemblyTimestampAfterCompile)'">
     <Output TaskParameter="Path" PropertyName="SdkPath" />
   <Exec WorkingDirectory="$(SdkPath)bin" Command="peverify.exe /nologo &quot;$(TargetPath)&quot;" />

This file needs to be imported at the end of your project file. So you’ll want to open your project file using a text editor not Visual Studio. Remember that project files are really just XML so we can go in and made changes to their source code. We need to do this if we want to get our targets file included.

At the bottom of the file you should see XML that looks roughly like this.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" 
<!-- Pretend this is all of the rest of the project file -->
      <UserProperties OpenAccess_ConfigFile="App.config" 
          OpenAccess_UseMSBuild="True" />


All we have to do is add in one line and change it to this using a relative path to where we placed the targets file. I admit I didn’t really know the best place to put it so I put it with the Telerik class libraries for my project.

<Import Project="..\..\lib\Telerik\enhance.targets" />
    <UserProperties OpenAccess_ConfigFile="App.config" 
        OpenAccess_UseMSBuild="True" />

And now we should be able to commit our changes and everything should work correctly on the build server. Cross your fingers. Make sure that all of your relative paths are correct. If you have any questions just post a comment below, on the Telerik forums, or both.

Silverlight 3 Out of the Browser

Running a Silverlight application out of the browser is very powerful. This lets users install a Silverlight application locally with a quick right click on the app in the browser. In earlier versions of Silverlight this was still pretty easy, but now you don’t even have to open up an xml file to do it.

So here is my simple Silverlight application running in the browser.


After I click that Button the app makes a web service call to change the text, which isn’t that important to this demo. I figured it was better than having it do nothing.


Hooray we have a working Silverlight application. Now in order to get it running out of the browser we have only a couple of steps to take. None of which involve going into the AppManifest.xml file like was required in previous versions. Now we simply right-click on the Silverlight project in Visual Studio and select Properties.


After enabling the ability to run out of the browser you just need to change the Out-of-Browser Settings. Doing this will create a file in the properties folder of the Silverlight application which has XML defining all of the settings configured here. This GUI just makes it easy to set up.


I like how simple this is. Not overloaded with tons of options. Just easy to use.

Now when we run the app we can right-click on the application and we are able to install the app locally.


When we click on the Install option we get a nice installation wizard with no complexity.


All the user has to do is decide where to put a shortcut. Once they click this the app will be installed and running. The application will look a little bit like this.


And when we click out button we get another web service call and this time we pass a different parameter to the service call and get a different message. Take a look.


So how easy was that? Say that the user wants to uninstall the application now. That is also easy. All they have to do is right-click on it and select the option to remove the app and it is gone. They can do this in or out of browser.


So now you know how easy it is to set up an out of browser Silverlight application.

How to Change or Remove the No Data Series Message in a RadChart for Silverlight

I’ve been working with the charts from Telerik’s RadControls for Silverlight. I am of course not blocking the UI when I make my requests to get my data for the charts. Since I am doing this late-loading of the data into the charts it causes them to initially show a message, “No Data Series.” This message is not a bad default message since it provides adequate information about why the chart is not displaying data.


However, since my charts will always start with no data, that message is quite silly. Luckily, changing or removing that message is easy. There is a convenient property on the ChartArea object called NoDataString, and in my case I set that as an empty string and I receive this nice blank chart now. I could potentially change the message to something else.


Snippet of Relevant Code

<UserControl x:Class="MyProject.UI.Charts.MyChart"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot">
        <telerikChart:RadChart x:Name="Chart1" 
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                <telerikCharting:ChartTitle Content="My Chart" 
                <telerikCharting:ChartArea x:Name="ChartArea1" 
                  Grid.Row="1" NoDataString="" />