Pages

Monday, May 19, 2014

Things to do in a fresh ASP.NET MVC Project

Do remove the custom ASP.NET HTTP response headers

There's no need to send

X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
X-AspNetMvc-Version: 2.0

To your client's browsers all the time.  Add this to in your application's startup to stop doing it.

MvcHandler.DisableMvcResponseHeader = true;

Do use code analysis (fxcop) on build

Use project -> properties -> code analysis to configure it.  It's a lot less painful if you do it from the beginning.

Do decide what to do with your XML and JSON formatters

You can do this and just remove XML as a supported response type.


    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

BUT you may want to support JSON API calls in the future.  If you don't, I suggest just removing the formatter.

Do install the Web Essentials Plugin

http://visualstudiogallery.msdn.microsoft.com/56633663-6799-41d7-9df7-0f2a504ca361

This plugin contains many experimental features that eventually make it into ASP.NET, but is very stable.  

Do create a Visual Studio schema comparison for your various database environments.

This is the simplest way for a developer without 3rd party products to move schema changes between Dev/QA/Staging/Prod

Do create XML document transform files for your various environment deployments.

In production, be sure to use to prevent yourself from accidentally leaking stacktraces and to ensure you're compiling for release

<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>

Do create an appoffline.htm page

By default, your web server will server this file for all requests if it exists in the root of your web application.  Be sure to embed any CSS/JS you use, users won't be able to request your application's CSS/JS files when this file exists!

Consider installing SignalR for real time application features.

It's important to consider your installation of Signalr because SignalR 2.0 now requires .NET 4.5.  If you're planning on making an application or set of libraries that work under 4.0

Bonus : General Visual Studio Tips


Do learn the hotkeys
  • ctrl + , 
  • ctrl + q
  • ctrl + k + x
The first two you will find yourself using all the time after you learn them.

Ctrl + , will intelligently search your code in Visual Studio 2013.  It's still useful in 2012 and less, but the 2013 version will knock your socks off.



ctrl + q is the closest you'll get to a command line IDE.  You can search just about anything outside your project in visual studio by hitting control + q.  A cool bonus is that the input is buffered; for example, if you quickly type ctrl + q + type 'sql' + enter it will still bring you to the  before the results are rendered, it will catch your input and immediately bring up your result in the IDE.  


The last, try yourself!  It's the homework for the reader

Note : some of these recommendations are sourced from http://stackoverflow.com/questions/54929/hidden-features-of-asp-net 


Sunday, November 17, 2013

JavaScript Binding, Templating and Reactive Programming without (much) of a framework

Working on existing projects or projects where the main framework isn't MV* or 2-way bindable or easily template-able can be challenging.  For some projects, they aren't always the best choice.

Here are some techniques we can use if we want to imitate a similar style without actually using any of them.

Delegation

Delegation in jQuery allows you to attach a handler to the children elements of a selector for the lifetime of that element.  This is a super powerful feature of jQuery and not often utilized.

For anything involving adding and removing items in a list (that's a lot of use cases!), I would recommend using this to maintain event handlers.

Event bindings in templated lists is a huge benefit of KnockoutJS and AngularJS.

Note : .delegate is deprecated and you should use .on to achieve the same in newer versions of jQuery

Similar to : foreach templates and template event binding

You can view the below jsfiddle here jsfiddle.net/U3bum

Observing variables

Observing changes in variables is a key feature of any popular MV* framework.  Unfortunately, without a binding framework you won't be able to automatically update your UI.

But you can still make it so that your UI updates with the minimal amount of code and excellent separation of concerns.  If you write code like this, you'll be able to have your business logic in one place and your DOM updating code in another.

How often do we run our business logic and then immediately update the same DOM element from multiple places in our code?  Think about this when you look at the below example that shows you how to subscribe to changes in variables.

Similar to : Knockout observables

Here's a jsfiddle with sourced variable watch plugin

You can view the below jsfiddle here jsfiddle.net/fbnXb/1

Don't Embed HTML in your code; use $.clone() instead.

This will seem obvious to most, but you should keep all of your "templates" in a hidden div and then select and clone it.  If you don't use a templating framework, favor the decision to leave HTML intellisense intact and templates separated from JavaScript code.  You'll thank yourself later when your project is more maintainable.

If you just want a good templating framework, mustacheJS is the way to go.

Similar to : Templating (all) 

Favor higher events like 'input'

Avoid events like 'keyup'.  'keyup' is an excellent way to find out if a textbox has had its value changed but you start running into edge cases like people copy-pasting into your textbox.  

Handling the wrong event leads to edge cases. Binding frameworks rarely expose cruft like this except in the unusual case.  The beauty of using a MV* framework is that someone with a lot more domain knowledge  has thought about the usual use case, made that the default, but still allows you to have unusual behaviors with little configuration if you really need them.

Without a framework, you'll have to explore events carefully to reduce boilerplate and allow you to get to the heart of the problem you're trying to solve.

Similar to : New events exposed in binding frameworks

Other tips?

If anyone has any tips on imitating 2-way binding and templating, I'd love to hear them!  A lot of projects aren't ready frameworks for a variety of reasons and I love thinking of how to solve a problem with less at my fingertips than I'm used to.  

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