After a little bit of work with MVC, you get infected with the spirit of clean code and begin to desire even more ways of eliminating repetition. You’ve got partials and html helpers. Still you are hungry. SubControllers are the dish that will fill you up.
There’s a design decision here. The question is why are we designing with subcontrollers? To understand the rationale, let’s look at the qualities of the various sub-view options.
1) Add a reference to MvcContrib.
2) Create a class called StructureMapSubControllerBinder. This is only required if you’re using StructureMap to do your IOC for you. You can use the base SubControllerBinder from MvcContrib, or create your own version for your IOC tool.
public class StructureMapSubControllerBinder : SubControllerBinder { public override object CreateSubController(Type destinationType) { object instance = ObjectFactory.GetInstance(destinationType); if (instance == null) { throw new InvalidOperationException(destinationType + " not registered with StructureMap"); } return instance; } }
3) Make the SubControllerBinder your default binder.
ModelBinders.Binders.DefaultBinder = new StructureMapSubControllerBinder();
<add namespace="MvcContrib"/>
1) Create a ~/Controllers/SubControllers folder. This is completely optional. If you have a bigger project you might want to make multiple subcontrollers folders for different areas.
2) Create a SubController class. The action needs to have the ‘same’ name as the class. It also subclasses from SubController.
using System.Web.Mvc; using MvcContrib; namespace NWIS.Business.Web.Controllers.SubControllers { public class DemoSubController : SubController { public ViewResult Demo() { return View(); } } }
3) Create a View subfolder. Using the ‘Add View’ context menu from the controller won’t work because the ‘sub’ in the class name. Just create the folder yourself. ~/Views/Demo.
4) Create a View. Right click on the ~/Views/Demo folder. Select Add->View. Name the view ‘Demo’. Make it a partial view (.ascx). Go ahead an add some markup to the view. Whatever you like.
1) Add an attribute to your Controller class.
[SubControllerActionToViewDataAttribute]
2) Add the subcontroller as a parameter to the action you want to use it in.
public ViewResult Index(DemoSubController mySubCont)
3) Place the subcontroller output into your view.
<% ViewData.Get<Action>("mySubCont").Invoke(); %>
I Love StructureMap! It’s wonderful. What a way to compose your code together easily, precisely, and consolidatedly (!!). When I put a sentence like that together, I wonder if I even know what I’m talking about. The problem with StructureMap, IoC, and dependency injection really seems to be that the jargon for the patterns is so manifestly true that once you learn what the hell you are doing, you are completely unable to stop talking about it in shorthand. And that shorthand makes absolutely no sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Once you do it, you’ll get it. Then you’ll be there and not be able to explain to other people why you’re so right. It’s like being Tom Cruise and needing to explain scientology.
Anyways.
I learned two things today. The first is how to hook all of my concrete generic repository types together with their interfaces. I had been adding a line of configuration for each repository. Now my test code looks like this:
ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(ListRepository<>));
And my production code:
ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(LlblRepository<>));
That’s easy!
The other thing I learned is that I can happily and easily inject data into my object registry for testing purposes. I have an in-memory repository implementation built. All it needs is data.
public class MemoryDataSource { private Dictionary<Type, IQueryable> data; public MemoryDataSource(Dictionary<Type, IQueryable> data) { this.data = data; } public IQueryable GetQueryable(Type type) { return this.data[type]; } } public class ListRepository<T> : IRepository<T> { private MemoryDataSource source; public ListRepository(MemoryDataSource source) { this.source = source; } public IQueryable<T> GetSource() { return ((IQueryable<T>)source.GetQueryable(typeof(T))); } public void SaveEntity(T entity) { return; } }
Now all I need to do is build a Dictionary<> keyed on the entity object type and fill it up with data. Once I’ve done that, I just pass it into the StructureMap registry like this:
ObjectFactory.Inject<Dictionary<Type, IQueryable>>(dataSource);
Now I can have ObjectFactory construct my object under test and it’s got just the data I need it to have.
ASP.NET MVC Has added a very useful new programming model to developing websites in .NET. There is hype and debate all throughout the interwebs on how great MVC is. And it all can be yours, with nothing but a ‘File->New’ in Visual Studio….unless you already have an ASP.NET application. In which case, you need to do a bit more work.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <pages> <namespaces> <add namespace="System.Web.Mvc"/> <add namespace="System.Web.Mvc.Ajax"/> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing"/> <add namespace="System.Linq"/> <add namespace="System.Collections.Generic"/> </namespaces> </pages> <compilation> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </assemblies> </compilation> <httpModules> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </httpModules> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules runAllManagedModulesForAllRequests="true"> <remove name="ScriptModule" /> <remove name="UrlRoutingModule" /> <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="ScriptHandlerFactory" /> <remove name="ScriptHandlerFactoryAppServices" /> <remove name="ScriptResource" /> <remove name="MvcHttpHandler" /> <remove name="UrlRoutingHandler" /> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </handlers> </system.webServer> </configuration>
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); }
The above is the “standard” routing for a MVC site. It will work, but it might cause you trouble if you want the root of your website to still go to a ‘default.aspx’. Try this line instead:
routes.MapRoute( "Default", "MVC/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }
<ProjectTypeGuids>{603c0e0b-db56-11dc-be95-000d561079b0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
Boy howdy. That was a good chunk of work. But now you have the infinite pleasure of developing in MVC, and your old web site should continue to work under you. Delicious incremental development goodness.
In my last post, I covered how you can implement a publish/subscribe system for sending events between components of your Windows Forms application. Using this model, it is easy to create separate components that don’t rely on each other’s implementation details in order to provide a consistent experience for the user. A button on the toolbar can be disabled by an action on the data entry screen…without hard references between the two.
However, the implementation from last time required a new aggregator and set of interfaces for each message type that needed to be passed around. Let’s fix that with generics.
First we replace the IEventReciever interface from last time with a generic IListener interface that uses a generic type for the message object.
public interface IListener<T> { void Handle(T message); }
Similarly, the Event Aggregator needs a generics reset. Notice that the Add and Remove methods now accept any old object.
public interface IEventAggregator { void SendMessage<T>(T message); void AddListener(object listener); void RemoveListener(object listener); }
public class EventAggregator : IEventAggregator { private readonly List<object> listeners = new List<object>(); #region IEventAggregator Members public void SendMessage<T>(T message) { listeners.CallOnEach<IListener<T>>(x => { x.Handle(message); }); } public void AddListener(object listener) { if (listeners.Contains(listener)) return; listeners.Add(listener); } public void RemoveListener(object listener) { listeners.Remove(listener); } #endregion }
Not much new here….except for that CallOnEach method. Where did that come from?
We need to add a few utility methods to the IEnumerables so that we can send our messages:
public static void CallOnEach<T>(this IEnumerable enumerable, Action<T> action) where T : class { foreach (object o in enumerable) { o.CallOn(action); } } public static void CallOn<T>(this object target, Action<T> action) where T : class { var subject = target as T; if (subject != null) { action(subject); } }
Put those in a likely static class somewhere.
This Event Aggregator is getting powerful. We should kill it before it develops language skills.
With the code we have so far, we can easily create a new message in the system without modifying the aggregator code. I like adding the methods as child classes of their receivers (when they are receiver-specific).
There is, however, still a problem. In the type of application that needs this eventing system, you are likely going to need to do some background threading to keep the UI responsive. The Event Aggregator we have doesn’t do anything to keep itself or the rest of the application synchronized.
What happens when a background thread sends a message that the receiver needs to act on by talking to the UI thread? Do you write a bunch of Invoke() code everywhere?
As it turns out, there is a better way. And my next post will show you how to upgrade your EventAggregator to be the thread master!
In my last post, I described the creeping problem I’ve been having with wiring my large Windows Forms application up with EventHandler delegates. In short, the design becomes brittle—it’s hard to write and hard to change. Luckily, the solution is an easy one: Publish/Subscribe.
The Event Aggregator is a singleton. You can either manage this yourself, or you can have your Inversion of Control container do it for you. When an Event Receiver is created, it registers itself with the Event Aggregator, which stores a reference to the receiver. When a Event Sender sends a message to the Event Aggregator, the aggregator loops through all the registered receivers and calls a method on them to handle the event. This is facilitated by having the receivers implementing an interface. Here’s a simple implementation:
public class EventMessage { public string MessageText { get; set; } } public interface IEventReceiver { void Handle(EventMessage message); } public interface IEventAggregator { void SendMessage(EventMessage message); void AddReceiver(IEventReceiver receiver); void RemoveReceiver(IEventReceiver receiver); } public class EventAggregator : IEventAggregator { private readonly List<IEventReceiver> receivers = new List<IEventReceiver>(); #region IEventAggregator Members public void SendMessage(EventMessage message) { receivers.ForEach(r => r.Handle(message)); } public void AddReceiver(IEventReceiver receiver) { if (receivers.Contains(receiver)) return; receivers.Add(receiver); } public void RemoveReceiver(IEventReceiver receiver) { receivers.Remove(receiver); } #endregion } public class EventReceiver : IEventReceiver { public EventReceiver(IEventAggregator aggregator) { aggregator.AddReceiver(this); } #region IEventReceiver Members public void Handle(EventMessage message) { Console.WriteLine(message.MessageText); } #endregion } public class EventSender { private IEventAggregator aggregator; public EventSender(IEventAggregator aggregator) { this.aggregator = aggregator; } public void SendErrorMessage(string message) { aggregator.SendMessage(new EventMessage { MessageText = message }); } }
This is a big improvement over manual event wiring through an application. No longer do the targets of a message need to know (have references to) the senders of the message in order to make the connection. You can add a new target (receiver) without changing the code of the sender. You can add a new sender without changing the code of the receivers. And you don’t have to manually map things out in some sort of registry class. This is simple easy and it will work.
Ok. I like it. I’m happy. But how many of these things am I going to have floating around? It seems like a lot of code to write to hand one type of event between some components. I’m going to have to hire some Indian outsourcing company to write all of these singleton aggregators.
This sounds like a job for generics! My next post will rewrite the Event Aggregator so that a single aggregator can handle every message your application has.
Anxiety. This is a feeling I’ve been learning to recognize as a SIGN when I’m coding. The feeling you get when the camera gets really close on the face of the pretty girl as she walks around the empty, and silent, house. Is she going to turn around suddenly and be given flowers? Or is the disemboweling only moments away. You don’t know, but you’re cringing either way.
I’ve felt this in the past about data access layers. This is the feeling I’ve been accumulating around my Windows Forms application lately. I don’t want to code. I’m afraid to code. It’s going to be painful. I’m not sure what’s going to go wrong. But something will, and I’ll be sucked into the unproductive death pit.
Having spent a bit of time feeling around the problem, I’m pretty sure what I don’t like is having to deal with events. Let’s take a look at the reason why:
Click click click! I have a button and I have an event linked to it. Amazingly productive. My app will be running in no time.
It’s so easy to link an action to an event handler. Well. It’s pretty easy. It’s very easy within one class. Not so bad if you’ve got a reference to the object that contains the event handler. A little bit of encapsulation makes it harder. Chained event handlers can fix that though……
This form is easy. Add a few buttons and it’s great. If you’re prepared to make your application out of a bunch of forms that the user will work with one-by-one, there’s no problem.
If the user is going to be in one application all day long, it will have to provide easy access to a number of different types of functionality. The application can’t consolidate all of the interface elements required for a single task into a single place. Rather there’s a spaghetti monster of functionality, reaching it’s noodley appendages everywhere.
Can you actually wire all this up with EventHandler references? Sure. Of course you can. However, you end with a lot of tightly coupled code that is a real mess to create and to maintain.
A application shell is a complicated beast. But problems have solutions. In my next post, I’ll show how you can integrate all these separate components without strangling yourself in wiring.
ELMAH (Error Logging Modules and Handlers) is a fantastic library that provides error logging and troubleshooting support to an ASP.NET web site. You practically just drop it in and BOOM, you’ve got great exception reporting.
Step 1: Add A Reference
Add a reference to the ELMAH DLL in your ASP.NET project. (They tell me it just needs to be dropped in the BIN folder, but that almost seems like more work to me.)
Step 2: Add Config Sections
In web.config, add the following lines to <configSections>
<configSections>
<sectionGroup name="elmah">
<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
Step 3: Add the ELMAH Section
<elmah>
<security allowRemoteAccess="0" />
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="|DataDirectory|" />
</elmah>
Step 4: System.web—httpModules and httpHandlers
<system.web>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
</system.web>
Step 5: (II7 Only) Configure system.webServer
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="Elmah.ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
<add name="Elmah.ErrorFilter" type="Elmah.ErrorFilterModule" preCondition="managedHandler" />
<add name="Elmah.ErrorMail" type="Elmah.ErrorMailModule" preCondition="managedHandler" />
</modules>
<handlers>
<add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
</system.webServer>
Step 6: Secure remote access using ASP.NET membership
<location path="elmah.axd">
<authorization>
<deny users="?"/>
</authorization>
</location>
Resources:
One, Two, Three, Four. I thought I understood the damn things. And then it turns out they have ‘lifestyle choices’ and Mr. One says ‘you know, I just don’t FEEL like an Integer’ and suddenly they are making ‘changes’ and you’re alone with the Xbox, a pound of bacon, and nothing but tears.
I’m talking numbers in Ruby right now, but I’m shaken to the core. Floating numbers are numbers! They should work right! They should ADD UP! Now, a floating point number is at least equal to itself. This passes:
assert_equal(0.1, 0.1)
But this doesn’t:
assert_not_equal(0.1, 0.4-0.3)
You’d think 0.1 == 0.1 but you’d be wrong! You see, 0.1 is only an approximation of the value stored by the floating point system in binary. 0.3 is an approximation, and 0.4 is an approximation. And when they are mathed, they don’t approximate out equally. There’s a loss of precision. It’s pretty close. This passes:
expected_float = 0.1
actual_float = 0.4-0.3
assert ( (expected_float - actual_float).abs <= 0.00000005 )
…it’s just not exact. It’s wrong over in C# too.
[Test]
public void FloatTests()
{
Assert.AreEqual(0.1f, 0.3f - 0.2f);
}
Goes boom:
What’s a modulus? First off, I thought it was the number you get when you use the mod operator in a language…but it’s not. The modulus is actually the number you ‘divide’ by in a mod operation. The result is technically called the remainder.
Now the way I learned it, the mod operation is a lot like making change. If I have 1453 copper pieces (cp) and one silver piece (sp) is 100 coppers, then I find out how many silvers I have with simple division. This passes in C#:
int copper = 1453;
int silver = copper / 100;
int change = copper % 100;
Assert.AreEqual(14, silver);
Assert.AreEqual(53, change);
And in Ruby:
copper = 1453
silver = copper / 100
change = copper % 100
assert_equal 14, silver
assert_equal 53, change
It’s all good so far, right? But what if I owe money? What if my initial total is –1453 ? I owe 14 silvers and 53 coppers, right? Well, yes. And that’s what C# shows. –14 silver and –53 coppers. But not Ruby:
copper = -1453
assert_equal -15, silver
assert_equal 47, change
You owe 15 silver. And when you pay…you’ll get 47 copper back. If you want the C# (C++, C, etc) results, you’ll need to use positive numbers and handle the negative yourself.
I’ve been scratching my head around this, and it really seems like it’s an equally valid way of the numbers. The math people have both definitions lying around. And some cases have this method make more sense. Imagine you’re trying to find out what O’Clock it is. You have your hours variable and you use the mod operator. HOURS % 12. That works just fine, until you go negative. What if you wanted to know what O’Clock it was 143 hours ago? If it’s noon, and you’re using Ruby, –143 % 12 gives you the right answer.
I guess the accountants are right. “What do you want the numbers to be?”
In my recent post, I started sharing some of the fun of learning Ruby using Test-Driven techniques to learn the language features and document what you are learning as you go.
There are several advantages of learning the language this way. It flexes your brain in ways that just reading the book or typing in the sample code doesn’t. Once you’re done, you have some running, organized code that you can refer back to. Also, when you upgrade your language, or change which platform you run it on, you can run your suite of learning tests. Find out if Ruby 1.9 is different from 1.8…and how. Are there implementation differences between linux Ruby and Iron Ruby? You’ll know.
Today, I’d like to cover the additional assert variants available in the Test::Unit module, and talk about using an IDE.
Last time, we covered the assert method for testing truth. But there are lot more things you can test!
With this group of methods, it should be rather easy for you to write some nice, readable tests as you learn things up. One interesting one is assert_same, which can prove that all values of True are really the same instance. Also, when you write a test that fails by raising an exception, use assert_raise to document that. You should have a test that shows what happens when you divide by zero, and one that shows what happens when you use an uninitialized variable.
Using an IDE
Most of the ‘True Ruby Folk’ believe with all their flinty hearts that you shouldn’t need anything more than a charred and pointed stick to write excellent Ruby. They are probably right. On the other hand, a good IDE can be like a coding video game and make the process so much more colorful and fun. I’ve sure found that JetBrains’ new RubyMine IDE has made my early Ruby coding a bit of clicky goodness.
Creating a new test class is really easy. You just add the file to your project:
You get a fully fleshed and voluptuous test class ready for you to have your way with it.
And while you’re learning the language, it’s really nice to have some code completion features so that you can figure out the rest of what you’re typing without going mad switching between windows.
All that and it’s not going to break the bank. Just $99! Give it a try.
I hope you’re keeping up with your test writing. I’ve got 168 assertions testing language features and I’m just through the primitives and variable types.
How many tests can you write?
You may not have realized it, but learning Ruby is like being attacked by a bunch of ADD Buddhist Monks. They’ll jump into your living room, raving and excited, and do back flips while telling you how Zen and relaxing development should be. It’s weird.
Once we’ve medicated the frenetic relaxation, though, it’s really evident that there a lot of good ideas to be found in this community. The latest that I’ve discovered is Test-Driven Learning.
What this means to me is that I can FINALLY stop writing ‘Hello World’ programs. Languages have print or printf or puts commands—we can stop being thrilled by that now. Ok? Let’s just write Tests! If we can make test Assertions, we can kick the tires of each new piece of language syntax we learn as we learn it without creating silly, baroque programs to host them.
Lets start out by discovering the shortest syntax to use the language’s testing framework. The one built into Ruby is Test::Unit. This is easy in Ruby. You need a ‘require’ line and to subclass the test fixture class.
require "test/unit"
class TestTest < Test::Unit::TestCase
def test_tests
assert true
end
That’s easy. And now you can assert things. Like ‘true’. Save that in a file, like ‘test.rb’ then execute it with the ruby command line.
C:\Users\josh\Desktop> ruby test.rb
Loaded suite test_test
Started
.
Finished in 0.001 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
From here on out, just start adding ‘assert’ lines as you discover things about Ruby. Since we started with ‘true’, maybe some asserts on Truth would be a good start. I wonder which of these will pass and which will fail? If you know Perl, Javascript, or C# your preconceptions will be different.
assert false
assert 'True'
assert ""
assert 0
assert 1
So little code, and now you can curl up with your favorite Ruby howto book and spend a warm afternoon pondering the nature of Truth. Exciting eh? Well calm down! You don’t need to be a crazy Zen guy. Just do some learning.