Posted on 8/28/2008 8:15:00 AM by Justin Etheredge
Wow, times flies. I apologize for not getting something up sooner, but the Richmond Meet and Code Dinner is tonight! The topic is functional programming and my good friend Kevin Hazzard is going to be presenting on F#. He has an excellent series of posts going on about F# for beginners, so I am really looking forward to his talk.
I will be presenting on some functional-ish stuff in C# 3.0. It is going to be some of the same material from my .net user group talk, but if you didn't get to catch that talk, then it will all be new! Also, for those that did see my talk, this is going to be a good time to come out and ask questions.
There will be food provided, so come hungry. The meeting is located at SnagAJob.com's headquarters and is at 6pm. If you want to sign up and get directions, then please click here. We hope to see you there!
Posted on 8/25/2008 7:58:52 PM by Justin Etheredge
I had the need to completely script a database at work today. I couldn't just attach a backup because I couldn't run the backup on the database since I didn't have physical access. At my last job we did this pretty often, but we had the wonderful SQL Compare and SQL Data Compare tool by Red Gate. (You could also use SQL Packager) At my current job I didn't have access to these tools, so I set about to do it without them. I figured that I would just script out the database by using the built in SQL Server 2005 scripting tools. The process is pretty simple, you just right click on the database and go to "Tasks" and then "Generate Scripts..."
The wizard is pretty simple so I'm not going to go over it. Then I was going to use this stored proc that I have actually used many times in the past(click the image to download):
The problem I had was that when I tried to script the database using the built-in "Generate Scripts..." function I got an error stating that "An entry with the same key already exists". It looks like a bug surrounding synonyms in the database conflicting with table names. So, I didn't feel like trying to figure out my way around it, since the schema was valid it should be able to be scripted out. So I started looking around for an alternate method of scripting my databases.
I found just the tool, it is Microsoft Database Publishing Wizard and it is part of the SQL Server Hosting Toolkit. It is a tool for scripting databases to a file so that you can install it on a remote host. In fact, it will script the entire schema and the data! I ran it on the database that I needed to script and it worked like a charm.
When I went to install it after I got home, I noticed that it was already on my machine! And then I did a bit of digging and found out that it is included in Visual Studio 2008. All you have to do is open the Server Explorer and right click on one of the databases:
A wizard will pop up that looks like this:

The wizard is pretty self explanatory, so I'm not going to walk through it. Suffice to say that you can choose to publish the database to a file with schema, data, or both.
I hope that this helps out someone!
Posted on 8/21/2008 10:58:27 PM by Justin Etheredge
I had someone send me an e-mail today asking me about configuring Ninject in a real application since most other DI frameworks just have a default config section or file that they just magically read from in order set themselves up. Well, the answer is quite simple, and I think that as a community we have become so used to config files and xml settings that we can forget how easy it is to just configure things in code. I'm going to lay out my DI container that I use in a few of my projects, and it is so simple that you will have a "duh!" moment.
I think another part of it is also that Ninject does not have a single "Factory" that you can request objects from, since in Ninject you can have multiple kernels and multiple modules per kernel. Below is a simple setup with a single kernel and module, but I'm sure you can see how it flesh it out a bit more if you wanted multiple.
First thing I want to do is to make my application DI framework agnostic (You may or may not care about this). So, I do this by creating a class called DIFactory. This class will look something like this (and yes I made a class with static methods, some people might use instance methods. I have actually done this in a few projects, but since our DIFactory is used in tests and we rarely mock it, I am just showing this with static methods):
public static class DIFactory
{
public static T Resolve<T>()
{
}
public static T Resolve<T>(string name)
{
}
}
This covers the very basics of what most DI frameworks provide. You can probably already see where this is going, but lets take it further. What this class will allow us to do is just to call:
MyClass variable = DIFactory.Resolve<MyClass>();
And now you can resolve a class by type or by type and name. You can add overloads for passing in a Type object if you need them as well. In the case of Ninject, we could implement this class fully like this:
public static class DIFactory
{
private static IKernel kernel = null;
public static T Resolve<T>()
{
if (kernel == null)
{
CreateKernel();
}
return kernel.Get<T>();
}
public static T Resolve<T>(string name)
{
if (kernel == null)
{
CreateKernel();
}
return kernel.Get<T>(With.Parameters.ContextVariable("name", name));
}
private static void CreateKernel()
{
IModule module = new CustomModule();
kernel = new StandardKernel(module);
}
}
So, now that we can resolve any class by calling one of these two methods. Notice that we are only using a very small part of the flexibility that Ninject gives us, but we have to make the call on how important it is to support standard DI framework functions and allow for us to easily switch it out in the future, or to use Ninject specific powers and tightly tie our app to the framework. This is almost always a tradeoff in any tool that we use.
As far as the custom module you see above, it would look something like this:
internal class CustomModule : StandardModule
{
public override void Load()
{
Bind<ICaffeinated>().To<DietCoke>().Always();
Bind<IEdible>().To<Cheetos>().Always();
Bind<ISugary>().To<Cookies>().Always();
Bind<IEditor>().To<Emacs>()
.Only(When.Context.Variable("name").EqualTo("Linux"));
Bind<IEditor>().To<VisualStudio()
.Only(When.Context.Variable("name").EqualTo("Windows"));
}
}
This custom module was slightly modified from one of my presentations. And was also used on my screencast series over at Dimecasts.net. Pretty cool stuff. Well, I hope that this cleared something up for a few people, and I hope that this might inspire you to get our and use Ninject in your next application.
Posted on 8/20/2008 10:55:01 PM by Justin Etheredge
Most of you have probably been hearing a lot recently about the new ASP.NET MVC framework and the many features that it has which will hopefully simplify web development for those of us that want to get "closer to the browser". One of the features that they were initially implementing for the MVC framework was a new routing engine that gives you a flexible way of mapping urls to specific pages in your application. Early on they realized that the System.Web.Routing infrastructure was not only applicable to ASP.NET MVC, but could be used in any ASP.NET application to allow for much easier url rewriting. (They also realized that they wanted to use it in the Dynamic Data stuff!) Because of this they moved Routing out of the System.Web.Mvc namespace and into the System.Web namespace. Well, this namespace just shipped as part of .net 3.5 SP1, so lets take a look at how it works!
The first thing that you need to do in order to use these features are to add a reference to the System.Web.Routing dll:
System.Web.Routing has two core concepts. One is the concept of a route and the second is the concept of a route handler. A route is simply a class that holds a pattern which can be matched by urls coming into your application. Each url coming into the application will be matched against the list of Routes that you have defined, and if one matches then it will be used. A route will look something like this:
"Catalog/{Category}/{ProductId}"
This will match any url coming into the application that starts with "/Catalog/" so something like "/Catalog/Computers/3444" would match this route. The items between the curly braces are called segments, and these will be captured and used later in our route handler. These routes are defined on static property of System.Web.Routing.RouteTable called "Routes". These routes will be defined in the "Application_Start" method of your global.asax file like this:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("Catalog/{Category}/{ProductId}", new CatalogRouteHandler()));
}
Now, you may have noticed the "CatalogRouteHandler" class that we are creating in the "RegisterRoutes" method. This is a class that we need to create in order to processes a request that comes in matching the provided route. You can have any number of these Route handlers to handle different types of request, but for right now we are just going to have one.
These "Route Handlers" implement the IRouteHandler interface which only has a single method called "GetHttpHandler" which, as you probably guessed, returns an IHttpHandler. So, what is IHttpHandler? It is not a new interface, and is actually part of the System.Web namespace. This interface also supports just one method called ProcessRequest which takes an HttpContext. In the context of a normal ASP.NET application, the class that you are going to see which implements this is the Page class. If you are an ASP.NET developer I hope that you are familiar with the Page class, if not, then get a book! So, we have an Interface which returns an IHttpHandler, which in our case, is a page object.
So, I hope you see where this is going. We are just matching a bunch of urls against our list of patterns, and then when we find a matching pattern we will use the associated IRouteHandler to get the IHttpHandler which is going to be able to respond to our request! It is actually a lot more simple than it sounds!
As we already said, in our case, the IRouteHandler is going to be returning a Page object. What page object? It doesn't really matter. We can map any number of urls to any number of Page objects. We could map all of our urls to a single Page object if we wanted. So, now that we know that we can map to any number of pages that we want, how does our IRouteHandler decided which page to map to? What kind of data do we get that allows it to make a decision? This is where the System.Web.Routing.RequestContext class comes in. The "GetHttpHandler" method that I mentioned above returns an IHttpHandler, but it also takes a parameter of type RequestContext. The RequestContext class contains has two properties, one is called "HttpContext" which is of type System.Web.HttpContextBase. The other is "RouteData" which is of type System.Web.Routing.RouteData.
If you saw "System.Web.HttpContextBase" and did a double-take then you are probably not alone. This is another class that was added in .net 3.5 SP1 which is simply an abstract wrapper for our old untestable friend the HttpContext. Remember earlier when I was talking about the nice new testable design, well, this is a big part of it. Just keep in mind that this is part of System.Web.Abstractions and so you'll need to add a reference:
The HttpContext property just allows access to all of the normal information that we would garner from our HttpContext, so that we could make potential routing decisions based on the request data itself. For example if we wanted to do something different if we were operating under https or http. Or if we wanted to redirect different places based on the domain, or sub-domain coming in on the request.
The "RouteData" property is where all of our data concerning our route and the segments are stored. First it has a property called "Route" which is of type RouteBase, and this represents the matching route that was picked for this particular request.
Next there is a property called "Values" which holds all of the values and default values for the segments that were specified in the route that we created. For example, the route that we created at the beginning of this post ("Catalog/{Category}/{ProductId}") had "Category" and "ProductId" segments, so for the url that we had above ("/Catalog/Computers/3444") the "Values" property would have values for each:
routeData.Values["Category"] == "Computers"
routeData.Values["ProductId"] == "3444"
So, now we could use these values to pass in our HttpContext.Items collection to our asp.net page! This would be accomplished by implementing that IRouteHandler that we talked about earlier. Here is a basic IRouteHandler for you to take a look at, take note that we have not implemented any security or anything in this.
public class CatalogRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
foreach (KeyValuePair<string, object> token in requestContext.RouteData.Values)
{
requestContext.HttpContext.Items.Add(token.Key, token.Value);
}
IHttpHandler result = BuildManager
.CreateInstanceFromVirtualPath("~/Product.aspx", typeof(Product)) as IHttpHandler;
return result;
}
}
From here you can see that we are shoving our Category and ProductId into the "HttpContext.Items" collection.
Now that we have defined our routes, and we have defined our CatalogRouteHandler, lets look at a few more features of the routes. The first thing that we can do is setup defaults for our routes. So, lets say that we want to default the "ProductId" to 0001 when the "Catalog/{Category}/{ProductId}" route is used without the "ProductId" segment. Let us go ahead and default "Category" to "Default" when that is not passed in as well. This actually quite easy and is simply an overload of the Route constructor. To define the route above with a product default would look like this:
private static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("Catalog/{Category}/{ProductId}",
new RouteValueDictionary(new { Category = "Default", ProductId = "0001" }),
new CatalogRouteHandler()));
}
As you can see we are creating a new RouteValueDictionary and we are initializing it using the constructor that just uses the properties off a given object to initialize it. Here we are using an anonymous type with Category and ProductId properties. This could also be done by just using a collection initializer and it would look like this:
private static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("Catalog/{Category}/{ProductId}",
new RouteValueDictionary { {"Category", "Default"}, {"ProductId", "0001"} },
new CatalogRouteHandler()));
}
Now, there is another part to adding a route that we need to discuss and that is route constraints. Route constraints actually take more than one form. First we have regular expressions. Let's say that we want to limit the ProductId on the route above to a max of 4 numbers. Then we could implement the constraint like this:
routes.Add(new Route("Catalog/{Category}/{ProductId}",
new RouteValueDictionary { {"Category", "Default"}, {"ProductId", "0001"} },
new RouteValueDictionary { {"ProductId", @"\d{1,4}"} },
new CatalogRouteHandler()));
Here you see that we have another RouteValueDictionary that has a single entry for "ProductId" which takes the regular expression "\d{1,4}". Well, this regex limits us to 1-4 digits. So, if we enter a 5 digit product id, then this route will no longer be matched. You can check any value that you can validate using a regex. Constraints also take on a second form, which is they implement the IRouteConstraint interface. This interface has a single method called "Match" that passes all relevant info about the request to your class, and allows you to put custom logic for route constraints into your own class. Pretty powerful stuff. There is one already built in called HttpMethodConstraint and it allows you to limit your route to a particular http verb such as "get" or "post". These classes are just inserted into the same RouteValueDictionary that we used above, and they key doesn't matter. The routing infrastructure will reflect the key and see that it supports the IRouteConstraint interface and call the appropriate method. If we wanted to limit the above route to just "get", it would look like this:
routes.Add(new Route("Catalog/{Category}/{ProductId}",
new RouteValueDictionary { {"Category", "Default"}, {"ProductId", "0001"} },
new RouteValueDictionary { {"ProductId", @"\d{1,4}"}, {"httpMethod", new HttpMethodConstraint("get")} },
new CatalogRouteHandler()));
Here we are giving it a key of "httpMethod", but you could really call it anything you want. The HttpMethodConstraint just takes a list of http verbs as a constructor and then checks the request for them when trying to match the route.
At this point I think that you have a pretty darn good overview of how the new System.Web.Routing namespace works, but there is just one more quick thing that I want to touch on. It is the StopRoutingHandler class. All this class does is cause the routing infrastructure to stop trying to route a particular request. This is good if you want to stop a particular extension from checking each and every route. Instead of allowing this, you can just put in routes at the top that will stop the process. So, if we wanted to stop looking for a route on an *.asmx request, we could add this to the top of our route definitions:
routes.Add(new Route("{service}.asmx/{*path}", new StopRoutingHandler()));
Here we are saying that any request which ends in ".asmx" and then has any path following it matches this route. Once this is matched, the route should stop being processed. Very useful if you have a huge number of routes.
So, at this point you may be reading this and thinking "I see how this all works, but how in the world does this actually process requests? Don't I need to get some module in the request pipeline?" And that answer is of course, "yes". There is a class called System.Web.Routing.UrlRoutingModule which is an IHttpModule which plugs into your request pipeline and intercepts the urls as they are coming through to allow the routing support to work. This is done using the exact same mechanism that most of us are using now in order to do url rewriting. Add this to the "modules" section in your web.config:
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
And then add this to the handlers section (if you are using IIS7):
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Well, that about wraps this up, I hope that you now have a good idea of how or if you can leverage the new routing infrastructure in .net 3.5 SP1.
Posted on 8/12/2008 11:51:27 PM by Justin Etheredge
Click here to view the entire IronRuby via C# series
In the last part of this series we talked about hashes in Ruby and C# and we saw how they are very close in functionality. In this entry we are going to start looking at the parts of Ruby that do not easily translate directly into C#. In a few past posts you have seen some parts of Ruby that vary a bit from C#, but in most cases the languages are still very similar. You will now start to see the features that people brag about when they tout Ruby's power over most statically typed languages.
The first feature that we are going to look at is called "duck typing". It is really less of a feature and more an underlying principle of the language. "Duck typing" refers to the way in which objects are used polymorphically in Ruby. In C# an object's class is its type and it represents the mechanism through which object can be manipulated. So, in C#, if you wanted to interact with a class then you need to know its type, one its base types or an interface supported by the type. So, lets define a tiny hierarchy here:
public abstract class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public abstract int VacationDays { get; }
}
public class Manager: Employee
{
public override int VacationDays
{
get
{
return 25;
}
}
}
public class Developer: Employee
{
public override int VacationDays
{
get
{
return 18;
}
}
}
In this you can see that we have a Employee class with Developer and Manager child classes. If we wanted a method to be able to operate on either a Manager or a Developer then we would create a method that used our Employee base class like this:
public void PrintEmployeeVacation(Employee employee)
{
Console.WriteLine("Vacation Days: {0}", employee.VacationDays);
}
And now we could pass either a Manager or Employee in and we would print out their vacation. So, how would we do this in Ruby? Well, in Ruby this hierarchy would look like this:
class Employee
attr_accessor :first_name
attr_accessor :last_name
end
class Manager < Employee
def vacation_days
25
end
end
class Developer < Employee
def vacation_days
18
end
end
But if we created the same method then we would create it to look like this:
def PrintEmployeeVacation(employee)
puts "#{employee.vacation_days}"
end
So, that looks very similar to the C# method, but there aren't any types. So how does that work? If we aren't specifying any types, how does Ruby know that it is valid to call "vacation_days" method on the object? This is where Ruby's duck typing comes in. Since in Ruby a class is not its type, Ruby simply relies on whether or not a class has an implementation of a particular method. Which is why it is called "duck typing", because "if it walks like a duck, and talks like a duck, then it must be a duck"!
And since Ruby doesn't rely on anything other than the fact that a class supports a particular method, we see that there is nothing regarding the "vacation_days" method in the "Employee" class at all. Ruby has no concept of an abstract class or method. And guess what, that means that these classes don't need to share a base class! In fact, Ruby has no concept of interfaces, and so you don't need one of those either. So, we could define these classes like this:
class Manager
attr_accessor :first_name
attr_accessor :last_name
def vacation_days
25
end
end
class Developer
def vacation_days
18
end
end
Notice that there is no first name and last name in the Developer class. I took those out so you can see that they don't share a base class and they don't even have an identical implementation. Ruby just doesn't care. It doesn't matter to the "PrintEmployeeVacation" method because it only uses the "vacation_days" method. This means that any class which has a method called "vacation_days" which returns a value that can be used in the "puts" method will work in this method. This means that we could change the Developer class to this:
class Developer
def vacation_days
"18"
end
end
And it would still work. Since the string "18" is valid in the context of our method, then execution would occur as normal. How is that for flexibility?
But all of this flexibility also comes at a cost. In fact, most of you who are used to static languages may be sitting there with your mouth agape in horror. You are probably thinking "you can pass anything into that method, and if the 'vacation_days" method isn't supported then it will just blow up!". What about if an object is passed in that has the method which doesn't perform the same operation, or return a valid result, or takes parameters? Well, you will get a runtime error. Because of that you may be shaking your static head and saying, "but how would you ever control the behavior!?"
The answer is unit testing. In dynamic languages, just like in static languages, everything should be unit tested. Sure the programmer must to have better knowledge of what an object needs in order to be passed into a particular method, but the lack of compile time checking is one of the fundamentals of dynamic programming. It is not a weakness, it is a feature! If the thought of not having every parameter on every method checked for type makes you lose sleep, then dynamic languages may not be for you. The important thing is that you must use heavy testing in order to flush out these errors and keep your code quality high.
I hope you enjoyed this look at the power and flexibility of Ruby's duck typing, in a future post we are going to delve a bit more deeply into Ruby's type system by introducing you to modules in Ruby. Have fun!