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.
DataFormatString="{}{0:P}"
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.
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())
{
objectScope.Transaction.Begin();
// Perform the persistence logic here
objectScope.Transaction.Commit();
}
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())
{
try
{
objectScope.Transaction.Begin();
// Perform the persistence logic here
objectScope.Transaction.Commit();
}
catch
{
// 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)
objectScope.Transaction.Rollback();
// 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?
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 CruiseControl.net. 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.
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;
}
else
{
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!
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.
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()
{
Bind<IAmAnInterface>().To<ConcreteCLass>();
}
}
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.