• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Thursday, 16 May 2013 09:12

Continuing from the controllers post, the parameter to the controller function is named $scope.

var AboutController = function($scope) {

    // ...    

};

The name $scope is important since it allows the AngularJS dependency injector to know what type of object you are asking for, in this case an object that will contain the view model. Any plain old JavaScript you attach to $scope (properties, functions, objects, arrays) is eligible to use from the expressions inside the view.

In the last post our model was relatively “flat” in the sense that properties and functions were added directly to $scope:

$scope.rabbitCount = 2;

$scope.increase = function() {
    $scope.rabbitCount *= $scope.rabbitCount;
};

This allowed us to use rabbitCount and increase() in the markup that was inside the view scope (the div) of the AboutController:

<div data-ng-controller="AboutController">

    <div>Number of rabbits in the yard: {{rabbitCount}}</div>

    <button ng-click="increase()">More rabbits</button>
    
</div>

You can think of $scope as the execution context for the expressions in the view. Saying ng-click=”increase” results in a call to $scope.increase. The only thing tricky to understand about $scope is that having a controller inside a controller, or a controller inside an application (which you’ll always have), will result in nested $scopes, and a nested $scope will prototypally inherit from it’s parent scope by default. This is why $scope is injected by angularJS – the framework sets up the prototype chain before giving your controller the $scope object to use as a model.

Inheritance means a view has access to it’s own scope as well as any inherited scope. In the following example, the view inside the ChildController markup can use an expression like {{rabbitCount}}, and this expression will read the rabbitCount property of AboutController’s scope ($scope.rabbitCount will follow the prototype chain).

<div data-ng-controller="AboutController">    

    <div>Number of rabbits in the yard: {{rabbitCount}}</div>
    
    <div data-ng-controller="ChildController">
        Number of rabbits in the yard: {{rabbitCount}}
        Number of squirrels in the yard: {{squirrelCount}}
    </div>

</div>

The one place to be careful with the inherited scope is with 2 way data binding. The way JavaScript prototypes work is that writing to the rabbitCount property of the ChildController $scope will add a rabbitCount property to the ChildController $scope and effectively hide the parent property. $scope.rabbitCount no longer needs to follow the prototype chain to find a value. More details and pictures on this scenario in “The Nuances of Scope Prototypal Inheritance”.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Wednesday, 15 May 2013 09:12

I watched the dotNetConf .NET Open Source Panel last week. It was a bit disappointing to hear defeatism in the voices of OSS project leaders, because .NET’s future appears to rely entirely on the success of open source software for .NET. Here are a couple reasons:

1. The success of Windows Azure. Azure is now an amazing cloud platform for developers and is getting better every few weeks. Azure is also a business success with annual revenue topping $1 billion. That’s $1 billion with only a 20% share of a $6 billion dollar market – a market that is expected to grow to $30 billion in 4 years. As Azure continues to pick up market share it is not completely unthinkable to see it post a 15+ billion dollar year in 2018, which is getting into the same double-digit-billion-dollar-revenue neighborhood as Windows itself.

The documentation page for Azure makes it clear where the growth will come from:

Azure Strategy 

To paraphrase the above graphic, Microsoft doesn’t need legions of developers building frameworks and tools for Windows developers when they can have legions of programmers building tools and a cloud platform for all developers. Hadoop, Redis, NodeJS, RoR, Django, PHP, and the list goes on. Even if it doesn’t run on Windows, you can always spin up a ready made Azure virtual machine image with Ubuntu, CentOS, or SUSE.

I don’t think Azure needs a successful server-side .NET framework to be a success itself.

2. The Direction of Windows 8.

I still feel Window 8 carpet bombed .NET developers. There was secrecy and hearsay followed by the death of one XAML platform and the arrival of yet another slightly different XAML platform. People running a business based on desktop technology don’t know where to place their bets and the Windows division has always appeared hostile to the CLR. I’m not sure what this year’s Build and Windows Blue will bring, but I can only hope it offers some direction for businesses who build desktop business applications with managed code.

I don’t think Windows wants to see a successful client-side .NET framework.

Where Are We?

It feels as if Microsoft has shifted focus away from .NET, and with the focus goes resources and innovation. Much of the CLR and it’s associated assemblies and languages appear to be entering maintenance or refinement mode instead of advancing in new directions. Anyone building software on Microsoft’s .NET platform should see this as cause for concern.

Except …

The circle of  software loosely surrounding .NET is exploding. There are more server side framework choices for C# developers than ever before, and client side web programming has advanced rapidly over the last few years with open source projects like AngularJS, Backbone, Ember, and Meteor. Document databases like MongoDB and RavenDB and key-value stores like Redis are all available to managed code, and products like Xamarin are pushing C# and mono to new platforms. What I’ve listed is a small sampling of what is happening and it is all pretty amazing when you sit back and look at the bigger picture. 

Plus, if you already build solutions with ASP.NET MVC, Web Pages, the WebAPI, or the Entity Framework, you are already building software on top of open source projects that rely on other open source projects from the community. 

What To Do?

If your business or company still relies solely on components delivered to developers through an MSDN subscription, then it is past time to start looking beyond what Microsoft offers for .NET development so you won’t be left behind in 5 years. Embrace and support open source.

At least, that’s how I see things.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 13 May 2013 09:12

In MVC web programming server side controllers are responsible for reacting to an external stimulus (an HTTP request), and then building a model and possibly rendering a view in response to the stimulus. In a client app with AngularJS, the controller has an easier job.

AngularJS is officially a Model-View-Whatever framework, meaning there is quite a bit of flexibility in the architecture of an application. But, if you follow the typical conventions, a controller is simply a function the framework will call at the appropriate time. It’s the controller’s responsibility to put together a model by any means possible, and then the controller function is complete. 

One notable difference between a controller in server side world of Rails or ASP.NET MVC  and a controller with AngularJS is the view selection. Controllers and views are generally bound together on the client using directives (ng-controller) or in routing rules (a topic for a future post).

As an example, the following html is setting up the AboutController to manage the primary div element in the document. The primary div also contains some data binding expressions.

<body data-ng-app="patientApp">
                          
    <div data-ng-controller="AboutController">
        <h3>{{message}}</h3>
        <div>Number of rabbits in the yard: {{rabbitCount}}</div>

        <button ng-click="increase()">More rabbits</button>
        <button ng-click="decrease()">Less rabbits</button>
    </div>

    <script src="http://odetocode.com/libs/angular.js"></script>
    <script src="http://odetocode.com/scripts/myScript.js"></script>
</body>

When AngularJS takes control of the DOM it will see the ng-controller directive and go off searching for an AboutController. Here is one way to write the controller:

(function () {
    
    var AboutController = function($scope) {

        $scope.message = "Hello from the AboutController!";
        
        $scope.rabbitCount = 2;
        
        $scope.increase = function() {
            $scope.rabbitCount *= $scope.rabbitCount;
        };
        
        $scope.decrease = function() {
            $scope.rabbitCount -= 1;
        };
    };
    
    // Describe dependencies for the injector
    // in a minifier friendly way.
    AboutController.$inject = ["$scope"];

    // Register the controller as part of a module.
    // The patientApp module will need to take a 
    // dependency on patientApp.Controllers.
    angular.module("patientApp.Controllers")
           .controller("AboutController", AboutController);
    
}());

Once AngularJS finds the controller, the framework invokes the function and injects any dependencies the controller requires. In this case the controller is simple and only requires a $scope dependency. We’ll talk about $scope in a future post, for now you can think of $scope as the model object you need to enhance for the application to work. The HTML contains data binding expressions like {{message}} and ng-click directives that will send the framework looking for functions to invoke named increase and decrease. These are all attributes the controller needs to provide on the $scope object.

In many respects the $scope object feels like a view model in an MVVM environment like Silverlight. The data binding expressions push and pull data into properties of the view model. The command type bindings, like ng-click=increase(), invoke methods on the view model. And the view model (a.k.a $scope object) behaves in true view model like fashion in the sense that it knows nothing about the view or the DOM. The view model only needs to change values internally and data binding takes care of the rest. Clean and testable.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Friday, 10 May 2013 09:12

From the Redis home page:

Redis is an advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

Redis is also fast. Incredibly fast. Mind-numbing fast.

For more information, try the Redis docs or “The Little Redis Book” by Karl  Seguin.

MSOpenTech just released a NuGet package of their Windows port to make it easy to download Redis and try the server from the command line. Combine this package with the ServiceStack.Redis package and it easy to be up and running quickly.

install-package redis-64
install-package servicestack.redis

The redis-64 package (for 64 bit systems) doesn’t add assembly references to a project, but does drop the Redis server executable in the packages\Redis-64.{version}\tools directory of the solution. Opening a command window and running redis-server.exe will launch the server with the default settings.

Here is a quick C# program to store and retrieve an object using the ServiceStack client:

static void Main(string[] args)
{
    var client = new RedisClient("localhost");
    var patientClient = client.As<Patient>();

    var patient = new Patient
        {
            Name = "Scott", 
            Codes = new List<string> {"1.1", "2.2"}
        };
    patient.Id = patientClient.GetNextSequence();
    patientClient.Store(patient);

    var retrievedPatient = patientClient.GetById(patient.Id);
    Console.WriteLine("{0}:{1}", retrievedPatient.Id, retrievedPatient.Name);

}

Once the program runs, you can also go to the command line client in the tools directory (redis-cli.exe), and verify the data stored inside of Redis. Here is a shot of the cli client and server running:

Redis running from NuGet

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 07 May 2013 09:12

imageNow that we know a bit about how modules work at an API level, we can look at questions that will be asked more than once in the lifetime of a project, like when to create a module, how many modules to create, and how to organize source code files for a module.

One thing to recognize early on is how much flexibility is available. Although the term "module" sounds like the JavaScript module design pattern (a single function inside a single file), there is nothing about an AngularJS module that requires all the code for a module to exist in a single file, or in a single function. Your code can use multiple JavaScript modules to add features to a single AngularJS module.

The code below is creating an alerter service to add to the patientApp.Services module, and could be one of many such pieces of code scattered across various files.

(function () {
    var alerter = function () {
        // ...
    };

    angular.module("patientApp.Services")           
           .factory("alerter", alerter);
}());

Given this amount of flexibility, there are no real limitations on the number of modules and files you create.

Use an approach that causes the least amount of friction for you and the team. Factors to evaluate include the test and deployment strategy and the reusability of a module across multiple apps. Managing the dependencies of a large number of modules produces friction. Building large monolithic modules can also produce friction. Somewhere in between is a sweet spot.

Reference Material

There is already some good material out there on organizing file and modules.

The Angular Seed project recommends creating one module for controllers, one for directives, one for filters, and one for services. I'm not a fan of choosing this approach as a default.

Brian Ford has a post on Building Huuuuuuge Apps with AngularJS. Brian suggestion: "Each file should have one "thing" in it, where a "thing" is a controller, directive, filter, or service".

Cliff Meyers also believes in one thing per file in his post "Code Organization in Large AngularJS and JavaScript applications". I like that Cliff uses a dedicated folder for models instead of throwing in models with services or controllers.

Finally, Jim Lavin has "AngularJS Modules for Great Justice" and talks about the concepts of "package by layer" versus "package by feature".

One scenario I haven't found addressed very well is the scenario where multiple apps exist in the same greater web application and require some shared code on the client. I'll try to blog about this one in the future, but we'll visit some of the other AngularJS abstractions first.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 06 May 2013 09:12

People ask me what I do on a a regular basis. For this and various other reasons I'll shed some light on the current situation.

medisolv1.Medisolv is a company I've worked with in various roles for the last 10+ years. I'm now CTO, but still work with various product teams and commit production code as often as possible, which is by far finest part of the job. We will be hiring more software developers in the near future, so keep an eye out if you are interested. 

Battle Of Valcour With Pluralsight Crystal2. Pluralsight is where I make glorious training videos. I'm currently working on a couple different courses and plan to finish "Learning To Program" in the next couple weeks. Making videos for Pluralsight is fun. Over the years I've collected 8 crystal microphones from Pluralsight as an award for making a Top 10 course. Occasionally I arrange them on the floor to recreate great naval battles from the 18th century. The photo to the right is the Battle of Valcour Island. You can see General Carleton advancing British warships towards the American's Congress and Royal Savage.

3. OdeToCode LLC is the company I own and operate for consulting services, but I've scaled back operations to simplify life and I am currently not taking on new work.

4. Workshops, Classes, and Conferences allow me to occasionally get out and see the world. I enjoy the classes I teach for DeveloperFocus and ProgramUtvikling and plan to update and revise my current curriculum to include topics like AngularJS and web service design with WebAPI. Conferences are fun, but also stressful and time consuming, so I'm cutting back. I will be at DevSum, NDC, and the fall DevIntersection this year.

And now, back to work…

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Wednesday, 01 May 2013 09:12

Continuing from the last post, a module in AngularJS is a place where you can collect and organize components like controllers, services, directives, and filters. We'll talk about the "when & why" of creating a module in a later post. This post will focus on the API to create a module, and get a reference to an existing module. Stimulating topic, eh?

The proper way to create a module is to use the angular.module method passing at least the module name, and an array naming all the dependencies of the module  (or an empty array if there are no dependencies).

angular.module("patientApp.Services", []);
angular.module("patientApp.Controllers", []);   
angular.module("patientApp", ["patientApp.Services",
                              "patientApp.Controllers"]);

The above code actually creates three modules – patientApp.Services, patientApp.Controllers, and a patientApp module that depends on the previous two modules. I like to have all this code centralized in one place for easy management.

The following code defines the three modules, then comes back and adds a "run block" to the patientApp module (a run block is a piece of code that Angular will invoke once the module is assembled and configured).

(function () {
    "use strict";

    angular.module("patientApp.Services", []);
    angular.module("patientApp.Controllers", []);   
    angular.module("patientApp", ["patientApp.Services",
                                  "patientApp.Controllers"]);

    var app = angular.module("patientApp");
    app.run(["$rootScope", function ($rootScope) {
        $rootScope.patientAppVersion = "0.0.0.1";
    }]);
    
}());

Note the call to angular.module("patientApp") does not pass a second parameter with required module names, doing so would recreate the module and destroy anything already registered inside. Calling angular.module with just the module name will give you back a reference to an existing module so you can continue adding run blocks, services, directives, and other components into the module.

Somewhere else in the same file, or in a separate file, another block of JavaScript code might add an "alerter" service to the 'patientApp.Services' module (I know we haven't talked about services yet, but we will, and the short summary is that a service can carry out a specific task, like communicate over the network, and a service typically contains code you want isolated for testability or to obey the single responsibility principle).

(function () {
    var alerter = function () {
        return {
            alert: function (message) {
                // ... do something alerty
            }
        };
    };

    angular.module("patientApp.Services")           
           .factory("alerter", alerter);
}());

The API and terminology around services in Angular is unfortunately confusing and sometimes misleading, but we'll talk about that, too. For now, think of the factory method as "registering a service" in the module. The factory method is not providing a factory for the module itself, as the name might imply. 

Yet another hunk of script from a different file can add a logger service to the same module.

(function() {

    var logger = function() {
      
        var log = function(message) {
            // .. do something loggy
        };

        return {
            log: log,            
        };
    };

    angular.module("patientApp.Services")
           .factory("logger", logger);           

}());

Of course, that could have all been combined together, if you so desire:

(function() {
    "use strict";

    var alerter = function () {
        //...
    };

    var logger = function() {
        //...
    };

    angular.module("patientApp.Services")
           .factory("alerter", alerter)
           .factory("logger", logger);           

}());

Now that we understand a bit about how to create modules, we'll talk about the "when and why" in a future post.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 30 Apr 2013 09:12

imageOne of the nice features of AngularJS is how the framework comes with a complete set of abstractions and features for building complex client pages from loosely structured and maintainable pieces of code. There are controllers, services, directives, data binding, and other pieces we'll continue looking at in future posts.

Angular also includes the concept of an application, which is the topic for this post.

An application is just an Angular module, which leads to a chicken and egg problem, since we haven't talked about modules, yet, but for now you can think of a module as an abstraction for packaging up related pieces of code.

For example, with Angular you can place all your controllers into a one module and all your services into a second module, or put the controllers and services all inside a single module. How many modules you define is entirely up to you and the needs of the project. Modules exist as containers that can provide configuration information, runtime dependencies, and other infrastructure support for their residents.

There are usually two features of the application module that make it "the application".

First is that the application module should know about all the other modules in the software, while those other modules might not know about each other or the application. Thus, the application module is the perfect place to bootstrap and glue together all the other components.

Secondly, the application module is the one identified by the ngApp directive. You can place this directive in the DOM using ng-app or data-ng-app attributes, as shown below in the simplest possible AnguarJS + HTML 5 page.

<!DOCTYPE html>
<html>
    <head>   
        <title>Patient Data</title>
    </head>
<body data-ng-app="PatientApp">
    <div>
        {{ patientAppVersion }}            
    </div>
    <script src="http://odetocode.com/libs/angular.js"></script>
    <script src="http://odetocode.com/… my scripts &hellip"></script>    
</body>
</html>

You can have multiple applications inside a single page, but typically there will only be a single application and the ng-app directive will appear on the document's body element. After Angular loads and processes the HTML in the DOM, it will go looking for the "patientApp" module, so the following code is required:

(function () {
    "use strict";

    var app = angular.module("PatientApp", []);

    app.run(function ($rootScope) {
        $rootScope.patientAppVersion = "0.0.0.1";
    });

}());

angular.module is the API to use for creating and configuring a module. The first parameter is the name of the module, the 2nd parameter describes the other modules this module depends on (there currently are none).

The .run method will give Angular a function to execute after all the modules are loaded and the dependencies are resolved. In this sample, we'll add a property to $rootScope, which is the scope in use in the previous HTML (since we have no controllers yet). The magic of {{ data binding }} allows the web page to display the text "0.0.0.1".

You can reference the patientApp module from other JavaScript files using angular.module. The following code block could live in a separate .js file, and demonstrates how different pieces of code could be tied together to execute during the application bootstrap phase:

(function() {
    "use strict";

    var app = angular.module("PatientApp");
  
    app.run(["$rootScope", function($rootScope) {
        $rootScope.patientAppGreeting = "Hello!";
    }]);  

}());

Note: the call to angular.module does not have a 2nd parameter (the list of dependencies) in this second block. The dependencies param should only appear once for a given module. Passing the dependencies parameter again will wipe out the module definition and start over.

Also note the second code block uses a style that is safe for minification because it passes $rootScope (a well known name to Angular) in an array along with the function to invoke during the run phase. Anytime you define a function where Angular will inject dependencies you are given the option of passing the function as the last element in an array that gives Angular the well known names of the dependencies required as arguments. We'll see more examples of this style as we move forward.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 29 Apr 2013 09:12

The one where I talk to Carl and Richard about everything from AngularJS, Durandal, and Glimpse to relationships and finding your true love.

Listen or download the show here.

 

Tablet Show #82

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 22 Apr 2013 09:12

If you want to teach someone the very basics of computer programming, then JavaScript might be a good place to start.

- The syntax is flexible and uses only a handful of keywords, plus functions and objects.

- The language includes standard control flow structures (if/else, while, do, switch, throw).

- A beginning programmer would also have an easier time understanding a number of other popular languages, including Java, C#, and C++.

- JavaScript runtimes are ubiquitous.

- Knowing how to program in JavaScript is marketable skill.

Once you've settled on JavaScript as a starting language, then the next question is what tools and environment to use. Node.js might be a good place to start.

 

nodejs

- Node is free and easy to install on all the popular desktop operating systems.

- As a pure JavaScript execution engine, you can start by explaining Javascript without explaining HTML DOM APIs.

- Node has a REPL for interactive programming

- Node has a large universe of packages to build anything from a web server to desktop applications.

- Node projects follow simple file system conventions.

- You can still pick any editor or IDE to work with the JavaScript language. 

Using node and JavaScript to learn programming fundamentals is something I'm putting together for a future Pluralsight video, and it's working quite well.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 16 Apr 2013 09:12

GridFS is a specification for storing large files in MongoDB. GridFS will chunk a file into documents, and the official C# driver supports GridFS.

The following class wraps some of the driver classes (MongoDatabase and MongoGridFS):

public class MongoGridFs
{
    private readonly MongoDatabase _db;
    private readonly MongoGridFS _gridFs;

    public MongoGridFs(MongoDatabase db)
    {
        _db = db;
        _gridFs = _db.GridFS;
    }

    public ObjectId AddFile(Stream fileStream, string fileName)
    {
        var fileInfo = _gridFs.Upload(fileStream, fileName);
        return (ObjectId)fileInfo.Id;
    }

    public Stream GetFile(ObjectId id)
    {
        var file = _gridFs.FindOneById(id);
        return file.OpenRead();           
    }
}

The following code uses the above class to put a file into MongoDB, then read it back out.

var fileName = "clip_image071.jpg";

var client = new MongoClient();
var server = client.GetServer();
var database = server.GetDatabase("testdb");
var gridFs = new MongoGridFs(database);

var id = ObjectId.Empty;            
using(var file = File.OpenRead(fileName))
{
    id = gridFs.AddFile(file, fileName);
}

using(var file = gridFs.GetFile(id))
{
    var buffer = new byte[file.Length];
    // note - you'll probably want to read in
    // small blocks or stream to avoid 
    // allocating large byte arrays like this
    file.Read(buffer, 0, (int)file.Length);
}           
Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 15 Apr 2013 10:16

Assuming I already have an existing web site or web application deployed, running, and working great for desktop browsers, my decision tree for getting the site working on mobile devices looks something like the following. mobile thoughts

The right-hand side, the "mobile friendly" approach, is primarily concerned with adding responsive design touches to an existing site. Frameworks like Bootstrap and Skeleton can make this easier, if they can be worked into the existing design. The right-hand side seems to work best with content heavy web sites (news, blogs, articles, and dashboards) with little interactivity from the user.  

The left-hand side uses frameworks like jQuery Mobile to create the illusion of a native app. These frameworks generally require some major structural changes to the presentation layer and thus often work better as a separate site and source control project (m.server.com for mobile devices, server.com for the desktop, for example). A clean separation allows for a complete focus on the mobile experience, but  there is still the possibility of reusing assets, media, and backend services previously built for the desktop version.

The middle box is a hybrid approach using a framework like ASP.NET MVC that allows for view selection at runtime (Index.cshtml and Index.mobile.cshtml). Although this approach makes it easy to reuse quite a bit of code (even into the UI layer of the server), and often takes less time, it sometimes sacrifices the optimizations that can be made when working from a clean slate and doesn't evolve as easily when adding new features. This approach might use just a CSS framework, or might use a framework like jQuery Mobile, while still keeping the ability to make structural changes like an entirely new site.

Like everything else in software, the decisions are all about tradeoffs and where the software has to go in the future.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 08 Apr 2013 10:12

Message handlers in the WebAPI feature a single method to process an HTTP request and turn the request into a response. SendAsync is the method name, and following the TAP, the method returns a Task<HttpResponseMessage>.

There are several different techniques available to return the Task result from a message handler. The samples on the ASP.NET site demonstrate a few of these techniques, although there is one new trick for .NET 4.5.

What you'll notice in these samples is that there is never a need to call Task.Run, or Task.Factory.StartNew, or use a Task constructor.

First, some message handlers will only need to process or modify the incoming request and not touch the response. In these cases the code can just return the result of the base SendAsync method (from DelegatingHandler). A good example is the MethodOverrideHandler sample on the ASP.NET site, which uses the presence of a header to change the HTTP method and thereby support clients or environments where HTTP PUT and DELETE messages are otherwise impossible.

public class MethodOverrideHandler : DelegatingHandler
{
    readonly string[] _methods = { "DELETE", "HEAD", "PUT" };
    const string _header = "X-HTTP-Method-Override";

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {           
        if (request.Method == HttpMethod.Post && request.Headers.Contains(_header))
        {
            var method = request.Headers.GetValues(_header).FirstOrDefault();
            if (_methods.Contains(method, StringComparer.InvariantCultureIgnoreCase))
            {
                request.Method = new HttpMethod(method);
            }
        }
        return base.SendAsync(request, cancellationToken);
    }
}

Notice the code to return base.SendAsync as the last line of the method.

In other cases, a message handler might only want to change the response and not touch the request. An example might be a message handler to add a custom header into the response message (again a sample from the ASP.NET site). Regardless of which framework version is in use, the code will need to wait for base.SendAsync to create the response. With the C# 4 compiler, a friendly way to do this is using a task's ContinueWith method to create a continuation.

protected override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken)
{
    return base.SendAsync(request, cancellationToken).ContinueWith(
        (task) =>
        {
            var response = task.Result;
            response.Headers.Add("X-Custom-Header", "This is my custom header.");
            return response;
        }
    );
}

With C# 5.0, the async and await magic removes the need for ContinueWith:

async protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
{
    var response = await base.SendAsync(request, cancellationToken);
    response.Headers.Add("X-Custom-Header", "This is my custom header.");
    return response;
}

Another set of handlers will want to short-circuit the pipeline processing and send an immediate response. These types of handlers are generally validating an incoming message and returning an error if something is wrong (like checking for the presence of API required header or authorization token). There is no need to call into base.SendAsync, instead the handler will create a response and not allow the rest of the pipeline to execute. For example, a message handler to require an encrypted connection:

protected override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request,
    CancellationToken cancellationToken)
{
    if (!Uri.UriSchemeHttps.Equals(
        request.RequestUri.Scheme, 
        StringComparison.OrdinalIgnoreCase))
    {
        var error = new HttpError("SSL required");
        var response = request.CreateErrorResponse(HttpStatusCode.Forbidden, error);
                                       
        var tsc = new TaskCompletionSource<HttpResponseMessage>();
        tsc.SetResult(response);
        return tsc.Task;
    }
    return base.SendAsync(request, cancellationToken);
}

There is still a call to base.SendAsync for the case when the request is encrypted, but over a regular connection the code returns an error response using a TaskCompletionSource. I think of TaskCompletionSource as an adapter for Task, since I can take code that doesn't require asynch execution (or is based on asynch events, like a timer), and make the code appear task oriented.

In .NET 4.5, Task.FromResult can accomplish the same goal with less code:

var error = new HttpError("SSL required");
var response = request.CreateErrorResponse(HttpStatusCode.Forbidden, error);

return Task.FromResult(response);                              

This concludes another electrifying post on the ASP.NET WebAPI.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Thursday, 04 Apr 2013 09:12

The WebAPI framework is full of abstractions. There are controllers, filter providers, model validators, and many other components that form the plumbing of the framework. However, there are only three simple abstractions you need to know on a daily basis to build reasonable software with the framework.

- HttpRequestMessage

- HttpResponseMessage

- HttpMessageHandler

The names are self explanatory. I was tempted to say HttpRequestMessage represents an incoming HTTP message, but saying so would mislead someone into thinking the WebAPI is all about server-side programming. I think of HttpRequestMessage as an incoming message on the server, but the HttpClient uses all the same abstractions, and when writing a client the request message is an outgoing message.  There is a symmetric beauty in how these 3 core abstractions work on both the server and the client.

WebAPI Abstractions

There are 4 abstractions in the above class diagram because while an HttpMessageHandler takes an HTTP request and returns an HTTP response, it doesn't know how to work in a pipeline. Multiple handlers can form a pipeline, or a chain of responsibility, which is useful for processing a network request. When you host the WebAPI in IIS with ASP.NET, you'll have a pipeline in IIS feeding requests to a pipeline in ASP.NET, which in turn gives control to a WebAPI pipeline. It's pipelines all the way down (to the final handler and back). It's the WebAPI pipeline that ultimately calls an ApiController in a project. You might never need to write a custom message handler, but if you want to work in the pipeline to inspect requests, check cookies, enforce SSL connections, modify headers, or log responses, then those types of scenarios are great for message handlers.

The 4th abstraction, DelegatingHandler, is a message handler that already knows how to work in a pipeline, thanks to an intelligent base class and an InnerHandler property. The code in a DelegatingHandler derived class doesn't need to do anything special to work in a pipeline except call the base class implementation of the SendAsync method. Here is where things can get slightly confusing because of the name (SendAsync), and the traditional notion of a pipeline. First, let's take a look at a simple message handler built on top of DelegatingHandler (it doesn't do anything useful, except to demonstrate later points):

public class DateObsessedHandler : DelegatingHandler
{          
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        var requestDate = request.Headers.Date;
        // do something with the date ...
        
        var response =  await base.SendAsync(request, cancellationToken);

        var responseDate = response.Headers.Date;
        // do something with the date ...

        return response;
    }
}

First, there is nothing pipeline specific in the code except for deriving from the DelegatingHandler base class and calling base.SendAsync (in other words, you never have to worry about using InnerHandler).

Secondly, we tend to think of a message pipeline as unidirectional. A message arrives at one end of the pipeline and passes through various components until it reaches a terminal handler. The pipeline for WebAPI message handlers is is bidirectional. Request messages arrive and pass through the pipeline until some handler generates a response, at which point the response message flows back out of the pipeline.

handlers

The purpose of SendAsync then, isn't just about sending. The purpose is to take a request message, and send a response message.

All the code in the method before the call to base.SendAsync is code to process the request message. You can check for required cookies, enforce an SSL connection, or change properties of the request for handlers further down the pipeline (like changing the HTTP method when a particular HTTP header is present).

When the call to base.SendAsync happens, the message continues to flow through the pipeline until a handler generates a response, and the response comes back in the other direction. Symmetry.

All the code in the method after the call to base.SendAsync is code to process the response message. You can add additional headers to the response, change the status code, and perform other post processing activities.

Most message handlers will probably only inspect the request or the response, not both. My sample code wanted to show both to show the two part nature of SendAsync. Once I started thinking of SendAsync as being divided into two parts, and how the messages flow up and down the pipeline, working with the WebAPI became easier. In a future post we'll look at  a more realistic message handler that can inspect the request and short circuit the response.

Finally, it's easy to add a DelegatingHandler into the global message pipeline (this is for server code hosted in ASP.NET):

GlobalConfiguration.Configuration
                   .MessageHandlers
                   .Add(new DateObsessedHandler());

But remember, you can also use the same message handlers on the client with HttpClient and a client pipeline, which is a another reason the WebAPI is symmetrically beautiful.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 01 Apr 2013 09:35

A one and a half minute teaser for my upcoming Pluralsight course:

Happy April 1st ...

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Thursday, 28 Mar 2013 09:12

It doesn't take long to realize that the HTTP methods POST, GET, PUT, and DELETE can map directly to the database operations we call CRUD (create, read, update, and delete).

It also doesn't take much effort to find samples that demonstrate CRUD applications with the WebAPI. In fact, the built-in scaffolding can give you code where the only software between an incoming HTTP message and the database is the EntityFramework.

Is CRUD all the WebAPI is good for? That's a question I've heard asked a few times.

Stepping Back

I think one of the reasons we see CRUD with the WebAPI is because CRUD is simple. CRUD is the easiest approach to building a running application. CRUD is also the easiest approach to building a demo, and for explaining how a new technology works. CRUD isn't specific to the WebAPI, you can build CRUD applications on any framework that sits on the top or the outer layer of an application.

CRUD is Everywhere

All the above applications would have these characteristics:

- Minimal business logic

- Database structure mimicked in the output (on the screen, or in request and response messages).

There is nothing inherently wrong with CRUD, and for some applications it's all that is needed.

But Can It Do More?

Let's not talk about WebAPI as yet, let's  talk about these 2 WPF scenarios:

1) When the user clicks the Save button, take the information in the "New Customer" form, check for required fields, and save the data in the Customers table.

versus

2) When the user clicks the Save button, take the information from the "New Customer" form. Send the data to the Customer service for validation, identification, and eventual storage. If the first stage validation succeeds, send a message to the legacy Sales service  so it has the chance to build alerts based on the customer profile. Finally, send a message to the Tenant Provisioning service to start reserving hardware resources for the customer and retrieve a token for future progress checks on the provisioning of the service.

#1 is simple CRUD and relatively trivial to build with most frameworks. In fact, scaffolding and code generation might get you 90% of the way there.

#2 presents a few more challenges, but it's no more challenging with WPF than it would be with the WebAPI (in fact, I think it might be a bit simpler in a stateless environment like a web service). The framework presents no inherent obstacles to building a feature rich application in a complex domain.

Of course, you should think about the problem differently with the WebAPI (see How To GET A Cup Of Coffee, for example), but most of the hard work, as always, is building a domain and architecture with just the right amount of flexibility to solve the business problem for today and tomorrow. That's something no reusable framework gives you out of the box.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Wednesday, 27 Mar 2013 09:12

Generating a link to an ApiController isn't too difficult once you know the right methods to call.

Outside the API Controller

In a Razor view, for example, you can generate a link to an API controller using the standard Url helper property. The following link will point to an Albums controller and pass along an id parameter with a value of 3:

@Url.RouteUrl("DefaultApi", new { httproute=true, controller="Albums", id=3})

Notice the route name is "DefaultApi", which is the default route name for WebAPI routes, but you can chose any API route name you need. Also notice the presence of the httproute value, which disambiguates WebAPI routes from other MVC routes. You can avoid the httproute parameter if you use the HttpRouteUrl helper method instead:

@Url.HttpRouteUrl("DefaultApi", new { controller="Albumns", id=3 })

An action parameter isn't needed, since API routing uses the HTTP method by default (but you could specify an action in the route parameters, if need be).

Inside an API Controller

An ApiController has a Url helper property with two interesting methods: Link and Route. Link always returns an absolute URL, while Route can produce a relative URL.

The following code uses Link and will produce a URL pointing to the same controller where the code executes:

Url.Link("DefaultApi", new { id = 3 })

If you want a link to a different controller, just pass the controller name along in the route values (along with any other route values the route might support):

Url.Link("DefaultApi", new { controller = "Albums", id = 3})

Note: both the Link and Route methods add an httproute key to the route parameters you pass in. Technically then, you shouldn't use the Url property in an ApiController to generate non-WebAPI links, although it generates the right URL (because regular MVC route handlers don't care about the presence of httproute).

This concludes the extreme excitement of link generation.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 26 Mar 2013 09:12

SOA circa 2004This post is a commentary on the statement: "We are sticking with WCF because we want a service oriented architecture."

SOA is a three letter acronym that created a fervor from the server closet to the executive boardroom.  A decade of labor by standards committees, tool vendors, framework builders, consultants, and hucksters made sure SOA became the silver bullet for enterprise architecture.

If I look through the noise for the pragmatic essence of SOA, I see three noble goals:

- Software encapsulation – or the ability to hide complexity behind coarse grained interfaces.

- Software autonomy - or the absolute control of the execution environment and the resources required by software, as well as the freedom to make independent decisions about implementation details.

- Software interoperability – or optimizing for reuse by relying on standard application level communication protocols.

Those three goals are entirely possible with HTTP based services and the ASP.NET WebAPI. The S in SOA doesn't stand for SOAP.

I know many people will say the additional metadata commonly associated with SOA (like WS-Metadata Exchange, WS-Policy, and XML Schema, to name just a few) is also a core part of SOA. I'd argue the metadata was good for vendors who built software to manage the complexity of the metadata.

KISS it goodbye with the WebAPI.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 25 Mar 2013 09:12

Let's say you have the following type definition in C#:

public class Thing
{
    public int Id { get; set; }
    public string FirstName { get; set; }    
    public string ISBN { get; set; }
    public DateTime ReleaseDate { get; set; }
}

The default JSON serialization of a thing will look like this:

{"Id":1,"FirstName":"Scott","ISBN":"123","ReleaseDate":"2013-03-24T16:26:33.7719981Z"}

It feels awkward to work with JavaScript objects where the first letter of a property name is a capital letter. But, it feels awkward to work with C# objects where the first letter of a property name is not capitalized.

Fortunately, the default serializer (Json.NET) will let you have the best of both worlds. All you need is a bit of configuration during application startup:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

The CamelCasePropertyNamesContractResolver will produce the following JSON instead:

{
  "id": 1,
  "firstName": "Scott",
  "isbn": "123",
  "releaseDate": "2013-03-24T16:39:28.4516517Z"
}

We also tweaked the formatting settings to make the JSON easier for humans to read.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Thursday, 21 Mar 2013 09:12

Henceforth we begin a series of tips and musings on the WebAPI.

Tip #1 – HttpStatusCode is an enum you can use to send specific status codes in a response. Going through the list, it is not always clear what name matches a value you are looking for, so here is a WebAPI controller to dump status codes into JSON.

public class StatusCodesController : ApiController
{
    public HttpResponseMessage Get()
    {
        var type = typeof(HttpStatusCode);
        var values =
            Enum.GetNames(type)                    
                .Select(name => new { name =name, value = (int)Enum.Parse(type, name) });

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new ObjectContent(values.GetType(),
            values,
            Configuration.Formatters.JsonFormatter);

        return response;
    }
}

Tip #2 – The Request.CreateResponse extension method will use a content negotiation strategy to pick the best formatter for the response. In cases where you want to force a specific content type, use the approach in the above code. This example is forcing a JSON request by passing in the JsonFormatter to the ObjectContent ctor (because the XML formatter doesn't like anonymous types).

More to come...

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader