in

Chennai .Net User Group

A platform that enables you to Learn, Share & Grow (India's first .Net user group)

Shiju Varghese's Blog

  • Building a Simple REST API using Node.js with MongoDB and Mongoose

    In this post, I will demonstrate how to build a simple REST API using Node.js with NoSQL database MongoDB. This demo app will be using MongoDB object modeling tool Mongoose to connecting with MongoDB from the Node app. This demo app is a very basic level API app without following any better practices and mainly created this sample demo for demonstrating Node.js and MongoDB using with Mongoose Node package.

    Node.js for building REST JSON API

    Node.js is a very powerful platform for building highly scalable REST APIs. A Node.js app with a NoSQL database MongoDB can provide great performance and better scalability. I am in the process of building highly scalable REST API on the Windows Azure platform using Node.js and MongoDB and will be put the samples on my Github repositories in future. 

    Node packages

    The following Node packages to be installed in the app in order to working the demo app.

    Express is a web development module for Node.js. Mongoose is a Node.js ORM module for working with MongoDB database.

    Creating Server and Connecting to MongoDB

    The following code block will create the server using express module and connecting to the MongoDB database using the Mongoose.

       1:   //Creating server
       2:  var express = require('express')
       3:        , app = express.createServer()
       4:        , mongoose = require('mongoose');
       5:        
       6:  //Connecting to MongoDB
       7:   mongoose.connect('mongodb://localhost/ProductDB');
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Creating the Model using Mongoose

    Let’s define the Model objects using the Mongoose

       1:  //Models using Mongoose
       2:   var Schema = mongoose.Schema
       3:   , ObjectId = Schema.ObjectID;
       4:   
       5:   var Product = new Schema({
       6:     name : { type: String, required: true, trim: true }
       7:    ,unitPrice  : { type: Number, required: true }
       8:    ,itemsInStock  : { type: Number, required: true }
       9:    });    
      10:      
      11:  var Category = new Schema({
      12:   name   : { type: String, required: true, trim: true }
      13:   ,description    :  { type: String, required: true, trim: true }  
      14:   ,products         : [Product]       
      15:   });    
      16:      
      17:  var ProductCatalog = mongoose.model('Category', Category);
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    In the above code block, we have created the schema for Product and Category and Prodcut schema used as embedded document in the Category schema. We can define the Model using the mongoose.Model.

    var ProductCatalog = mongoose.model('Category', Category);
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Exposing the API methods

    The following function returns the all product catalog information as a JSON string. The request for ‘/’ will return the all product catalog data.

       1:   //Get all product catalog 
       2:    app.get('/', function(req,res){    
       3:   ProductCatalog.find({}, function(error, data){
       4:              if(error){
       5:               res.json(error);
       6:              }
       7:              else if(data == null){
       8:               res.json('Empty data')
       9:              }
      10:              else{
      11:                res.json(data);
      12:              }
      13:              
      14:          });
      15:      });

    The following function returns the category information for a given category name. The request ‘/name’ will be executed the following API method.

       1:  //Get a specified category
       2:  app.get('/:name', function(req,res){    
       3:   ProductCatalog.findOne({ name: req.params.name },
       4:      function(error, category){
       5:   if(error){
       6:        res.json(error);
       7:       }
       8:       else if(category == null){
       9:             res.json('Category not found!')
      10:       }
      11:    else{
      12:       res.json(category);    
      13:        }
      14:     });            
      15:    });
      16:      
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    The request for '/addcategory/name/description' will be executed the following method and will add a new category to the MongoDB database.The method will return the added data as JSON.

       1:  app.get('/addcategory/:name/:description',
       2:   function(req, res){
       3:   var categoryData = {
       4:   name: req.params.name
       5:    , description: req.params.description         
       6:  };
       7:   
       8:  var category = new ProductCatalog(categoryData);
       9:   //Save data
      10:   category.save( function(error, data){
      11:  if(error){
      12:   res.json(error);
      13:  }
      14:  else{
      15:  res.json(data);
      16:     }
      17:   });
      18:  });
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Source Code

    I have created a repository in Github for putting REST API samples. This is the first and basic level sample which can be download from here. This is a very introductory level post mainly used for demonstrating Node.js and MongoDB with Mongoose. I will update the source code repository with more samples.

     

  • Windows Azure SDK for Node.js 0.5.4 Released

    The Microsoft Windows Azure team has released the Windows Azure SDK for Node.js 0.5.4 which  will be using the Node.js 0.6.17 and iisnode 0.1.19. The Node.js 0.6.17 contains a security fix against the HTTP Server Security Vulnerability detected by recently. It would be recommended to upgrade to the new version of Azure SDK for Node.js if you have already deployed any Node.js app to Windows Azure which will provide better security. The iisnode 0.1.19 provides iisnode.yml file instead of XML based configurations which can be use for setting up all iisnode settings. You can download the Windows Azure SDK for Node.js 0.5.4 from here.

  • Windows Azure Supports Voice and SMS Capabilities

    Windows Azure is now supports Telephony and SMS capabilities to the apps hosted in Windows Azure by using the Twilio API. Twilio is a third-party service that provides a cloud-based telephony service which allows to add scalable, reliable voice and text messaging capabilities into you apps. Using Twilio's native libraries for Java, PHP and .NET, developers can build telephony enabled web apps hosted on Windows Azure in which we can make and receive phone calls and SMS messages from  phones and web apps. Twillio is providing 1,000 free text messages or 1,000 voice minutes for Windows Azure developers and you can get the free offerings for Windows Azure from here .

    Check out the following links for getting more details on Twillio API and working it with Windows Azure

  • Dependency Injection in ASP.NET Web API using Autofac

    In this post, I will demonstrate how to use Dependency Injection in ASP.NET Web API using Autofac in an ASP.NET MVC 4 app. The new ASP.NET Web API is a great framework for building HTTP services. The Autofac IoC container provides the better integration with ASP.NET Web API for applying dependency injection. The NuGet package Autofac.WebApi provides the  Dependency Injection support for ASP.NET Web API services.

    Using Autofac in ASP.NET Web API

    The following command in the Package Manager console will install Autofac.WebApi package into your ASP.NET Web API application.

    PM > Install-Package Autofac.WebApi

    image

    The following code block imports the necessary namespaces for using Autofact.WebApi

    using Autofac;
    using Autofac.Integration.WebApi;
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    The following code in the Bootstrapper class configures the Autofac.

       1:  public static class Bootstrapper
       2:  {
       3:   public static void Run()
       4:   {
       5:       SetAutofacWebAPI();
       6:   }       
       7:   private static void SetAutofacWebAPI()
       8:   {
       9:      var configuration = GlobalConfiguration.Configuration;
      10:      var builder = new ContainerBuilder();
      11:      // Configure the container 
      12:      builder.ConfigureWebApi(configuration);
      13:      // Register API controllers using assembly scanning.
      14:      builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
      15:      builder.RegisterType<DefaultCommandBus>().As<ICommandBus>()
      16:          .InstancePerApiRequest();
      17:      builder.RegisterType<UnitOfWork>().As<IUnitOfWork>()
      18:          .InstancePerApiRequest();
      19:      builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>()
      20:          .InstancePerApiRequest();
      21:      builder.RegisterAssemblyTypes(typeof(CategoryRepository)
      22:     .Assembly).Where(t => t.Name.EndsWith("Repository"))
      23:      .AsImplementedInterfaces().InstancePerApiRequest();
      24:      var services = Assembly.Load("EFMVC.Domain");
      25:      builder.RegisterAssemblyTypes(services)
      26:      .AsClosedTypesOf(typeof(ICommandHandler<>))
      27:          .InstancePerApiRequest();
      28:      builder.RegisterAssemblyTypes(services)
      29:      .AsClosedTypesOf(typeof(IValidationHandler<>))
      30:          .InstancePerApiRequest();
      31:      var container = builder.Build();
      32:      // Set the WebApi dependency resolver.
      33:      var resolver = new AutofacWebApiDependencyResolver(container);
      34:      configuration.ServiceResolver.SetResolver(resolver);             
      35:   }
      36:  }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    The RegisterApiControllers method will scan the given assembly and register the all ApiController classes. This method will look for types that derive from IHttpController with name convention end with “Controller”. The InstancePerApiRequest method specifies the life time of the component for once per API controller invocation. The GlobalConfiguration.Configuration provides a ServiceResolver class which can be use set dependency resolver for ASP.NET Web API. In our example, we are using AutofacWebApiDependencyResolver class provided by Autofac.WebApi to set the dependency resolver.

    The Run method of Bootstrapper class is calling from Application_Start method of Global.asax.cs.

       1:  protected void Application_Start()
       2:  {
       3:      AreaRegistration.RegisterAllAreas();
       4:      RegisterGlobalFilters(GlobalFilters.Filters);
       5:      RegisterRoutes(RouteTable.Routes);
       6:      BundleTable.Bundles.RegisterTemplateBundles();
       7:      //Call Autofac DI configurations
       8:      Bootstrapper.Run();
       9:  } 
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Autofac.Mvc4

    The Autofac framework’s integration with ASP.NET MVC has updated for ASP.NET MVC 4. The NuGet package Autofac.Mvc4 provides the dependency injection support for ASP.NET MVC 4. There is not any syntax change between Autofac.Mvc3 and Autofac.Mvc4

    Source Code

    I have updated my EFMVC app with Autofac.WebApi for applying dependency injection for it’s ASP.NET Web API services. EFMVC app also updated to Autofac.Mvc4 for it’s ASP.NET MVC 4 web app. The above code sample is taken from the EFMVC app. You can download the source code of EFMVC app from http://efmvc.codeplex.com/

  • Windows Azure PowerShell for Node.js

    The Windows Azure PowerShell for Node.js is a command-line tool that  allows the Node developers to build and deploy Node.js apps in Windows Azure using Windows PowerShell cmdlets. Using Windows Azure PowerShell for Node.js, you can develop, test, deploy and manage Node based hosted service in Windows Azure.

    For getting the PowerShell for Node.js, click All Programs, Windows Azure SDK Node.js and run  Windows Azure PowerShell for Node.js, as Administrator.

    image

    The followings are the few PowerShell cmdlets that lets you to work with Node.js apps in Windows Azure

    Create New Hosted Service

    New-AzureService <HostedServiceName>

    The below cmdlet will created a Windows Aazure hosted service named NodeOnAzure in the folder C:\nodejs and this will also create ServiceConfiguration.Cloud.cscfg, ServiceConfiguration.Local.cscfg and ServiceDefinition.csdef and deploymentSettings.json files for the hosted service.

    PS C:\nodejs> New-AzureService NodeOnAzure

    The below picture shows the files after creating the hosted service

    image

    Create Web Role

    Add-AzureNodeWebRole <RoleName>

    The following cmdlet will create a hosted service named MyNodeApp along with web.config file.

    PS C:\nodejs\NodeOnAzure> Add-AzureNodeWebRole MyNodeApp

    The below picture shows the files after creating the web role app.

    image

    Install Node Module

    npm install <NodeModule>

    The following command will install Node Module Express onto your web role app.

    PS C:\nodejs\NodeOnAzure\MyNodeApp> npm install Express

    image

    Run Windows Azure Apps Locally in the Emulator

     Start-AzureEmulator -launch

    The following cmdlet will create a local package and run Windows Azure app locally in the emulator

    PS C:\nodejs\NodeOnAzure\MyNodeApp> Start-AzureEmulator -launch

    image

    Stop Windows Azure Emulator

    Stop-AzureEmulator

    The following cmdlet will stop your Windows Azure in the emulator.

    PS C:\nodejs\NodeOnAzure\MyNodeApp> Stop-AzureEmulator

    Download Windows Azure Publishing Settings

    Get-AzurePublishSettings

    The following cmdlet will redirect to Windows Azure portal where we can download Windows Azure publish settings

    PS C:\nodejs\NodeOnAzure\MyNodeApp> Get-AzurePublishSettings

    Import Windows Azure Publishing Settings

    Import-AzurePublishSettings <Location of .publishSettings file>

    The following cmdlet will import the publish settings file from the location c:\nodejs

    PS C:\nodejs\NodeOnAzure\MyNodeApp>  Import-AzurePublishSettings c:\nodejs\shijuvar.publishSettings

    Publish Apps to Windows Azure

    Publish-AzureService –name <Name> –location <Location of Data centre>

    The following cmdlet will publish the app to Windows Azure with name “NodeOnAzure” in the location Southeast Asia. Please keep in mind that the service name should be unique.

    PS C:\nodejs\NodeOnAzure\MyNodeApp> Publish-AzureService –name NodeonAzure –location "Southeast Asia” –launch

    Stop Windows Azure Service

    Stop-AzureService

    The following cmdlet will stop your service which you have deployed previously.

    PS C:\nodejs\NodeOnAzure\MyNodeApp> Stop-AzureService

    Remove Windows Azure Service

    Remove-AzureService

    The following cmdlet will remove your service from Windows Azure.

    PS C:\nodejs\NodeOnAzure\MyNodeApp> Remove-AzureService

    Quick Summary for PowerShell cmdlets

    Create  a new Hosted Service New-AzureService <HostedServiceName>
    Create a Web Role Add-AzureNodeWebRole <RoleName>
    Install Node Module npm install <NodeModule>
    Running Windows Azure Apps Locally in Emulator Start-AzureEmulator -launch
    Stop Windows Azure Emulator Stop-AzureEmulator
    Download Windows Azure Publishing Settings Get-AzurePublishSettings
    Import Windows Azure Publishing Settings Import-AzurePublishSettings <Location of .publishSettings file>
    Publish Apps to Windows Azure Publish-AzureService –name <Name> –location <Location of Data centre>
    Stop Windows Azure Service Stop-AzureService
    Remove Windows Azure Service Remove-AzureService
  • Using Node Package Manager in Cloud9 IDE

    NPM - Package Manager for Node.js

    npm is a package manager for node that is run through command-line interface. It can use it to install and publish your node programs. npm manages dependencies for an application.Node packages are represented as package.json files. The npm is a very similar like NuGet package manager for .NET.
    Using npm, you can quickly find node packages, download them, install them, and manage packages you have already installed.

    Cloud9 IDE supports Node Package Manager

    With Cloud9 IDE, you can install  node modules to your Node.js apps using npm. You can use the link http://search.npmjs.org/ to find out Node packages. To using npm from Cloud9 IDE, go to the text box at the end of the IDE and type the following command, and enter.

    npm install <packagename>

    npm

    In the above picture, we are installing node module express.  This will shows the following in the console

    npm_express

     

    The below picture shows node modules installed into our Node.js project.

    npm_modules

  • Building and Deploying Node.js Apps to Windows Azure using Cloud9 IDE

    In this post, I will demonstrate how to building  Node.js apps using Cloud9 IDE ad deploying Node.js apps to Windows Azure from the Cloud9 IDE.  Cloud9 IDE is a cross-platform, browser-based development environment for JavaScript and Node.js apps which is integrates with GitHub and BitBucket repository services. Cloud9 IDE is the most popular developer tool among the Node developers. Since Cloud9 IDE is working and running on the browser, developers can work from any OS platform. Using with Cloud IDE, you can build and deploy Node.js apps to Windows Azure. The Cloud9 IDE can access from http://c9.io/. Cloud9 IDE provides a free subscription as well as a paid subscription with more features.

    Node.js

    Node.js is a server-side JavaScript platform for  building high performance scalable network programs. Node.js is built on the top of Google's JavaScript runtime engine V8 which is used in Google Chrome.  Node.js uses an event-driven I/O model which provides the ability to handle thousands of parallel operations with greater performance. Node.js is popular for its performance and the Node.js apps are executed on the V8 runtime engine. Node.js lets the developers to write JavaScript programs on the server-side and its provides a JavaScript API to access the network and file systems.

    Node.js for Windows Azure

    Windows Azure is a powerful cloud platform which provides the first class support for Node.js apps. The Windows Azure SDK for Node.js provides the all support to develop and deploy Node.js apps to Windows Azure. With Windows Azure SDK for Node.js, you can deploy Node.js apps to Windows Azure as a Web Role.

    Working with Cloud9 IDE


    The Cloud9 IDE allows the developers to build and run Node.js apps. Let me explain how to develop Node apps from the Cloud9 IDE in the following steps.

    Creating a New Project

    In the Cloud9 IDE, select the Create New Project from My Projects tab. In the Create a new project dialog, enter a project name and click the Create button to create a new project as shown in the below pictures.

    image

    The Cloud9 IDE

    image

    Create a New Project Dialog

     

    Creating and Editing files in Cloud9 IDE

    After creating a project in Cloud9, click Start Editing as shown in the below picture. This will enable you create and edit files in the Cloud9 IDE.

    image

    You can add a new file by select New File from File menu. This will add a new tab titled *Untitled1.

    image

    To save your file, select Save As option from the File menu. This will show the below dialog box, where you can enter the file name and save it to the project created in Cloud9.

    image

    Creating a Node.js App in Cloud9 IDE

    Our sample Node.js application is a simple app which provides request handlers for the following three types of HTTP requests.

    1. Request handler for Home page which will provide a HTML form with two form fields.
    2. Request handler for handling and processing posted data submitted from the HTML form.
    3. Request handler for Http 404 No Found requests.

    In this app, we will be creating a HTTP server which will be listen for HTTP requests.

     

       1:  var http = require('http');
       2:  var querystring = require('querystring');
       3:  var utils = require('util');
       4:  var url = require("url");
       5:   
       6:  var port=process.env.PORT;
       7:   
       8:   var server = http.createServer(function(req, res) {
       9:    switch (req.url) { //checking the request url
      10:      case '/':
      11:        homePageHandler (req, res); //handler for home page
      12:        break;
      13:      case '/register':  
      14:        registerFormHandler (req, res);//hamdler for register
      15:        break;
      16:      default:
      17:        nofoundHandler (req, res);// handler for 404 not found
      18:        break;
      19:    }
      20:  });
      21:  server.listen(port);
      22:  //function to display the html form
      23:  function homePageHandler (req, res) {
      24:    res.writeHead(200, {'Content-Type': 'text/html'});
      25:     var body = '<html>'+
      26:      '<head>'+
      27:      '<meta http-equiv="Content-Type" content="text/html; '+
      28:      'charset=UTF-8" />'+
      29:      '</head>'+
      30:      '<body>'+
      31:      '<form action="/register" method="post">'+
      32:      'Name:<input type=text value="" name="name" size=15></br>'+
      33:      'Email:<input type=text value="" name="email" size=15></br>'+
      34:      '<input type="submit" value="Submit" />'+
      35:      '</form>'+
      36:      '</body>'+
      37:      '</html>';
      38:  //response content
      39:  res.end(body);
      40:  }
      41:  //handler for Post request
      42:  function registerFormHandler (req, res) {   
      43:  //var pathname = url.parse(req.url).pathname;
      44:  //console.log("Request for " + pathname + " received.");    
      45:   var postData = "";    
      46:    req.on('data', function(chunk) {
      47:        // append the current chunk of data to the postData variable
      48:        postData += chunk.toString();
      49:      });   
      50:      req.on('end', function() {
      51:      
      52:     // doing something with the posted data
      53:        res.writeHead(200, "OK", {'Content-Type': 'text/html'});      
      54:        // parse the posted data
      55:        var decodedBody = querystring.parse(postData);
      56:        // output the decoded data to the HTTP response          
      57:        res.write('<html><head><title>Post data</title></head><body><pre>');
      58:        res.write(utils.inspect(decodedBody));    
      59:        res.write('</pre></body></html>');       
      60:        res.end();
      61:      });
      62:  }
      63:  //==========Error handler==========
      64:  function nofoundHandler(req, res) {    
      65:    res.writeHead(404, {'Content-Type': 'text/plain'});
      66:    res.end('404 Error - Request handler not found'); 
      67:  }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

     

    In the above section of the program, we are importing different Node modules to our program.

     

    var http = require('http');
    var querystring = require('querystring');
    var utils = require('util');
    var url = require("url");
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }


    In the Node.js sample app, we are creating a HTTP server which will be listening for HTTP requests. Based on the request url, the server will call the corresponding request handlers.

    var server = http.createServer(function(req, res) {
      switch (req.url) { //checking the request url
        case '/':
          homePageHandler (req, res); //handler for home page
          break;
        case '/register':  
          registerFormHandler (req, res);//hamdler for register
          break;
        default:
          nofoundHandler (req, res);// handler for 404 not found
          break;
      }
    });
    server.listen(port);
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Running the App from Cloud9 IDE

    You can run the apps from Cloud9 IDE by click Debug button from the toolbar

    debug

    The debugger will show an output window where you can get a URL generated by the Cloud9 IDE to access your application.

    debug_console

    Running App in Browser

    The below picture shows the output of the request for home page

    home_page

    The below picture shows the output of the request for the form action register. This will show the posted data submitted from a HTML form.

    register_posteddata

    Deploying Node.js App to Windows Azure using Cloud9 IDE

    You can easily create a Deployment for Windows Azure from Cloud9 IDE itself. To create a deployment for Windows Azure, Select Deploy and click Create a Deploy Server

    select_deploy 

    The option for Create a Deploy Server will show the below dialog box where you can choose the deployment type as Windows Azure for deploying apps to Windows Azure. This will show the below window for download and upload the Windows Azure publish settings.

    deploy_target_azure

    After uploading the Windows Azure publish settings, click Create new option to create a new hosted service in Windows Azure. You can also able to choose an existing hosted service deployed in Windows Azure. The below window for new hosted service allows you put configurations for your Windows Azure hosted service. After putting the configurations for Windows Azure, click the Create button for creating a new deployment for Windows Azure. This will create a new deployment and this will show a deployment under the Deploy tab.

    add_deploy_target

     

    Deploying the App to Windows Azure

    Under the Deploy tab of Cloud9 IDE, you can see all the deployments you have created earlier. For deploying our Node.js app to Windows Azure, click the deployment we have created previously.This will show the below dialog.

    deploy

    For the first time deployment for a new hosted service, it will ask for creating a new web.config and .csdef file as shown in the below pictures. Select Yes for crating a new web.config and .csdef file.

    no_webconfig

    no_csdef

    After creating the web.config and .csdef file, click the Deploy button for deploy our Node.js app to Windows Azure. This will successfully deploy our Node.js app to Windows Azure.

    Summary

    In this post, we have created a simple Node.js app with request handlers within the Cloud9 IDE and later deployed it to Windows Azure using Cloud9 IDE. The Windows Azure SDK for Node.js provides the all support to develop and deploy Node.js apps to Windows Azure. The Cloud9 IDE provides the greater support to build and deploy apps to Windows Azure.

  • EFMVC App Migrated to ASP.NET MVC 4

    I have upgraded my EFMVC app from ASP.NET MVC 3 to ASP.NET MVC 4 Beta. EFMVC is a demo web app initially built for demonstrating ASP.NET MVC and EF Code First. Now I am planning to add more features onto EFMVC and want to add cloud specific features with Windows Azure. You can expect more implementations in future releases.

    The current migration does not contains any major code changes. I have added a Windows Azure web role and will add some cloud specific features on later. The migration process was very smooth and the Autofac.MVC3 has been working with ASP.NET MVC 4 app without any issue.  But I am having some issues with  Autofac.MVC3 package while integrating with ASP.NET Web API services. I have used the current AutofacDependencyResolver class to integrating with DependencyResolver. The ASP.NET Web API expects a System.Web.Http.Services.IDependencyResolver implementation instead of System.Web.Mvc.IDependencyResolver which is used by ASP.NET MVC.

    The below is the updated feature list of the EFMVC app

    • Windows Azure Web Role
    • CRUD demo in ASP.NET MVC 4 with Entity Framework 4.3 Code First
    • Generic repository for Entity Framework Code First
    • Repository Pattern and Unit of Work
    • Dependency Injection using Autofac
    • Razor View Engine
    • Solution Architectures using Commands(write operations), Command Handlers, Command Dispatcher
    • ASP.NET Web API

    You can download the source from http://efmvc.codeplex.com/

  • ASP.NET MVC 4 Beta Released

    Microsoft has announced the availability of ASP.NET MVC 4 Beta. You can get the all details on ASP.NET MVC 4 Beta at http://www.asp.net/mvc/mvc4. The greatest new feature of ASP.NET MVC 4 Beta is the addition of ASP.NET Web API which lets the developers to build REST based services which can be easily consume from variety of clients including browsers and mobile devices. These HTTP services are ideal for clients which are building by using Ajax and following a highly responsive UI.

    For more details on ASP.NET Web API, you can watch the presentation taken by Daniel Roth, a Senior Program Manager at Microsoft, from here.

    The following are the other new features included in the ASP.NET MVC 4

    • Refreshed and modernized default project templates
    • New mobile project template
    • Many new features to support mobile apps
    • Recipes to customize code generation
    • Enhanced support for asynchronous methods

    The new ASP.NET MVC 4 project dialog is shown below

    image

  • Microsoft Reduces Prices on SQL Azure Cloud Storage

    Microsoft has reduced the price of SQL Azure storage which will greatly attract customers to migrating their apps to Windows Azure. The newly announced  price of SQL Azure decreases 48 percentages to 75 percentages of cost from the previous cost.

    The new price details are given below

    GB

    Previous Pricing

    New Pricing

    New Price/GB

    Total % Decrease

    5

    $49.95

    $25.99

    $5.20

    48%

    10

    $99.99

    $45.99

    $4.60

    54%

    25

    $299.97

    $75.99

    $3.04

    75%

    50

    $499.95*

    $125.99

    $2.52

    75%

    100

    $499.95 *

    $175.99

    $1.76

    65%

    150

    $499.95*

    $225.99

    $1.51

    55%

     

     

  • Tips and Important Steps for Migrating Apps to Windows Azure

     The following are the few important steps and tips for migrating ASP.NET apps to Windows Azure.

    1. Convert the ASP.NET application into a Web Role project.
    2. Verify that the application is running correctly in the development environment.
    3. Make sure that your application is 64-bit compatible since Window azure is a 64-bit environment.
    4. Since Window Azure Web Roles runs on IIS7 Integrated mode, make sure that your web application does not have any issues with running on IIS 7 Integrated mode.
    5. If your web app is using Session, Membership, Roles and Profile data, you have to find a way to make the state information is working with Windows Azure environment. You can use ASP.NET Universal Providers for handling Session, Membership, Roles and Profile which will be working with Sql Azure. The Windows Azure Caching Service is also providing a provider for ASP.NET Session state which will be faster than working with Sql Azure, but will be bit expensive than using Sql Azure.
    6. If you are using ASP.NET caching, it would be recommended to use The Windows Azure Caching Service. The Windows Azure Caching Service is the better way to use Caching in Windows Azure.
    7. Upload and save files to BLOB storage, if your web application is dealing with documents, media files, etc.
    8. If your application is using any Windows services or using any background processing, migrate these services to Worker Roles.
    9. Put messages to Windows Azure storage Queue or Service Bus Queue if you want to communicate between Web Role and Worker Role.
    10. If you want to make federated claims-based authentication and single sign-on, you can use Windows Azure Access Control Service (ACS) that enables federated authentication. It will work with external identity providers such as Windows Live, Google, Facebook, and Open ID and you can also able to define service identities in ACS that lets you to authenticate without using an external identity provider.
    11. Use startup tasks if you want to perform operations and install components before your Azure Role starts on Virtual Server. You can add startup tasks by editing the ServiceDefinition.csdef file.
    12. Consider moving out some configuration settings in web.config files to ServiceConfiguration.cscfg so that you do not require redeployment after every change in configuration. Data in the ServiceConfiguration.cscfg file can be edited at runtime.
    13. The Windows Azure environment does not provide a SMTP relay or mail relay service. So if your application is using e-mail services, it would be recommended to use a third party service (like SendGrid or AuthSMTP) to send email from inside Windows Azure.
    14. If you are using Sql Azure, use a SQL Server 2008 R2 client so that you can easily migrate database schema and data into Sql Azure. And you can connect the Sql Azure from the SQL Server 2008 R2 client.


     


  • Building a Windows Azure App using Azure Queue, Azure Table and ASP.NET MVC Web Role

    In this post, I will demonstrate a Windows Azure app using Azure Queue, Azure Table and a ASP.NET MVC 4 Web Role application. This post is explaining few initial steps for building a demo Azure app where asynchronous commands (write operations that changes the data) put into Azure Queue and an Azure Work Role will persist the data into Azure Table from Queue messages for the read operations. The source code is available from http://azurehack.codeplex.com/ .The demo application will modify and add more functionality on later.

    Windows Azure Storage Services


    The Windows Azure storage services provide the following services that are secure, scalable and easy to access that remain persistent and durable storage in the cloud.

    Binary Large Object (BLOB) – BLOB service is the file system in the cloud which provide storage for large pieces of data, such as images, video, documents etc. BLOB is the simplest way to store text or binary data on Windows Azure.

    Tables – Windows Azure Table Storage Service provides queryable structured storage.Table Storage service is very similar to NoSQL databases that lets you to massively scalable your apps.

    Queues – Queue service provides reliable storage and delivery of messages and can be use for messaging between Web and Worker role instances.

    Drives – Windows Azure Drive provides durable NTFS volumes for Windows Azure applications.

    Demo Windows Azure App

    In our demo app, all database write commands will be perform in an asynchronous way and these command messages will send  to Azure Queue.  A worker role will retrieve the Queue messages and will persist the data into Azure Table. The web role app is built with ASP.NET MVC 4. In this simple demo app, we are creating Customer entity data and these data will list  in a AS.NET MVC view page from a Azure Table. The request for creating a new Customer data will write a message to Azure Queue. The below class is representing the write command for creating new Customer

    public class NewCustomerCommand : AzureQueueMessage
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Address { get; set; }
            public string Phone { get; set; }
            public string Email { get; set; }
        }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

     

    The new NewCustomerCommand is inherited from a  class AzureQueueMessage. The AzureQueueMessage class is the base class for the Azure Queue messages.The AzureQueueMessage class is shown below

    public abstract class AzureQueueMessage
    {
        public string Id { get; set; }
        public string PopReceipt { get; set; }
        public int DequeueCount { get; set; }
        public DateTime? InsertionTime { get;  set; }
        public DateTime? ExpirationTime { get; set; }
    }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    We are using strongly typed Azure Queue message. The below code block shows the contract type for our strongly type Azure Queue

    public interface IAzureQueue<T> where T : AzureQueueMessage
    {
        void EnsureExist();
        void Clear();
        void AddMessage(T message);
        T GetMessage();
        T GetMessage(TimeSpan timeout);
        IEnumerable<T> GetMessages(int maxMessagesToReturn);
        void DeleteMessage(T message);
        void DeleteMessage(CloudQueueMessage message);
        void DeleteQueue();
        int ApproximateMessageCount { get; }
    }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

     

    Creating Queue messages from ASP.NET MVC Controller

    The below code block in the ASP.NET MVC action method will create the strongly typed queue message with type NewCustomerCommand. The write command NewCustomerCommand  is representing the operation for  creating a new Customer entity.

    CloudStorageAccount account;
    public CustomerController()
    {
        account = CloudStorageAccount.
             FromConfigurationSetting("DataConnectionString");
    }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
    [HttpPost]
    public ActionResult Create(CustomerFormModel formModel)
    {
    if (ModelState.IsValid)
    {
        AzureQueue<NewCustomerCommand> queue = new 
                            AzureQueue<NewCustomerCommand>(account);
        queue.AddMessage(new NewCustomerCommand
        {
            FirstName = formModel.FirstName,
            LastName = formModel.LastName,
            Address = formModel.Address,
            Phone = formModel.Phone,
            Email = formModel.Email
        });              
    return RedirectToAction("Index");
    }
     return View(formModel);
    }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

     

    The class AzureQueue is a strongly typed Azure Queue. We are adding a message to the Queue with the information of  NewCustomerCommand. A worker role will look on the Queue message and will perform the operations for our command.

    Processing Queue messages in Worker Role

    The Worker Role is similar to a windows service and mainly using for background processing. In our application, we are using the Worker Role for processing the Queue message send from Web Role application. The Azure Queue is a great way to communicate between Web Role and Worker Role.

    In the following code block in Worker Role, we are creating a strongly typed Queue with NewCustomerCommand and getting the unprocessed Queue messages from the Queue. After that, the data of the each Queue message is using for creating a Customer entity and will persist this data into Azure Table. The Table storage can be use for read operations of our application. We are deleting the Queue message after persisting the Customer entity into Azure Table.

    var account = CloudStorageAccount.
    FromConfigurationSetting("DataConnectionString");
    AzureQueue<NewCustomerCommand> queue = new 
       AzureQueue<NewCustomerCommand>(account);
    queue.EnsureExist();            
                
    while (true)
    {
    try
    {
     var message = queue.GetMessage();                    
     if (message != null)
      {
            
    AzureTable<Customer> table = new AzureTable<Customer>(account);
        var guiid= Guid.NewGuid().ToString();
        table.AddEntity( new Customer
        {
            Id = Guid.NewGuid().ToString(),
            PartitionKey = guiid,
            RowKey = message.FirstName,
            FirstName = message.FirstName,
            LastName=message.LastName,
            Address=message.Address,
            Phone=message.Phone,
            Email=message.Email 
        });
        queue.DeleteMessage(message);
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
        }
        }
        catch { }
        Thread.Sleep(5000);
    }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    We are using a Azure Table entity Customer for persisting the Customer data. The Customer Table entity is shown below

    public class Customer : TableServiceEntity
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
    }

    The Customer entity is inherited from TableServiceEntity for making the Customer entity as a Azure Table. The TableServiceEntity provides properties PartionKey, RowKey and Timestamp. The server manages the value of Timestamp, which cannot be modified. We need to update the values of PartitionKey and RowKey.The partition key is a unique identifier for the partition within a given table, specified by the PartitionKey property. The partition key forms the first part of an entity's primary key. The second part of the primary key is the row key, specified by the RowKey property. The row key is a unique identifier for an entity within a given partition. Together the PartitionKey and RowKey uniquely identify every entity within a table.

    The AzureTable class is using for the all CRUD operations for Azure Table. The below code block shown the contract type of AzureTable class.

    public interface IAzureTable<TEntity> where TEntity : TableServiceEntity
    {
        IQueryable<TEntity> Query { get; }
        bool CreateIfNotExist();
        bool DeleteIfExist();
        void AddEntity(TEntity obj);
        void AddEntity(IEnumerable<TEntity> objs);
        void AddOrUpdateEntity(TEntity obj);
        void AddOrUpdateEntity(IEnumerable<TEntity> objs);
        void DeleteEntity(TEntity obj);
        void DeleteEntity(IEnumerable<TEntity> objs);
    }
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Reading the data in ASP.NET MVC App

    We are showing the Customer data from Azure table and periodically refresh the data using Ajax. The following code in the ASP.NET MVC action method querying the data from Azure Table Customer.

    public ActionResult Index()
    {
      AzureTable<Customer> table = new AzureTable<Customer>(account);
      var customers = table.Query;
      if (Request.IsAjaxRequest())
      {
         return PartialView("_List", customers);
      }
     return View(customers);
    }
     

    Since our write command is working in an asynchronous way, we are refreshing the view page periodically using Ajax for latest data

    @model IEnumerable<AzureHacks.Domain.Models.Customer>
    @{
        ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <div id="CustomerList">
    @Html.Partial("_List", Model)
    </div>
     <script type="text/javascript">
    $(function () {
    setInterval(function () {
     $.get('@Url.Action("Index")', {}, function (view) {
        $("#CustomerList").html(view);
      })
     },5000);
    });
    </script>   

    Source Code

    The source code can be download from http://azurehack.codeplex.com/

    Summary

    This post is an initial step for building a demo app on the Windows Azure. We have discussed Azure storage services Queue and Table and explored the Worker Role for processing Queue messages. Azure Queue is a great way to communicate between Web Role and Worker Role. And the Azure Table is providing a great way to store massively scalable structured data that is available for querying the data. We are are performing our commands in an asynchronous way  and Azure Table is using for our read operations.

  • Startup Tasks for Windows Azure Roles

    Windows Azure supports startup tasks that can be use to perform operations and install components before your Azure Role starts on Virtual Server. You can use to startup tasks to install other software, register COM components, setting registry keys, start another process, etc. This is very useful in many situations where you might want to running an initialization scripts, execute batch files and PowerShell scripts etc before your Role starts. In the past, I had used a startup task to install ASP.NET MVC 3 when ASP.NET MVC 3 web role was not supported. You can add startup tasks by editing the ServiceDefinition.csdef file. The below configuration in the Service Definition  file will add a startup task.

    <?xml version="1.0" encoding="utf-8"?>
    <ServiceDefinition name="AzureDemo" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
      <WebRole name="WebRole1" vmsize="Small">
        <Startup>
         <Task commandLine="install.cmd" executionContext="elevated" />
        </Startup>
     <!--Other Configurations below-->
       </WebRole>
    </ServiceDefinition>

    The above configuration added a batch file install.cmd as a startup task. You should add the batch file install.cmd onto your Azure Role project. The executionContex attribute specifies the permission level.This value can be limited or elevated. The elevated execution context enables administrator level permission and limited level permission gives non-admin level permission. Windows Azure will look for the bin folder for the startup tasks. So you should specify the batch file as “Copy to Output Directory” in Visual Studio so that the batch file will be copied to bin folder of your Azure Role. In our example, the batch file install.cmd will be executed before the Azure role  starts.

  • Visual Studio Enhancements in Windows Azure SDK 1.6 for Publishing Apps

    The new Windows Azure SDK 1.6 is providing many enhancements including a better experience for publishing Windows Azure applications using Visual Studio. To publish an application onto Azure, do the following steps.

    First right click on the Azure project from Visual Studio and Select Publish. The below publish window will show.

    Publish_SignIn

     

    When you run the publish wizard  for the first time, you must download your credentials from Windows Azure portal. Choose the Sign In To Download Credentials link from the Sign in window. This will redirects to Windows Azure portal which will  generate a publish-settings file for you to download. This will be generated a file and prompt for download the file from the location https://windows.azure.com/download/publishprofile.aspx . The generated file will be en extension with publishsettings which contains the credentials and subscriptions information. After download the file, you need to import the publish-settings file into the Windows Azure publish window. Then you can chose a subscription from the populated subscriptions drop down and proceed.

    The next step is setting the publication settings. In the Settings window, we can select a service to deploy or create a new hosted service. The below window shows the option for create a new Windows Azure hosted service. To create a new hosted service, give the hosted service name and the location. The new feature lets the Azure developers to create hosted service accounts without going to Windows Azure portal.

    azure_newhosterservice

    In the Settings Window, we can set hosted service, cloud environment  (production or staging), the build configuration (release or debug), and the Service configuration file (cloud or local) to be used. We also can select the Advanced Settings tab to specify the deployment label, storage account information etc. We can also able to setting up remote desktop by checking the  related checkbox. The below windows shows the Remote Desktop Configuration.

    rdcide


    Click the next button after completing the Settings, this will show the summary details of settings we had just specified and it will save the all information as new profile. You can use these settings when we are publishing the project again. The final step is to click the publish button. This will proceed the publish and deploy our application onto Windows Azure.

    Summary 

    The new Windows Azure SDK 1.6 is providing a better developer experience for deploying Windows Azure  apps from Visual Studio. The new features lets the Visual Studio developers to deploy Windows Azure apps without touching the Windows Azure portal. We can now create hosted services and able to specify all the settings to deploy apps to Azure from Visual Studio itself that lets better productivity to the Azure developers.

  • CQRS, Commands, Command Handlers and Command Dispatcher

    In this post, I am trying to add some CQRS principles onto my EFMVC project. Please keep in mind that this is not the implementation CQRS patterns, but trying to add some CQRS flavors on the Solution Architecture with Commands that changes the data (Create, Update and Delete). The current implementation of command execution is implemented in a synchronous way. 

    CQRS 

    CQRS is stands for Command-Query Responsibility Segregation that is a principle of separating commands (that change the data) from queries (that read the data). The CQRS pattern is first described by Greg Young and his blog post CQRS, Task Based UIs, Event Sourcing agh! has explained about this approach. If you want to build real world CRQS based apps, I highly recommending to read Rinta Abdullin's blog and the CQRS info site.

    Domain Entity

    The below domain entity Category is using for demo  application

    public class Category
    {
        public int CategoryId { getset; }
        [Required]
        public string Name { getset; }
        public string Description { getset; }
    }

     
    Command


    Every write operations represent a command and these commands will be executed by using a Command Handler.  Let’s add command object CreateOrUpdateCategoryCommand for representing the Create and Update write operation.

    public class CreateOrUpdateCategoryCommand : ICommand
    {
        public CreateOrUpdateCategoryCommand(int CategoryId,string name, string description)
        {
            this.CategoryId = CategoryId;
            this.Name = name;
            this.Description = description;
        }
        public int CategoryId { getset; }
        public string Name { getset; }
        public string Description { getset; }
    }


    The interface ICommand is now just using for IoC purpose to hook corresponding Command Handler object.

    public interface ICommand  { }
    

    Command Handler


     The following code is shown the Command Handler for the command object CreateOrUpdateCategoryCommand.

    public class CreateOrUpdateCategoryHandler : ICommandHandler<CreateOrUpdateCategoryCommand>
    {
        private readonly ICategoryRepository categoryRepository;
        private readonly IUnitOfWork unitOfWork;
        public CreateOrUpdateCategoryHandler(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)
        {
            this.categoryRepository = categoryRepository;
            this.unitOfWork = unitOfWork;
        }
        public ICommandResult Execute(CreateOrUpdateCategoryCommand command)
        {
            var category = new Category
            {
                CategoryId = command.CategoryId,
                Name = command.Name,
                Description = command.Description
            };
            if (category.CategoryId == 0)
                categoryRepository.Add(category);
            else
                categoryRepository.Update(category);
            unitOfWork.Commit();
            return new CommandResult(true);
        }
    }

     The CreateOrUpdateCategoryHandler object will do the data persistence for the command operation CreateOrUpdateCategoryCommand.

    The ICommandHandler<T> interface is shown below

     public interface ICommandHandler<in TCommand> where TCommand: ICommand
        {
            ICommandResult Execute(TCommand command);
        }

     Command Validator


    Every command object would be submitted to a Command Bus that will be hook the right command handler and will execute the command operation. In this demo app, we just validate the command before submitting the command to command bus.


    The following is Validator for our command CreateOrUpdateCategoryCommand

    public class CanAddCategory : IValidationHandler<CreateOrUpdateCategoryCommand>
    {
        private readonly ICategoryRepository categoryRepository;      
        public CanAddCategory(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)
        {
            this.categoryRepository = categoryRepository;           
        }
        public IEnumerable<ValidationResult> Validate(CreateOrUpdateCategoryCommand command)
        {
            Category isCategoryExists=null;
            if(command.CategoryId==0)
                isCategoryExists = categoryRepository.Get(c => c.Name == command.Name);
            else
                isCategoryExists = categoryRepository.Get(c => c.Name == command.Name && c.CategoryId!=command.CategoryId);
            if (isCategoryExists!=null )
            {
                yield return new ValidationResult("Name"Resources.CategoryExists);
            }
        }
    }

     
    The IValidationHandler<T> interface is shown below

    public interface IValidationHandler<in TCommand> where TCommand : ICommand
    {
        IEnumerable<ValidationResult>  Validate(TCommand command);
    }


    Command Dispatcher


    The responsibility of the Command Dispatcher object is to hook right Command Handler object based on the command object we have submitted to the Command Dispatcher object. Autofac IoC container is using to hook the Command Handler object for the given command object.
    The following is the contract type of Command Dispatcher

    public interface ICommandBus
    {
        ICommandResult Submit<TCommand>(TCommand command) where TCommand: ICommand;
        IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand;
    }

     
    The default implementation of the ICommandBus is shown below

    public class DefaultCommandBus : ICommandBus
    {
        public ICommandResult Submit<TCommand>(TCommand command) where TCommand: ICommand
        {    
            var handler = DependencyResolver.Current.GetService<ICommandHandler<TCommand>>();
            if (!((handler != null) && handler is ICommandHandler<TCommand>))
            {
                throw new CommandHandlerNotFoundException(typeof(TCommand));
            }  
            return handler.Execute(command);
     
        }
        public IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand
        {
            var handler = DependencyResolver.Current.GetService<IValidationHandler<TCommand>>();
            if (!((handler != null) && handler is IValidationHandler<TCommand>))
            {
                throw new ValidationHandlerNotFoundException(typeof(TCommand));
            }  
            return handler.Validate(command);
        }
    }


    The command bus provides two methods – Submit and Validate. The submit method will execute the appropriate command handler object and the validate method is used for validating the command object before submitting the command. The default command bus object provides the command execution in a synchronous way. In many real world CQRS implementations, this would be in anasynchronous way.

    Component Registration in Autofac

    The following code is using in the EFMVC project to register components with Autofac.

    private static void SetAutofacContainer()
    {
        var builder = new ContainerBuilder();          
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<DefaultCommandBus>().As<ICommandBus>().InstancePerHttpRequest();
        builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
        builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerHttpRequest();
        builder.RegisterAssemblyTypes(typeof(CategoryRepository).Assembly)
        .Where(t => t.Name.EndsWith("Repository"))
        .AsImplementedInterfaces().InstancePerHttpRequest();          
        var services = Assembly.Load("EFMVC.Domain");
        builder.RegisterAssemblyTypes(services)
        .AsClosedTypesOf(typeof(ICommandHandler<>)).InstancePerHttpRequest();
        builder.RegisterAssemblyTypes(services)
        .AsClosedTypesOf(typeof(IValidationHandler<>)).InstancePerHttpRequest();
        builder.RegisterType<DefaultFormsAuthentication>().As<IFormsAuthentication>().InstancePerHttpRequest();
        builder.RegisterFilterProvider();
        IContainer container = builder.Build();                  
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }


    ASP.NET MVC Controller 

    In our demo app, the command object CreateOrUpdateCategoryCommand is creating and submitting to Command Bus from a ASP.NET MVC controller action method. In the following action method, we are creating the CreateOrUpdateCategoryCommand object based form values and calling the Validate method of command bus. The command is valid, we will submit the command object to the Command Bus object and execute the command operation in a synchronous way.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Save(CategoryFormModel form)
    {
        if(ModelState.IsValid)
        {
            var command = new CreateOrUpdateCategoryCommand(form.CategoryId,form.Name, form.Description);
            IEnumerable<ValidationResult> errors=  commandBus.Validate(command);
            if (errors.Count() > 0)
            {
                ModelState.AddModelErrors(errors);
            }
            if (ModelState.IsValid)
            {
                var result = commandBus.Submit(command);
                if (result.Success) return RedirectToAction("Index");                 
            }                
        }   
        //if fail
        if (form.CategoryId == 0)
            return View("Create",form);
        else
            return View("Edit", form);
    }    

    Source Code

    You can download the source code from http://efmvc.codeplex.com/.  



More Posts Next page »
Copyright © 2002-2008 Chennai .Net User Group. All Rights Reserved. Microsoft and Microsoft logo's are trademarks of Microsoft Corporation