Pages

Thursday, August 22, 2013

You don't say, MSDN [Lightswitch]





They may be onto something here..






Glad we could clear everything up about testing Lightswitch applications.

I know Lightswitch is aimed at people who aren't necessarily developers, but come on!

Not meant to be inflammatory, just a funny little thing I noticed.  Lightswitch actually seems really productive for intranet applications!

Friday, June 28, 2013

Great New Feature of F# 3.1 (CRUD applications rejoice)

I was pretty disappointed when I asked on stackoverflow how I could easily compose predicates in F# (because this is so easy in C# with LINQ)

Thomas Petricek gave me a thorough and clear answer and it's really impressive that the entire language is quotable.

http://stackoverflow.com/questions/13826749/how-do-you-compose-query-expressions-in-f

The only problem is that this code is really hard for a beginner to write; so you're still probably going to be using the query computation expression for your SQL/ORM/type provider queries as a beginner.

So here's what you'll be writing ( source : http://msdn.microsoft.com/en-us/library/vstudio/hh225374.aspx )

query {
    for number in data do
    skipWhile (number < 3)
    select student
    }

To me, this is the second coming of SQL and LINQ/fluent style is preferred.  Composability and modularity are completely lost on this style unless you do some quoting/splicing.  I was really disappointed that the normal way to query in F# was so weak, and the best way was a bit too complicated with a lot of upfront thinking required.  

Up until today, C# provided a more flexible way of accessing external data. Even if they had to add many language features to make this happen, easier to use is still easier to use.

Well, today they announced F# 3.1 which will provide real support for using LINQ-style extension methods.  Anyone making CRUD applications should seriously consider giving F# a try now.


Friday, June 21, 2013

Beginning ASP.NET MVC dependency injection and automated testing

Let's take a look at testing the simplest MVC controller that could prove the worth of automated testing/dependency injection.

Our task is the following:
  •  For users configured to view English webpages, output "Hello World!" 
  •  For Users configured to view Spanish webpages, output "Hola Mundo!"
  • For users configured to view any other language, throw an exception.
We will prove our application performs this way via automated tests.

The way we know a user's language preference is via the 'Accept-language' header in an HTTP request.


Getting this information out of the request is simple.  Anywhere in your code you can write the following to get a user's most preferred language :


BUT you have to be sure that HttpContext has its properties set (its properties are set in thread local storage by ASP.NET, for those wondering).  In other words, this will only work when executing as part of a web request.

This poses a problem for unit testing.  When you write a test like this:

It will throw an exception when it tries executing your controller's action because the test runner isn't running your code with a set HttpContext.

Dependency Injection

The best way to make our class testable is to use dependency injection.  

We're going to setup our controller to get the preferred language from a class that implements IRequest, an interface that looks like this


And we'll implement it using the one liner for preferred language like we did above 


The major difference to the code we are trying to to test will be that we going to have our controller rely on the IRequest interface as opposed to using the HttpContext class directly. Our class will look like this :


Now, all we need to test our controller is a stub of IRequest that will allow us to specify the incoming language.


This now allows us to write three comprehensive tests where we can actually specify the language ourselves and prove the behavior of our controllers even though we aren't actually receiving an HTTP request.

In production : [Inject]

For this to work in production, you may have noticed in the HomeController class I'm using an 'Inject' attribute which will eventually resolve to an instance of  the 'Request' class when the code is serving a real HTTP request.

How does this work?

I'm using a third party library called Ninject (the MVC 3 package) that lets me easily specify these bindings for the production run of the app.  Meaning, that after HomeController gets allocated, the IRequest will automatically be set to my Request concrete class.

Obviously this mapping must be done to ensure that when my code is running as an MVC application, and not in unit tests, that its using the class that utilizes the real HttpContext.

Conclusion

What we have accomplished

  • Wrote a controller that only depends on an interface, not a built-in ASP.NET class that only works inside an HTTP request.
  • Proved our controller works for three different language scenarios (would be quite a pain to have to change your browsers language setting to test each scenario).
  • Can see that dependency injection is useful for unit testing classes that have external dependencies.  Other external dependencies include : file systems, databases, and web services. 
  • Used Ninject to make property injection as painless as possible in production.


Thursday, May 30, 2013

New Site Launched : CSharp.io

I've launched a new site Csharp.io

Its main feature is that it adds intellisense to C# code snippets in the browser as well as allowing you to embed them everywhere.  Here is an example. It also offers some social features and a nice UI for browsing and posting snippets


Friday, April 26, 2013

C# Snippet Sharing with Roslyn and SignalR

I've begun creating an Azure app that will take sharing C# to a new level

You can check out the initial plan for it here

http://www.codeproject.com/Articles/583477/Csharp-Snippet-Sharing-with-Roslyn-and-SignalR

I've had the idea for a while, but decided to put it in writing and enter the idea into the Windows Azure contest currently going on at CodeProject

Monday, April 1, 2013

Removing excess lambda expressions with a Roslyn Visual Studio plugin

I've created a Roslyn application that will let us write LINQ statements and make sure that we don't copy and paste them in the same class

The plugin, called 'Refactor Lambdas' does the following :

  • Looks for duplicated lambda expressions
  • Once detected, breaks them out into a separate function
  • Names the function something based on what the function is doing
  • Has some capacity to do fuzzy matching (if 2 lambdas are both the same logically but use variables  from the outer scope with different names and the same type, it can still refactor those 2 lambda expressions)


Showing may be easier than explaining in this situation.  Here's how the plugin would react to a scaffolded controller from the MVC scaffolding project (A gallery of images is below if you don't have Flash)





Here's a link to the repository on BitBucket


I would enjoy having this as apart of ReSharper so I think it's actually a worthwhile plugin.  Also you could get really crazy and search the entire codebase, with a fuzzy search, and condense all duplicated lambdas.  It would have to be torn apart but I think this is a good end-goal to have with this project.

Some Todos in case anyone is interested.  This would be a good project for someone to get their feet with in open source :

  • Unit tests are good but need a little work.  I could not find an easy way to unit test without specifying cursor position in each test; yuck.  Still has >90% test coverage and does all testing in memory.  Could use some negative tests.
  • Fuzzy matching could be improved when deciding if 2 lambdas are equivalent. 
  • Make it work on files with multiple classes (not really super important--right now it just takes the first class and does the search there)
  • Speed considerations?  Any way to detect this code issue more efficiently?  
I'll release this as a Visual Studio plugin on the gallery once Roslyn is finished and pushed out to Visual Studio 2012 and is enabled by default.  Comments?

Monday, March 18, 2013

Which ASP.NET MVC validation strategy should we use?

At least as long as programming has existed, people have tried to be tricky.

I'm sure we have all tried to architecture something tricky only to have to revert our project and sheepishly go with a simpler solution.

Whenever I look at something that isn't a tricky optimization, it's almost always a tricky way to waste cpu cycles.

The lure of trickyness we'll be looking at is validation in ASP.NET MVC.  Let's look at 3 methods of validation.

The bad way (using model objects)


Unless you want to get hacked in the same fashion github did last year, don't do the following.  You leave yourself open to getting model injected if you do this; only new MVC users will try using model objects bound to a view.  The initial lure might be that you can do this without creating an extra ViewModel.


It's not an extensible way to write code anyway so luckily you have an excuse to not be lazy.  The second you need to use the same domain object on multiple pages for even slightly different purposes, this pattern falls apart and subsequent pages will have trouble accommodating new functionality.

Add a field like this and now we have a security problem because model binding is blind and will greedily bind anything it can.
Actually the above example is prone to being insecure out of the box.  If you only wanted to let the user update their email and password, you'd have to specifically guard the Username and Id (and any new fields as I point out above).

It also shows how unclear the above code is--you may have assumed I was taking the Id and Username from a submitted field even though this was for a profile editing controller.  It's even less readable.


The tricky way (using centralized validation close to your model)


Okay, fine we'll use ViewModels, but we're going to be tricky.  We're going to keep all of our validation inside our domain objects.  When someone goes to input some data, we'll map to our domain objects, check the validation rules and then bubble the results up.  It's genius.

Actually it's bad.  For several reasons.  Exceptions to rules will be painful.

Let's not say things we don't mean and have to take them back


It also doesn't take advantage of the model state of MVC which I find to be quite nice and allows you to check errors separately.


  • Once for easy validations like max length and whether a field is required, 
  • Again for dynamic validations that involve costly database operations.


Bundling those two operations isn't good.  Without a simple way to perform client-side checks, that's what you'll be doing (I would just bundle them on the server if you have jQuery validate on the client for the sake of saving a few lines of code in each controller).  .

I don't care what horrid path Visual Studio Magazine (scroll to 'Integrating annotations') is trying to send you down.  Don't do the tricky way.  It's cute little examples like this have people being tricky.  But then you feed tricky after midnight and bam...code gremlins.  They even seem to recommend 'The bad way'.

This pattern could work in a fully back-end scenario, but this next pattern is just too durable, efficient and fast for anything else to be used for ASP.NET MVC development.

The smart way (also the easiest way -- using ViewModels and validation attributes)



A good example.  Simple and gets created in the default MVC4 project template.


But author, creating a view model AND validation attributes for each form is more typing.  How is it the easiest way?  Because ordering your thoughts is hard.  Not being able to trigger your validation on the client, is hard.  Having to mess with your DbContext just validate user input (noise++ to your codebase) is hard.  Having to make an exception to what you thought were your domain rules becomes a hack (I'll remove this one validation rule..)

Let me be clear about that last point.  Adding something and then removing it later down the pipeline before you do any real work is a HUGE anti-pattern.  I don't know this anti-pattern by a name, but this is one of the biggest mistakes I see in code.  It's unclear, it's a hack, it's inefficient, it shouldn't be done.


Here is the article to read that will explain the best practices of the ViewModel pattern.   (Although the author doesn't mention that your HTML will be rendered with jQuery validate baked into it which is a big plus)


It's worth noting that this works great with ajax heavy sites.  I almost exclusively use ajax to submit forms and working with data annotation attributes is still preferred.  Data annotation validators will cover any  non-dynamic validations you need.  The jQuery validate attributes will be rendered in your HTML which you can easily call out to yourself (a huge benefit over the previous example--an easy way to make super responsive pages by having automatic client side validation.)

The ViewModel pattern solves so many issues.  It's not completely D.R.Y., though.

Or is it?

If you have two pages that allow modification of a profile (lets say, registration and profile updating) you will have to copy and paste your name length validator attribute to both view models.  I would say that attributes are data and not code (we've been blurring the line lately.. look at expressions) and that the code is still D.R.Y.

Conclusion

Most MVC developers already know, and practice, everything I've said above.  So why would I spend my time writing about it?   Because why not examine the other avenues and possible architectures even if they end up being poor choices?  If you ever felt like maybe you were missing something or you were wasting time when writing a bunch of ViewModels and repeating attributes on them, well, you should feel a bit more justified after reading this.  It's the standard--keep doing it.

Also, hasn't everyone tried conquering validation with a tricky pattern at some point?  I think the answer is probably yes.  But at the end of the day, being as specific as you can and failing as soon as you can (Client passes -> server side checks passes -> dynamic server side checks pass -> okay go), is always going to be king and it does not facilitate tricky patterns.

This post may leave you thinking about unit testing as much as possible because there are some maintainability considerations with validations attributes on ViewModels even if this even if it is the best way to write your MVC application.  What do you think?