Thursday, September 19, 2013

ASP.NET SignalR

ASP.NET SignalR is a library that allows developers to add real-time web functionality to applications quickly and easily. The library wraps various techniques and creates a unified toolkit for server to client push notifications. SignalR will leverage the best technique for bi-directional communication available for the current browser and server by first attempting to connect via WebSockets and then falling through to long polling. The best part is that your application code stays the same no matter what communication methodology is in use. SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements Ajax long polling to retrieve new data, is candidate for using SignalR. It also enables completely new types of applications, that require high frequency updates from the server, e.g. real-time gaming. For a great example of this, see the ShootR game

Get it on NuGet by running:
Install-Package Microsoft.AspNet.SignalR


Get a sample on NuGet, straight into your app by running:
Install-Package Microsoft.AspNet.SignalR.Sample

Monday, August 26, 2013

Securing a Web API with Windows Azure AD and Katana

I just read through this article doing a walk-through on how to secure your WebAPI with Azure AD using Katana and OWIN.  It lays out all of the benefits of of OWIN and using Katana. 

http://www.cloudidentity.com/blog/2013/07/23/securing-a-web-api-with-windows-azure-ad-and-katana/

Worth the read.

Monday, August 12, 2013

Windows Azure Notification Hubs

Windows Azure Notification Hubs was just released for general availability.  These hubs help mobile app developers deliver large numbers of push notifications to mobile users on a wide range of platform.Windows Azure Notification Hubs makes sending push notifications through multiple notification services achievable with just a few lines of code.  Today, apps like the Bing News for Windows 8 are using notification to send millions of push notifications to inform users of the latest breaking news. 

This doesn't replace Windows Azure Mobile Services, which  also supports push notifications. The table below explains the differences.   In short, Mobile Services is best used for communicating to a single user whereas Notification Hubs is best used for communicating to many users simultaneously.


Mobile Services
Notification Hubs
MPNS, WNS, APNS, and GCM support
Yes
Yes
Turnkey event-triggered push
Yes
No
Device registration management
No
Yes
Interest tags for routing messages to a subset of users
No
Yes
Templates for formatting messages to user preferences including language
No
Yes
Broadcast to >1 million devices at once within minutes
No
Yes 

Check out Scott Gu's post for more details.

Friday, August 2, 2013

OWIN and the Katana Project

OWIN

OWIN (a.k.a. Open Web Interface for .NET) is a new way of processing HTTP requests in .NET.  It is a specification describing how .NET web servers and .NET applications should interface and interact. The idea is that by decoupling the server and application we are able to write code independent of the host platform.  Our code at that point can be host agnostic and allow us much more flexibility on our chosen publishing environment.

IIS currently does double duty by handling both the host and server responsibilities.  To be clear, by host duties, I mean the process management, and by server, I mean network management and request handling.  This means that we as developers have to use packages specific to IIS suck as HttpModules, HttpHandlers, etc.  While this is effective, it makes our application tightly coupled to a specific hosting environment.  So, if we would want to target something a little more small to host a WebAPI, we would be out of luck.  OWIN gives us the ability to decouple those two things which gives us the flexibility to choose components based on individual functions while selecting only the ones we need and substituting only the ones that are actually different across hosting platforms. All of those changes would actually take place beneath the application.  Hm.. where have I seen this kind of thing before?

The way I understand it, a server in OWN is made up of an environment dictionary, of the form IDictionary<string, object>, used for holding the request processing state: things like the request path, the headers collection, the request bits themselves, and a delegate, of the form Func<IDictionary<string, object>, Task>, which is used to model how the components appear to each other.  This means that an app is a list of those components executed in sequence, each of those awaiting the next and passing the environment dictionary to each other.  This seems very dynamic and portable, which is a really strong position for a WebAPI or other hosted service. 

Katana Project

Katana is a set of components by Microsoft for building and hosting OWIN-based web applications.  Katana has host, server, and middleware source code and documentation located here. These tools are available via NuGet.  These products are actively developed by the Katana team assigned to the Microsoft Open Tech Hub and in collaboration with a community of open source developers.

Tuesday, July 2, 2013

ASP.NET MVC4 - Mobile Views

In ASP.NET MVC4 you have the ability to easily present a view directed at a mobile display without requiring the use of an add on tools.  Sure, for a good mobile experience, you may choose to implement jQueryMobile or something similar, but the fact remains that it is not required with this functionality.


Mobile Experience

A good portion of visual design for mobile can come from using simple media queries to detect the current size of the users' device and render a visual experience accordingly.   Media queries within CSS are straightforward and can handle the majority of simple user experience changes.  For instance, if you wanted to change any properties of an element based on the screen width and orientation of the users' device, you could simply create some combination of the following code:
/* #### Mobile Phones Portrait #### */
@media screen and (max-device-width: 480px) and (orientation: portrait){
  /* some CSS here */
}

/* #### Mobile Phones Landscape #### */
@media screen and (max-device-width: 640px) and (orientation: landscape){
  /* some CSS here */
}

/* #### Mobile Phones Portrait or Landscape #### */
@media screen and (max-device-width: 640px){
  /* some CSS here */
}

/* #### iPhone 4+ Portrait or Landscape #### */
@media screen and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2){
  /* some CSS here */
}

/* #### Tablets Portrait or Landscape #### */
@media screen and (min-device-width: 768px) and (max-device-width: 1024px){
  /* some CSS here */
}

/* #### Desktops #### */
@media screen and (min-width: 1024px){
  /* some CSS here */
}

That sort of thing will go a long way, but sometimes it can lead to clutter and hard to follow CSS.


Overriding a mobile view in MVC4

With MVC 4, there is a very simple mechanism that lets you override any view for mobile browsers in general.  You can also define your own parameters for a specific mobile override, giving you the ability to build specific views for specific devices or user agents.  To provide a view that overrides for any mobile device, all you have to do is copy the view to a new file and add .Mobile to the file name. For example, to create a mobile Something view, copy Views\Home\Something.cshtml to Views\Home\Something.Mobile.cshtml.  The current context will trigger which view is pulled in a run time for a given client.  Now, you have effectively created a mobile specific view that can be visually altered for an experience geared at a mobile platform.


Custom Override Views

You can create almost any kind of custom mobile view you would like by defining a context condition and inserting into the DisplayModeProvider instance. For example, the following code will create a specific display mode based on check the user agent of the current context against 'iPhone'. Then, you add it to the list of display modes within the ApplicationStart method of the global.asax:

public class MvcApplication : System.Web.HttpApplication 
 {
 protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

     DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone")
        {
         ContextCondition = (ctx =>
         ctx.Request.UserAgent.IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
        });

    //Add another one specifically for some tablets too 
    DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Tablet")
        {
         ContextCondition = (ctx =>
         ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >= 0 ||
         ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0 &&
         ctx.Request.UserAgent.IndexOf("Mobile", StringComparison.OrdinalIgnoreCase) <= 0
        )
        });
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
 }

As you can see, the framework gives you the ability to create as many focused views, with as much device granularity as you see fit for your application. This will help ensure good user experiences on specific devices without having to rework existing CSS or get into switching to mobile sites.

Sunday, June 23, 2013

ASP.NET Web API

The ASP.NET Web API framework was introduced recently into ASP.NET.  I touched on it some previously at an overview level, but would like to dig in a little more at this time to show the power of having a true Web API in your product.  

Overview

From a high level, leveraging the Web API framework in ASP.NET allows you to easily build HTTP based services geared at reaching browsers, desktop or mobile clients.  By creating a responsive layer of RESTful APIs for a product, the platform immediately becomes a much more adaptable and scalable solution.  The simple act of ensuring all 'real' application logic is handled behind a RESTful API call, an inherent separation of interests is manifested, which enables a more loosely couple application at every layer.

ASP.NET Web API Infrastructure

At its base, the ASP.NET Web API mechanism is a simple adaptation of an HTTP service.  Web API can be used along with WCF, but realistically, they are two means to create virtually the same thing.  The main aspect of a Web API layer is the ability to create an API project within a given solution that allows user stories to be executed via RESTful calls to the services.  Microsoft has a great tutorial for creating a simple Web API project as an introduction to the platform.  For those familiar with MVC, this exercise should be very straightforward and easily worked through.  In fact, as you work through this, it will probably become clear that there is very little difference here than a standard MVC application.  The main difference is that Web API uses the HTTP method, not the URI path, to select the action. But, you can also use MVC-style routing in Web API if that is more your style.

Dynamism

Leveraging an API infrastructure as a service layer for you web application gives you the ability to manifest any client on any platform without recreating application intelligence. Some of the main features of Web API allow for the creation of a dynamic service layer that can interact with multiple versions of the same platform, 3rd party vendors, customer integrations and most importantly, your own application.  A strong API will have an entry point to accommodate the same list of user stories that the main presentation layer in your application presents to a user.  The API layer should handle modeling, security, extensibility and scalability.  This allows for the consistent use of application logic and business rules across multiple consuming platforms.  API/SDK layers should be manifested by version, with all historic versions co-existing.  A single set of business logic and data access logic should persist across versions of API.  This allows forward movement without backward degradation.  By adhering to the rule of the eternal public interface, this is an achievable goal.

The 'Real' API

While the main focus of this post is the ASP.NET Web API offering, I would like to make a point regarding what an API should be in my opinion.  An API should be a complete manifestation of every user story that exists in your application.  The API should be a service layer that is not the data access layer, nor is it the main business logic layer.  It is the manifestation of User Stories.  This type of layer has been called the User Story Layer and the services contained within have been called Complex Services.  This is a logical regrouping, or coupling of specific business logic tasks to create a user story.  A user story should be completely executed within its single methodological representation, including input validation, security and access validation, activity logging and return values. All manifested user story methods should assume no knowledge of requirements, modalities, system or data flow from any client executing the method. Data access and business logic should never be directly exposed to an end user, third party or otherwise.  Data access and business logic should be separated from each other as well as from the API/SDK/USL.  This enables the ability to quickly couple existing sets of logic into a new user story without having to accommodate situational elements inside the business logic layer.  For more information on building a strong SOA, see some of my previous posts here.  For a theoretical discussion of the purpose behind SOA, check this post.  A framework that has been built with this decoupled approach of singularly responsible object residing behind globally accessible services will much more easily allow for productivity items such as Continual Integration, Continual Deployment, and fully automated testing.

Your First API Client

The short answer here is that it’s your application.  A robust API should first and foremost serve all logic to your own applications.  You have to create your API and then consume it.  This ensures that all changes made are not only accounted for in the API, but are placed there with intent.  You have to eat your own dog food.  In a web development and agile deployment environment, the ability to decouple code and responsibility of objects is the best friend you will ever have.  Approach your web design with intent and long term vision for things like scalability and performance.  Understand that you need to support multiple versions of your service layer and extend your data objects over multiple versions.  A properly architected system will ensure you are able to respond to changes in your market and your market requirements much more quickly than would be the case otherwise.