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

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?