Dependency Injection Using Ninject with the MVC4 Web API
I’m exploring a few new ideas in a new project that’s using MVC’s Web API. I tend to use Ninject as my DI framework of choice: it’s simple, I like that it’s open source and it’s a very powerful framework.
Putting together new applications and sites has always been very straight-forward with MVC. I can create a repository for my data layer, throw together a few interfaces and just tell Ninject that when my app starts up, if it finds any references to IMyAwesomeRepository in a constructor then inject an instance of the MyAwesomeRepository class in its place.
Wiring Ninject up to your MVC project is incredibly easy if you’re using Nuget packages. There’s a Ninject.MVC3 extension that streamlines the process of wiring up ServiceModule classes to the Ninject kernel. Typically once the Nuget package is installed, all that is required is to tweak a number of lines in your Global.asax so that the application inherits from NinjectHttpApplication instead of the default and to override the OnApplicationStarted() method to wire the Ninject kernel up to the ServiceModule bindings.
A web application will commonly wire up its dependencies like this:
protected override IKernel CreateKernel()
{
var modules = new INinjectModule[]
{
new ServiceModule()
};
return new StandardKernel(modules);
}
internal class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<IFormsAuthenticationService>().To<FormsAuthenticationService>();
Bind<IMembershipService>().To<AccountMembershipService>();
Bind<IDatabaseFactory>().To<DatabaseFactory>();
Bind<IAccountRepository>().To<AccountRepository>();
// etc, etc.
}
}
The difficulty presented with the Web API is that Ninject bindings don’t apply to ApiController instances. To work around this problem you need to set up a dependency resolver explicitly. Chances are you’ve probably spent at least an hour or two if you’re new to working with the Web API and Ninject. The error you’ll receive when you try to hit one of your API endpoints will be the incredibly helpful error:
Type ‘MyApplication.Controllers.MyValueController’ does not have a default constructor.
The solution to this issue is out there; Phil Haack covered the topic almost a year ago. There’s enough information about how to configure dependency resolvers for MVC and Web API but the trick for new players is that much of this information was written before the MVC Web API Release Candidate was released, meaning some peoples’ cheese was moved once the RTM version went out.
To save you the litany of Google sleuthing and link following I had to do, here is the solution for DI in a Web API project using Ninject.
To handle the dependency resolutions, you need to create two custom classes that will be used by the NinjectWebCommon class installed with the Ninject package:
using Ninject;
using Ninject.Syntax;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Web.Http.Dependencies;
namespace MyApplication.App_Start
{
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
}
The NinjectDependencyResolver class takes a Ninject StandardKernel object as a constructor argument and this reference is used whenever a dependency scope is pipelined.
To make this all work, the NinjectDependencyResolver class is assigned to the application’s global configuration:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
You register your bindings as you normally would and your dependency injection in Web API methods is all set to go.
Hope this helps!
Authentication Using Firefox Persona and MVC
If you’ve been a Firefox user for a while, you might have seen a new feature being pushed out – Firefox Persona. “What’s the big deal? Firefox has been using Personas for skinning and themes on my browser since ages ago”, you might say. Well here’s the thing: There’s personas and there’s persona. One is the themes and skins for your browser and the other is an authentication protocol renamed from BrowserId in February this year.
If you think this naming convention is a bit ridiculous, you’re probably not alone. In Mozilla’s defence however, larger companies have been known to create their own marketing disasters with product names. Developers should instead get used to the Persona reference as being an authentication system utilising a verified email protocol (spec available at Github): a mechanism for websites to request, from the user via her user-agent, a signed assertion of email-address ownership. Web sites can use this mechanism to register users on their first visit and log them back in on subsequent visits.
So why Persona? Why bother with this particular authentication system versus, say, OpenId or Facebook Connect? There are a couple of good reasons why you’d consider using Persona for your site’s user authentication. First, it’s insanely easy to implement. Eventually Mozilla hope this protocol will be supported in all major browsers. As it stands right now, it’s not in any since the spec only went from a lab product to beta this week. Rather, the support for Persona is provided through a polyfill library that you include in your pages. Once you’ve added support, the API is essentially three methods:
Second, the user experience is much more streamlined, simply asking the user to associate an email address they own with this particular site. The browser remembers this email address for future use. The user doesn’t need to remember passwords, doesn’t have a registration process to go through and doesn’t need to be bothered by a login process on that machine again.
Authentication and Authorization in MVC Projects Using RavenDb

I’ve been getting a huge kick lately out of getting familiar with RavenDb. I’m just starting out, so there’s no doubt plenty I’m doing wrong and plenty that I’m not yet aware of by way of best practice. All the same, this “NoSQL” database is built specifically with the .Net framework in mind and it is just a pile of fun to play with.
When I’m building a new ASP.Net MVC site one of the most common things I’ll want to do is implement some degree of security. That is, authentication and authorization. Normally when you create a new web application the Visual Studio template will put together an application database, an AccountController and everything else that goes along with the Membership Provider. The trouble is that apart from likely being more clout than I need for a simple application, the existing .Net Membership Provider is a poor fit for RavenDb.
Microsoft’s Forms Authentication model works well for most situations. In a nutshell, all this is doing is writing a cookie for your application that confirms that a given user is indeed authenticated. This is available on every page request and I don’t really see a need to completely re-write the implementation for this. The Membership Provider deals with how users’ details and their passwords are stored and the validation of those users’ credentials. There are a huge number of methods and features available in this provider model that from a practical point of view become inefficient or downright annoying to recreate in a custom membership provider and I’m inclined not to use it.
I’m not the only one who thinks so. There are a couple of pretty good alternative membership provider solutions available for RavenDb although my preference is probably this one by Jonas Gauffin due to its cut-down and minimal implementation. The other resource I’ve linked to here is also very thorough and works well; YMMV.
For anyone wanting to roll their own auth code, there are two bundles provided by the RavenDb project: Authorisation and Authentication. The Authentication bundle is particularly useful if you plan on integrating an OAuth facility into your project. Ayende discusses this further in this YouTube video which also touches briefly on basic authentication principles with RavenDb.
Users
The RavenDb bundles deal with AuthenticationUser and AuthorizationRole objects / classes. Typical usage for an application user looks like this:
using (IDocumentSession Session = DataDocumentStore.Instance.OpenSession())
{
Session.Store(new AuthenticationUser
{
Name = Email,
Id = String.Format("Raven/Users/{0}", Name),
AllowedDatabases = new[] { "*" }
}.SetPassword(Password));
Session.SaveChanges();
return Session.Load(String.Format("Raven/Users/{0}", Name));
}
This creates a new user in the RavenDb database. You would pass in the values for Email, Name and Password and Raven takes care of the rest. The AuthenticationUser class has a convenient method for validating a user’s existence and password, named ValidatePassword():
using (IDocumentSession Session = DataDocumentStore.Instance.OpenSession())
{
return Session.Load(String.Format("Raven/Users/{0}", Username)).ValidatePassword(Password);
}
This returns a boolean in exactly the same way as calling Membership.ValidateUser() in conventional Forms Authentication.
Roles
Role management looks somewhat more foreign for users who are only accustomed to native .Net implementations. At its simplest, a new role is added in the following way:
Session.Store(new AuthorizationRole
{
Id = String.Format("Authorization/Roles/{0}", Name),
Permissions = {
new OperationPermission
{
Allow = true,
Operation = "*"
}
}
});
Session.SaveChanges();
The role name is passed in with the variable Name in the example above. Users are added to roles in a similar manner:
Session.Store(new AuthorizationUser
{
Id = String.Format("Authorization/Users/{0}", UserId),
Name = UserId,
Roles = Roles.Select(rl => String.Format("Authorization/Roles/{0}", rl)).ToList(),
Permissions =
{
new OperationPermission
{
Allow = true,
Operation = "*"
}
}
});
Session.SaveChanges();
Again, the UserId and a list of roles to add that user to (passed in as List
Roles also use a concept of tags, which in an MVC setting are well suited to ActionResult methods but might contain any such information the developer deems fit. The tags form part of the OperationPermission object that is included in the AuthorizationRole and AuthorizationUser objects. For example:
public static void Add(string Name, List Tags)
{
using (IDocumentSession Session = DataDocumentStore.Instance.OpenSession())
{
if (Session.Load(String.Format("Authorization/Roles/{0}", Name)) == null)
{
Session.Store(new AuthorizationRole
{
Id = String.Format("Authorization/Roles/{0}", Name),
Permissions = {
new OperationPermission
{
Allow = true,
Operation = "Cars/Add",
Tags = Tags
}
}
});
Session.SaveChanges();
}
}
}
What this is actually doing is to secure the individual documents (i.e. the entities in the database) by providing a mechanism for matching tags within each document to actions performed on their documents. Read the RavenDb documentation here for a clear description of how it can be made to work.
It should be pointed out you don’t have to go to this level of granularity for a basic MVC site. It is quite acceptable to create a set of Roles, then add AuthorizationUser records whose roles are defined as part of the record. RavenDb is quick and easy enough that you could just as easily call the user, find that user’s roles then match those against whatever role you have decorated your ActionResult with.
Overriding the Authorize attribute in MVC couldn’t be much easier:
public class AuthenticateAttribute : AuthorizeAttribute
{
IDocumentSession DocumentSession;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
using (DocumentSession = DataDocumentStore.Instance.OpenSession())
{
try
{
var user = DocumentSession.Load(String.Format("Raven/Users/{0}", HttpContext.Current.User.Identity.Name));
return DocumentSession.Load(user.Id.Replace("Raven", "Authorization"))
.Roles.Contains("Authorization/Roles/Administrators");
}
catch (NullReferenceException)
{
return false;
}
}
}
}
Now I can decorate my methods using this syntax:
[Authenticate(Roles="Administrators")]
RavenDb doesn’t require a lot of heavy lifting and basic operations are ridiculously easy and even fun to work with. I’m still finding my way around the best approach to certain problems but I’m finding that the simplicity of the framework is such that even mistakes are enjoyable learning opportunities.
If you’d like to learn more about RavenDb there’s an excellent TekPub series on the subject at http://tekpub.com/productions/raven
Search Engine APIs. Contrast and Compare
It was with quite a bit of interest that I received an email today from Bing advising that “the Bing Search API will transition to an offering made available on the Windows Azure Marketplace”. Within the PR hype were two pretty crucial pieces of information:
- Developers can expect subscription pricing to start at approximately $40 (USD) per month for up to 20,000 queries each month.
- After the transition period [completed in the next few months], Bing Search API 2.0 will no longer be available for free public use.
That’s a big deal. Here’s the full announcement. Why? Because it’s a lot of money for any business or amateur / hobbyist sites or applications to front up with at very short notice. Exchange rates may make this cost even more significant (for example, at time of writing $40 US dollars equated to $48.20 NZ dollars) and a few months may well not be enough time to compare different alternatives, test them and deploy them to a production environment.
So along that line of thinking, what are some of the different options for search APIs? How do their pricing structures compare and what limitations are imposed with each?
| Search Engine | Cost | Per | Cap (in queries) | Link | Notes |
|---|---|---|---|---|---|
| Free | Day | 100 | Google API | All additional requests over the 100 daily request cap are charged at the rate of $5 per 1000 queries, for up to 10,000 queries per day. | |
| Baidu | Free | Week | Quota | Baidu API | The quota system is not clear on the initial allotment of allowed API calls |
| DuckDuckGo | Free | Always | None | DuckDuckGo API | Search engine attribution requested in results |
| Bing | US $40 | Month | 20000 | Bing API |
Yahoo! search APIs were deprecated in April 2011 in favour of Bing when Microsoft finally secured a stake in the search giant.
DuckDuckGo is the darling child of bleeding-edge web enthusiasts and power users with its !bang syntax, strong keyboard shortcut support and quirky UX.
Baidu appears on this list because despite being almost exclusively Cino-centric, it commands a very high ranking in global share purely by virtue of the population it serves. However I found it extremely difficult (using the translated English description) to find concrete numbers regarding the Baidu quota system and the complexities around the calculation of API query totals.
A Bung Move for Bing?
With most of the main competitors offering a free service for low-end users or, in the case of DuckDuckGo, a completely free service, it’s difficult to understand what Bing is trying to achieve with this decision. It seems on the one hand that Bing would want to drive as many potential customers away from the “not evil” Google in favour of its own services but charging from the outset across the board for all users would likely achieve exactly the opposite.
Maybe Microsoft are trying to position themselves in a niche within the search market that targets higher-end enterprise customers. Their API is solid, their results generally good and the options around the delivery of those results are very broad but the pricing model still sets a barrier for entry that will in all probability make Bing a second choice at best behind its competitors.
So there it is. Do you know something I don’t? If I’ve overlooked or misunderstood some details around the Bing or other search APIs, add a comment below or tweet me. I’ll be really interested to see where this is going.
Putting the “You” in Community – Why You Should Care to Get Involved
I was very fortunate to have Scott Hanselman agree to stop by The Office for a casual meet and greet with some of our development folks yesterday and it was a really valuable couple of hours. We chatted about general stuff, asp.net stuff, Microsoft management layers (Way more than three degrees of separation between himself and Ballmer. Who knew?) and – resonating particularly with us – community. Scott feels quite strongly about the .net community but thinks it has quite some way to go before we – collectively – are really “there yet”.
Scott is in Wellington this week for the 2012 Webstock conference (great conference, by the way. Really valuable speakers, workshops and networking opportunities. Get along if you can). An interesting observation he made was that people would ask where he was from and when they heard the answer, “Microsoft”, they usually reacted with indifference or borderline sympathy. This is a shame. Microsoft has moved a long way since those days and he’s quite right to say there are more evil companies than this now. There’s like a “Technology Stack of Evil” that puts Microsoft way down the list. They’re only quasi-evil. The diet coke of evil, as the quote goes. Just one calorie; not evil enough.
I wanted to do some kind of inverted pentagram, but couldn’t visualise how to arrange the members hierarchically (submissions or suggestions gratefully received). The Fox network and large bank CEOs probably fit somewhere in the middle there, by the way.
Anyway, the point – and there is one – is that the .Net Community (that’s probably you if you’re reading this) needs to follow Microsoft’s lead in the open source and community spaces. As a community the observations seem to be that we’re isolated into pockets, not constructive with our interactions with each other or not as engaged with sharing information, code or effort as, say, the Rails community.
That might seem a bit cynical. You look at Stack Overflow and you’d think that any .net question was filled quickly with good, helpful and constructive answers, but when you think about it, that’s an artificial construct that actively drives and promotes that sort of behaviour. Actual contributions by way of blogs, site content or (and this is a big one) open source participation are actually much lower in practice.
Possibly this is because the Microsoft stack makes it so easy to build your own projects and – for the most part – makes it so fun, that people do exactly that: spend their time learning, refining and growing their craft by projects that are personally significant to them. Possibly it’s because people aren’t familiar with how open source works and are reticent about dipping their toes in the water. Or possibly it’s because people are afraid to get involved with an open source .net community project because they haven’t found one they feel passionate enough about and are probably a bit scared they’d only get in the way or be shot down for making mistakes.
Whatever the reason, this is why we as a community need to get behind events such as the Webstock workshops, speaking or networking events and local area user groups. Individuals aren’t going to learn, improve and grow their skills and their craft by staying at home and coding in their living room (although that helps). Get involved! We need to support events that are being organised for .net users; get passionate and contribute to projects that are community-facing and above all be constructive and supportive of those of us who are stepping out of our comfort zones and trying to engage.
This is why Hanselman is so highly regarded in the .net community: because he always makes the time to encourage, lead and support. But that’s a lot of responsibility for one guy. We need more leaders like that who we can look up to in our own regions. Hanselman says “Tweet less, blog more” in his post from early January titled “Your blog is the engine of community”, I’d argue tweet more if that means you are trying to engage in your community and widen your network. Meet people. Talk to them and find out what sort of common ground you have in the .net space. Find ways to collaborate or share knowledge. Argue your case to attend those conference opportunities. Everyone benefits: you learn new stuff, the community grows and leaders emerge that reinforce this pattern so that everyone profits from being better at what they do.
Working With Checkboxes and Other Controls in Word Using OpenXml
Microsoft’s adoption of the OpenXML format for its Office documents such as Word, PowerPoint and Excel has meant that developers can provide considerably improved experiences over the web and on desktop applications when working with Office documents. For example, it used to be the case that in order to serve up a Word document from a web server, you needed to have Microsoft Office installed on that server. While this might still occasionally be the case, in most instances you can now reference the OpenXml SDK and create a Word 2007 / 2010 document on the fly.
While the OpenXml framework offers a huge improvement in interoperability, it also adds a reasonable degree of complexity if you’re trying to work with attributes of a document that would generally be considered outside of the “routine” tasks of working with text and layout. My specific problem last week was trying to get references to checkbox controls I’d placed in the document and read or manipulate their states. The trick, it turns out, is knowing your checkboxes from your checkboxes. Not all checkboxes are created equal.
Understanding Control Genealogy
The Microsoft Office suite has evolved from a set of applications that employed proprietary binary file formats, windows-centric embedded controls and a litany of other ideosyncrasies that served their purpose at the time, but are little more than legacy relics today. Still – they need to be supported and we are therefore left with quite a diverse range of possible controls that might be found in a given document or spreadsheet.
What this means is that when working with embedded controls – particularly those used in forms such as checkboxes, dropdown lists and the like – we have to be aware of what kind of control is actually being used and thereby how to access it. In working with Word, we’re faced with three different incarnations of the checkbox: the “legacy” control, the ActiveX control and the most recent “Content Checkbox”.
Let’s look at how to get to each.
Legacy Checkboxes
The following code shows how to iterate across legacy checkbox controls. The Parent node of the checkbox holds information such as the name of the actual checkbox instance. To get identifying information we need to traverse up the XML tree and retrieve the FormFieldName element.
using (WordprocessingDocument doc = WordprocessingDocument.Open("c:\\checkbox.docx", true))
{
foreach (CheckBox cb in doc.MainDocumentPart.Document.Body.Descendants())
{
Console.Out.WriteLine(cb.LocalName);
FormFieldName cbName = cb.Parent.ChildElements.First();
Console.Out.WriteLine(cbName.Val);
DefaultCheckBoxFormFieldState defaultState = cb.GetFirstChild();
Checked state = cb.GetFirstChild();
Console.Out.WriteLine(defaultState.Val.ToString());
if (state.Val == null) // In case checkbox is checked the val attribute is null
{
Console.Out.WriteLine("CHECKED");
}
else
{
Console.Out.WriteLine(state.Val.ToString());
}
}
}
ActiveX Checkboxes
ActiveX controls present a more problematic situation. The OpenXML spec is not concerned with ActiveX controls, which are Windows-specific program building blocks and OpenXML is focused on interoperability across operating systems or platforms.
The code to find an ActiveX control is a lot more verbose and requires us to “sniff around” to check the class type of any controls found in the document. We can find ActiveX controls using the Control element type:
foreach (Control ctrl in doc.MainDocumentPart.Document.Body.Descendants()) { Console.Out.WriteLine(ctrl.Id); Console.Out.WriteLine(ctrl.Name); Console.Out.WriteLine(ctrl.ShapeId); }
As I’ve already mentioned, we can’t differentiate between ActiveX controls within the SDK framework itself, meaning we need to check the class ID of any control we find. The class ID for a checkbox is {8BD21D40-EC42-11CE-9E0D-00AA006002F3}.
OpenXmlPart part = doc.MainDocumentPart.GetPartById(ctrl.Id);
OpenXmlReader reader = OpenXmlReader.Create(part.GetStream());
reader.Read();
OpenXmlElement el = reader.LoadCurrentElement();
if(el.GetAttribute("classid", el.NamespaceUri).Value == "{8BD21D40-EC42-11CE-9E0D-00AA006002F3}")
{
Console.WriteLine("Checkbox found.");
}
reader.Close();
It’s a cumbersome and counter-intuitve approach and would ideally require the developer to replace any of these controls where possible.
Native Content Controls
As previously mentioned, Office 2010 introduces a native set of controls that are more manageable when working with the OpenXML SDK. These controls are differentiated using the SdtContentCheckBox type.
using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true))
{
MainDocumentPart mp = doc.MainDocumentPart;
foreach(SdtContentCheckBox cb in mp.Document.Body.Descendants())
{
if(cb.Checked.Val == "1");
{
Console.Out.WriteLine("CHECKED");
}
}
}
Form controls are somewhat tricky to work with but hopefully these examples go some way toward clearing up their quirks and traps.
Importing Data Into SQL Azure
![]()
I was working to get an updated set of data from my local development machine copied up to a Windows Azure database today and spent a lot of time trying to figure out why I couldn’t simply copy the data using the SQL Server Import and Export Wizard. Getting a connection between the two databases would always succeed, but as soon as I had picked my source and destination databases, clicking Next would always produce an error:
The stored procedure required to complete this operation could not be found on the server
While Microsoft may have good intentions of eventually supporting data import / export using the more familiar OLEDb provider, as it stands right now, selecting OLEDb will not work as it is not currently supported by SQL Azure. Looking over the MSDN articles is of little help, with suggestions that the wizard is used and links to various unhelpful resources. That said, there is a very good article on the TechNet Social pages.
It turns out that you are still able to use the wizard, but in order to get the data imported, you should use the .Net Framework Data Provider for SqlServer as the Data Source. Populate the values from your connection string into the corresponding fields in the dialog then carry on as normal.
Hope this helps!
Design Never Stops
When was the last time you wrote a new class?
I left my management position at a highly toxic work environment in June this year to start at a highly reputable software shop as a senior support developer. Support is an entirely different discipline to project development: its primary point of involvement is after a piece of software has shipped. Often it involves working with technologies that aren’t necessarily on the bleeding edge and – more often than not – the most common task is one of maintenance and bug-fixing rather than enhancement and evolution.
Typically when developers are in a maintenance role – or even seconded to a maintenance project – they don’t find themselves adding new classes very often at all. They’ll add new methods to existing classes or refactor old methods because the design phase “is over”. I’ve worked in various types of support development roles over the years and it’s an unfortunate fact of life that in most cases once a product has shipped, the design phase is considered to have been completed way back in the early stages of the application’s life cycle. The client has spent the budget they had alloted to the solution, there are other solutions that need to be built or there just isn’t time to continually revisit and refresh the application.
So the maintenance phase becomes less about keeping the solution up-to-date and supportable and more about functional preservation and ad-hoc enhancement. Michael Feathers (author of “Working Effectively with Legacy Code“) asserts that design is a continuous process: never completed. You should always be creating new functions and new classes.
I’m supporting (among other things) a VB6 applicationright now that uses a bit of Classic ASP thrown in for good measure. I am actually enjoying this because I can identify lots of areas where the design can be evolved and improved. The hard part in these situations is convincing the client that it’s a worthwhile investment. More often than not the general response is “Well, it’s working just fine as it is right now so I don’t really see any need to fix something that isn’t broken”.
As an application grows, evolves or ages the fear of making changes and especially deploying those changes into a production environment grows with it. This situation is exacerbated by not having any unit tests but the crux of the problem really comes down to two areas: cost and fear of change.
Fear of change is a valid concern in some respects. If you haven’t updated your application for some time or it’s a business-critical system, you’d be justifiably concerned about introducing any unnecessary risk to your systems. However the flip-side to this argument is that you would also – as a responsible business – want to ensure that the stability, availability and continuity of your applications was as assured as possible and a good way to ensuring this is to release regularly and often. The metaphor of a medical or dental check-up comes to mind where prevention is the best cure. Leaving problems untreated until they’re real hazards is both costly and risky when regular maintenance and selective modernisation would have likely avoided these situations altogether.
Investing the time and relatively low amounts of money in the ongoing design (i.e. paying back your software mortgage) is good business practice and better value for money than leaving your application neglected and unloved until age and technology advancements mean more serious problems arise.
Ninject and Entity Framework Code First: Easy repository patterns
When I was still learning the basics of Dependency Injection (DI), Repositories and Object Relational Mappers (ORM), it was a pretty long struggle to get my head around when much of my professional career had revolved around web forms and .Net 2.
It was only through playing around with code in my spare time that things gradually fell into place. I’m not a gifted developer savant like Scott Hanselman, Steve Sanderson or Rob Conery. Stuff doesn’t just “make sense” as soon as I read it. I need to walk through slowly and see stuff working first before trying to understand how it works.
So having gone through many failed or flawed implementations of the repository pattern and almost-but-not-quite getting DI to work correctly (let alone trying to get my head around Inversion of Control), I believe I’ve finally hit upon a clean, simple repository structure that allows good separation of concerns, highly-testable code and makes coding up my MVC3 sites an absolute doddle. It should be noted that I’ve only been able to reach this point by reading, observing examples and borrowing heavily from other cases out there in the world.
Over the next few posts, I’m going to discuss what I’ve found is working great for me, what’s actually happening and why I’ve done it that way. I’ll also go down a few side-routes to discuss other useful tools or tricks that I’ve found increase my productivity or standard of work.
I’m going to use the same example project throughout: an ASP.Net MVC3 application for support ticket management. This project uses the new Razor syntax, a bit of jQuery and some other fun odds & ends.
Simple Console Debugging
One of the most common tasks I carry out when building a new web application is to check my JavaScript performance and debugging in the browser console. The console window is one of the most indispensible tools in the developer’s kit and it’s very commonplace to see smatterings of “console.log(…);” throughout the app’s code.
What you may not know is that there are a lot of additional functions available than the omnipresent console.log command.
Inspecting Javascript Variables
The most convenient use of firebug for me is of seeing the JS variable values as I develop a complex client-side application. As I discussed above, you don’t want to see alert boxes again and again, IE developer tools, do that for you in two ways.
You can use console to see any output messages. To differentiate between these messages, different console.log APIs are available:
- console.log
- console.error
- console.warn
- console.info
- console.assert
My preferred command in Firebug used to be console.debug but I left using that long ago because IE Developer Tools support was buggy and usually broke my code. Secondly firebug formats logged objects nicely so that they are written not as static text, but as interactive hyperlinks that can be clicked to inspect the object in Firebug’s HTML, CSS, Script, or DOM tabs.
I have now moved toward using a more common set of debugging commands:
var myvar = 0; console.log(myvar); console.error(myvar); console.warn(myvar); console.info(myvar);
These commands are great in that the provide additional formatting to add visual cues to your debugging code as needed.
Browser Handling
Depending on the type of browser you’re using (oh, who am I kidding? If you’re using old versions of IE), you may get JavaScript exceptions being thrown, saying that console.log is undefined. Browsers that don’t have a native set of debugging tools will throw this error because, obviously, they don’t have a JavaScript console. You can get around this problem with the following code at the beginning of any globally-used script files.
if (typeof console == "undefined") { window.console = { log: function () { // do nothing } }; console.warn = console.debug = console.log; }Ben Alman has a nice little debugging script that can be included as a simple wrapper for console logging.








