One of the nice things about having a single extensibility model between ASP.NET MVC and Web API is that you can get many of the great MVC features for free. Model binding and validation is one of them.

A simple action in Web API controller is typically associated to a Http verb and can optionally receive or return a model (or a message if you want to have better control over the http messaging details). For example, the following implementation illustrates a simple case for creating a contact when an Http POST is received,

public class ContactController : ApiController
{
    IContactRepository repository;
 
    public ContactController(IContactRepository repository)
    {
        this.repository = repository;
    }
 
    public HttpResponseMessage Post(Contact contact)
    {
        int id = this.repository.Create(contact);
 
        var response = new HttpResponseMessage(HttpStatusCode.Created);
        response.Headers.Location = new Uri("/api/Contact/" + id);
 
        return response;
    }
}

All the details for deserializing the request message into a Contact model is automatically handled by the Web API infrastructure. It actually uses the model binding feature found in MVC but it also adds content negotiation on top of it.

Content negotiation in Web API is implemented through formatters that know how to serialize/deserialize an specific payload associated to a content type (json or html for example) into a model.

As you probably know, the model binding infrastructure in MVC also allows validations on model classes decorated with data annotations. That means you can decorate your models with different validation attributes as it shown bellow,

public class Contact
{
    [Required]
    public string FullName { get; set; }
 
    [Email]
    public string Email { get; set; }
}

The model binding infrastructure will validate the model but Web API will not do anything with it by default. If you want to reject a message based on the result of the validations, you need to implement a custom filter in the current bits.

That can be done by extending an ActionFilterAttribute and overriding the OnActionExecuting method.

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            var errors = actionContext.ModelState
                .Where(e => e.Value.Errors.Count > 0)
                .Select(e => new Error
                {
                    Name = e.Key,
                    Message = e.Value.Errors.First().ErrorMessage
                }).ToArray();
 
            actionContext.Response = new HttpResponseMessage<Error[]>(errors, HttpStatusCode.BadRequest);
        }
    }
}

As you can see, the implementation is very simple. It only checks whether the model state is valid and return a list of validation errors. The execution pipeline will be automatically interrupted and response will be sent back to the client with the list of errors. I am also using a model for representing an error so Web API can send the expected wire format to the client application (If the client is expecting json, it will receive a list of errors formatted as json for example).

This validation attribute can be injecting into the execution pipeline by either decorating the api controller with it or by adding it to the global filters collection.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new ValidationActionFilter());
}

Now, let’s see how this works in action with Fiddler. If we send a json message with an invalid email,

POST http://localhost:16913/api/Contact HTTP/1.1

Content-Type: application/json

Host: localhost:16913

Content-Length: 30

{"fullname":"re","email":"re"}

We will receive a response also formatted as json,

HTTP/1.1 400 Bad Request

Content-Type: application/json; charset=utf-8

[{"Message":"The Email field is not a valid e-mail address.","Name":"Email"}]

 

If we change the request message a little bit to expect xml as response

POST http://localhost:16913/api/Contact HTTP/1.1

Accept: text/xml

Content-Type: application/json

Host: localhost:16913

Content-Length: 31

{"fullname":"re","email":"foo"}

We will get a list of errors formatted as xml this time

HTTP/1.1 400 Bad Request

Content-Type: text/xml; charset=utf-8

<?xml version="1.0" encoding="utf-8"?><ArrayOfError xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Error><Name>Email</Name><Message>The Email field is not a valid e-mail address.</Message></Error></ArrayOfError>

Posted by cibrax | 5 comment(s)
Filed under: , ,

In case you did not see the latest news, what we used to know as WCF Web API was recently rebranded and included in ASP.NET MVC 4 as ASP.NET Web API. While both frameworks are similar in essence with focus on HTTP, the latter was primarily designed for building HTTP services that don’t typically require an user intervention. For example, some AJAX endpoints or a Web API for a mobile application. While you could use ASP.NET MVC for implementing those kind of services, that would require some extra work for implementing things right like content-negotiation, documentation, versioning, etc. What really matter is that both framework share many of the extensibility points like model binders, filters or routing to name a few.

If you don’t know what Backbone.js is, this quote from the main page in the framework website will give you some idea,

“Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface. “

You see, the framework will help you to organize your javascript code for the client side using an MVC pattern, and it will also provide an infrastructure for connecting your models with an existing Web API. (I wouldn’t use the term RESTful here as it usually implies your services adhere to all the tenets discussed in the Roy Fielding’s dissertation about REST). 

That means you should be able to connect the backbone.js models with your MVC Web API in a more natural way. As part of this post, I will use the “Todos” example included as part of the backbone.js code, but I will connect that to a Web API built using the new ASP.NET Web API framework. 

On the client side, a model is defined for representing a Todo item.

// Our basic **Todo** model has  `id`, `text`, `order`, and `done` attributes.
window.Todo = Backbone.Model.extend({
 
    idAttribute: 'Id',
 
    // The rest of model definition goes here
});

There is also a collection for representing the Todo list,

// The collection of todos is backed by *localStorage* instead of a remote
// server.
window.TodoList = Backbone.Collection.extend({
 
    // Reference to this collection's model.
    model: Todo,
 
    url: function () {
        return 'api/todos';
    },
 
    // The rest of the collection definition goes here
});

I modified the code for this collection to override the “url” setting. This new url will point to the route of our Web API controller. Backbone will try to synchronize all the changes in the models by sending http requests with the corresponding verb (GET, POST, PUT or DELETE) to that url.

Now, the interesting part is how we can define the Web API controller using the new ASP.NET Web Api framework.

public class TodosController : ApiController
{
    public IEnumerable<TodoItem> Get()
    {
        return TodoRepository.Items;
    }
 
    public IdModel Post(TodoItem item)
    {
        item.Id = Guid.NewGuid().ToString();
        
        TodoRepository.Items.Add(item);
 
        return new IdModel{ Id = item.Id };
    }
 
    public HttpResponseMessage Put(string id, TodoItem item)
    {
        var existingItem = TodoRepository.Items.FirstOrDefault(i => i.Id == id);
        if (existingItem == null)
        {
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
 
        existingItem.Text = item.Text;
        existingItem.Done = item.Done;
 
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
 
    public void Delete(string id)
    {
        TodoRepository.Items.RemoveAll(i => i.Id == id);
    }
}

As you can see, the code for implementing the controller is very clean and neat. A name convention based on the Http Verbs can be used to route the requests to the right controller method. Therefore, I have different methods for retrieving the list of items (GET), creating a new item (POST), updating an existing item (PUT) or just delete it (DELETE)

A few things to comment about the code above,

  1. I haven’t specified the wire format anywhere in the code. The framework will be smart enough to do content negotiation based on the headers sent by the client side (In this case text/json).
  2. You can return any serializable class or a HttpResponseMessage if you want to have better control over the returned message (set the status code for example).
  3. The framework will take care of serialize or deserialize the message on the wire to the right model (TodoItem in this case)
  4. A hardcoded repository is being used, which is not a good practice at all, but you can easily inject any dependency into the controllers as you would do with the traditional ASP.NET MVC controllers.

Here is the class definition for the TodoItem model,

public class TodoItem : IdModel
{
    public int Order { get; set; }
    public string Text { get; set; }
    public bool Done { get; set; }
}

The IdModel is just a workaround for returning only an Id property to the client side when a new item is created. This is what backbone needs to associate an id to a new model. A more elegant solution would be to return an anonymous object with the id (such as new { Id = “xxx” }), but the default serializer for Json in the current bits (DataContractJsonSerializer) can not serialize them. Extending the built-in formatter to use a different serializer is something I am going to show in a different post.

public class IdModel
{
   public string Id { get; set; }
}

The default routing rule in the global.asax file is configured like this,

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

All the calls to a API controller must be prefixed with “api”. That’s why I set the url to “api/todos” in the backbone model.

Posted by cibrax | 2 comment(s)

Although JQuery provides a very good support for caching responses from AJAX calls in the browser, it is always good to know how you can use http as protocol for making an effective use of it.

The first thing you need to do on the server side is to supports HTTP GETs, and identify your resources with different URLs for retrieving the data (The resource in this case could be just a MVC action). If you use the same URL for retrieving different resource representations, you are doing it wrong. An HTTP POST will not work either as the response can not cached. Many devs typically use HTTP POSTs for two reason, they want to make explicit the data can not be cached or they use it as workaround for avoiding JSON hijacking attacks, which can be avoided anyways in HTTP GETs by returning a JSON array.

The ajax method in the JQuery global object provides a few options for supporting caching and conditional gets,

$.ajax({
    ifModified: [true|false],
    cache: [true|false],
});

The “ifModified” flag specifies whether we want to support conditional gets in the ajax calls. JQuery will automatically handle everything for us by picking the last received “Last-Modified” header from the server, and sending that as “If-Modified-Since” in all the subsequent requests. This requires that our MVC controller implements conditional gets. A conditional get in the context of http caching is used to revalidate an expired entry in the cache. If JQuery determines an entry is expired, it will be first try to revalidate that entry using a conditional get against the server. If the response returns an status code 304 (Not modified), JQuery will reuse the entry in the cache. In that way, we can save some of the bandwidth required to download the complete payload associated to that entry from the server.

The “cache” option basically overrides all the caching settings sent by the server as http headers. By setting this flag to false, JQuery will add an auto generated timestamp in the end of the URL to make it different from any previous used URL, so the browser will not know how to cache the responses.

Let’s analyze a couple scenarios.

The server sets a No-Cache header on the response

The server is the king. If the server explicitly states the response can not be cached, JQuery will honor that. The “cache” option on the ajax call will be completely ignored.

$('#nocache').click(function () {
    $.ajax({
        url: '/Home/NoCache',
        ifModified: false,
        cache: true,
        success: function (data, status, xhr) {
            $('#content').html(data.count);
        }
    });
});
public ActionResult NoCache()
{
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
   return Json(new { count = Count++ }, JsonRequestBehavior.AllowGet);
}

The server sets an Expiration header on the response

Again, the server is always is the one in condition for setting an expiration time for the data it returns. The entry will cached on the client side using that expiration setting.

$('#expires').click(function () {
    $.ajax({
        url: '/Home/Expires',
        ifModified: false,
        cache: true,
        success: function (data, status, xhr) {
            $('#content').html(data.count);
        }
    });
});
public ActionResult Expires()
{
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(5));
    return Json(new { count = Count++ }, JsonRequestBehavior.AllowGet);
}

The client never caches the data

The client side specifically states the data must be always fresh and the cache not be used. This means the “cache” option is set to false. No matter what the server specifies, JQuery will always generate an unique URL so that will be impossible to cache.

$('#expires_nocache').click(function () {
    $.ajax({
        url: '/Home/Expires',
        ifModified: false,
        cache: false,
        success: function (data, status, xhr) {
            $('#content').html(data.count);
        }
    });
});
public ActionResult Expires()
{
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(5));
    return Json(new { count = Count++ }, JsonRequestBehavior.AllowGet);
}

The client and server use conditional gets for validating the cached data.

The client puts a new entry in the cache, which will be validated after its expiration.  The server side must implement a conditional GET using either ETags or the last modified header.

$('#expires_conditional').click(function () {
    $.ajax({
        url: '/Home/ExpiresWithConditional',
        ifModified: true,
        cache: true,
        success: function (data, status, xhr) {
            $('#content').html(data.count);
        }
    });
});
public ActionResult ExpiresWithConditional()
{
    if (Request.Headers["If-Modified-Since"] != null && Count % 2 == 0)
    {
        return new HttpStatusCodeResult((int)HttpStatusCode.NotModified);
    }
    
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(5));
    Response.Cache.SetLastModified(DateTime.Now);
 
    return Json(new { count = Count++ }, JsonRequestBehavior.AllowGet);
}

The MVC action in the example above is only an example. In a real implementation, the server should be able to know whether the data has changed since the last time it was served or not.

Posted by cibrax | 2 comment(s)
Filed under: , ,

Another important milestone in my career started three years ago when I joined Tellago. I convinced my friend Jesus to hire me, and I would eventually move to the United States with my family to work in the company.  That never occurred for some personal things, but I fortunately had a chance to create an excellent team of very talented people in Argentina. I started myself working remotely from Argentina, and the things went so well for the company that we end up hiring more than 15 great architects down here in Argentina.  Creating this team was a very interesting and completely new challenge in my career.

I also got involved in a lot of interesting projects, and what is more important, I had a chance to work and met great people, which is what it really worth it.

However, a month ago, I decided it was about time to start a personal project with a good friend of mine, and that’s how AgileSight was born. Although the initial conception of the company was to create software products, we will also offering software consulting and development services. I am definitely very excited to be part of this new venture and face all new kind of challenges ahead.

My first assignment in AgileSight couldn’t be better as I will be working in the next Web Mobile Guidance project (Liike project) with the Microsoft Patterns & Practices team.

Posted by cibrax | 1 comment(s)
Filed under: ,

Limited connectivity is one of the main challenges in web mobile. The stateless nature of http causes that  content  and associated static files like scripts or images be transmitted over the wire every time a page is fully refreshed (assuming http caching is not implemented correctly). Diverse techniques have emerged over the years to solve part of that problem by using the browser AJAX support. One of these techniques, which drastically changed the way we develop web applications is know as single page applications.

A single page application design assumes that good part of the website layout is fixed and there are a few placeholders for showing dynamic content. The layout and associated files can be download once, and the rest can be dynamically changed using AJAX calls to a backend Web API.    

There are also a few improvements that can be made like caching all the static content and associated files, and use client templates to remove all the overhead involved with downloading html markup on every AJAX call. By using client templates (e.g. JQuery templates, JSRender, Mustache) , only the data (usually JSON data) is negotiated with the backend, and the templates can be cached as static content as well.

In the area of web mobile, it is pretty important to optimize the use of the available bandwidth to support scenarios where the connectivity is very unreliable or limited data plans are used. This is exactly where single page applications make a lot of sense. As this kind of application makes a heavy use of javascript for DOM manipulation, it might not be ideal for all kind of mobile devices (the device should support DOM manipulation and XHR).

I personally think this kind of architecture for a web application will become a common norm now that we have devices with web support everywhere.

Posted by cibrax | 4 comment(s)
Filed under: ,

One common problem with the naming convention and default routing mechanism in ASP.NET MVC is that we tend to group actions in a controller for sharing an URL space.  This basically leads to complex controllers with a lot of unrelated methods that break the SOLID principles.  Too many responsibilities in a simple class affects maintainability in the long run and causes secondary effects that complicates unit testing. For example, we usually end up with class constructors that receives too many dependencies as it is discussed here in SO.

A service façade or a service locator are not the solution for this problem either. I personally think the solution here is to use controllers with fewer responsibilities and define the right routing in case you want to share the URL space. There are some discussions around the idea of using what was called controller-less actions, in which a controller only performs a single thing. Without going to that extreme, we can use a more resource oriented approach for assigning responsibilities to a controller.  A resource in http is uniquely identified by an URI  and can be manipulated through an unified interface with http verbs. Although some verbs do not make much sense when working with a browser like “delete” or “put”, we can replace those with “post”.

Implementing a delete action with an http get is definitely wrong, as an http get should be idempotent.

Let’s start an example by defining a simple scenario for managing a set of customers. We can initially define two resources, Customers for performing actions in the collection, and Customers/{id} for performing actions in a single customer. Although they both share the same URL space “Customers”, it does not mean we need to implement all the functionality in a single controller called “Customers”. We can still have a “CustomersController” for the collection, and a “CustomerController” for the individual customers. We can use routing for share the same URL and still forward the requests to the right controller.

We can define the following operations in the “CustomersController”,

  • Add (GET Customers/Add): Retrieves the Html form representation for creating a new customer
  • Add (POST Customers/Add): Receives a representation (encoded in the form) for creating a new customer in the collection
  • Delete (POST Customers/{id}/Delete: Removes a customer from the collection
  • Index (GET Customers): Retrieves a Html view representing a list of customers
public class CustomersController : Controller
{
    ICustomerRepository repository;
 
    public CustomersController()
        : this(new CustomerRepository())
    {
    }
 
    public CustomersController(ICustomerRepository repository)
    {
        this.repository = repository;
    }
 
    public ActionResult Index(string filter = null)
    {
        IEnumerable<Customer> customers = null;
 
        if (!string.IsNullOrEmpty(filter))
        {
            customers = this.repository.GetAll()
                .Where(c => c.FirstName.Contains(filter) || c.LastName.Contains(filter));
        }
        else
        {
            customers = this.repository.GetAll();
        }
        
        return View(customers);
    }
 
    [HttpGet]
    public ActionResult Add()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Add(Customer customer)
    {
        if(ModelState.IsValid)
            this.repository.Add(customer);
 
        return RedirectToAction("Index");
    }
 
    [HttpPost]
    public ActionResult Delete(int id)
    {
        this.repository.Delete(id);
 
        if (Request.IsAjaxRequest())
            return new HttpStatusCodeResult((int)HttpStatusCode.OK);
 
        return RedirectToAction("Index");
    }
 
}

The “CustomerController” can have the following operations:

  • Get (GET Customers/{id}): Retrieves an Html form representing an specific customer
  • Update (POST Customers/{id}): Receives a representation (encoded in the form) for updating the customer
public class CustomerController : Controller
{
    ICustomerRepository repository;
 
    public CustomerController()
        : this(new CustomerRepository())
    {
    }
 
    public CustomerController(ICustomerRepository repository)
    {
        this.repository = repository;
    }
 
    [HttpGet]
    public ActionResult Get(int id)
    {
        var customer = this.repository.GetAll()
            .Where(c => c.Id == id)
            .FirstOrDefault();
 
        if (customer == null)
            return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);
 
        return View(customer);
    }
 
    [HttpPost]
    public ActionResult Update(Customer customer)
    {
        if (ModelState.IsValid)
            this.repository.Update(customer);
 
        return RedirectToAction("Index", "Customers");
    }
 
}

This is how the routing table looks like,

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
    //This map is required so the Add segment is not used as {id}
    routes.MapRoute(
      name: "CustomerAdd",
      url: "Customers/Add",
      defaults: new { controller = "Customers", action = "Add" }
      );
 
    routes.MapRoute(
       name: "CustomerGet",
       url: "Customers/{id}",
       defaults: new { controller = "Customer", action = "Get" },
       constraints: new { httpMethod = new HttpMethodConstraint("GET") }
       );
 
    routes.MapRoute(
        name: "CustomerUpdate",
        url: "Customers/{id}",
        defaults: new { controller = "Customer", action = "Update" },
        constraints: new { httpMethod = new HttpMethodConstraint("POST") }
        );
 
    routes.MapRoute(
        name: "MVC Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
 
   
}

You can override the default route for “Customers/{id}” for getting or updating an specific customer by using an http method constraint. I also added the first  route for adding a new customer so the “Add” segment is not used as the “{id}” wildcard.

As you could see, we could split all the responsibilities in two controllers, which look simpler at first glance. In conclusion, you don’t need to assume the same URL means the same controller.

The “delete” action is implemented as an http post. This can be sent from the browser by using an Ajax call or a Http form. For example, the following code shows how to do that using a JQuery Ajax call.

@Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "delete" })
<script type="text/javascript" language="javascript">
   1:  
   2:     $(function () {
   3:         $('.delete').click(function () {
   4:             var that = $(this);
   5:             var url = that.attr('href');
   6:  
   7:             $.post(url, function () {
   8:                 alert('delete called');
   9:             });
  10:  
  11:             return false;
  12:         });
  13:     });
</script>
The code is available for download from here
Posted by cibrax | 4 comment(s)
Filed under: , ,

Microsoft Patterns & Practices has recently started a new project whose codename is “Liike” (pronounced as LEEE-keh) for delivering guidance and a reference application in the mobile web space. As many of the recent initiatives started by different teams in Microsoft, this project will also be hosted in GitHub under http://liike.github.com/. All the artifacts, patterns and code generated during the project will be shared as part of that project.

Html5 and the rise of mobile devices have contributed to make Web Mobile one of the hot topics nowadays. Embarking in a new project for implementing a web mobile application can be a bit cumbersome without proper documentation or knowledge of proven practices. This project will try to address many of the concerns you might have by showing different patterns or solutions that can be applied in the context of web mobile, and how those solutions get reflected in real code with the Microsoft stack. The idea is not produce reusable code, but a reference application that people can explore.

As any of projects in MS Patterns & Practices, Microsoft does not have the final word on any of the discussed topics and a lot of feedback is received. They also have a team of external advisors with a bunch of talented people that have an extensive background working in this space.

Your help is always very valuable, so you can also contribute to the project by joining to the advisory team or giving feedback through user voice here.  

Posted by cibrax
Filed under: , , ,

Faye is a simple Http Pub/Sub server initially implemented by John Coglan in Ruby, and also later ported by himself to Node.js. The version for Node.js implements the Bayeux protocol, which at first glace, many of us known as http long polling.

This project just represents another alternative to Socket.IO, which also works for client applications that are not necessarily implemented within a web browser.  As many http pub/sub engines out there, Faye also uses the idea of channels for routing messages, and it ships with two message repositories out of the box, a repository that runs in memory and a repository that stores the messages in REDIS.

On other hand, we have “IISNode”, one the coolest projects announced by Microsoft to host Node.js applications in IIS. One of the things you can do with IISNode is to run websites implemented with express or connect, and Faye can also be attached to an application implemented with connect, so we can this use this common denominator to mount a Faye server with IISNode.

This is also relatively attractive if you want to run your own pub/sub server in Windows Azure using IISNode as it was announced today

The code for the Faye server looks as follow (server.js),

var faye = require('faye'),
       connect = require('connect');
var server = connect.createServer(
    connect.staticCache()
);
  
var ROOT_ADDRESS = '/node/faye-node/myapp/';
 
server.use(ROOT_ADDRESS + 'static', connect.static(__dirname + '/static'));
server.use(ROOT_ADDRESS, function(req, res) {
  res.setHeader('Content-Type', 'text/html');
  res.end(process.env.PORT);
});
 
var bayeux = new faye.NodeAdapter({mount: ROOT_ADDRESS + 'faye', timeout: 45 });
 
bayeux.attach(server);
 
server.listen(process.env.PORT);

A few things to notice here,

  • The listen port is provided by IIS through the PORT environment variable.
  • The application is hosted in IIS under the virtual directory “node/faye-node”, and “myapp” is just a mapping I defined for the application using connect.
  • The Faye server is configured to listen to request messages on “node/faye-node/myapp/faye”

If you take a look at the web.config file for this application, the URL routing module is used to redirect all the traffic to “myapp” to this node application (server.js)

<configuration>
  <system.webServer>
 
    <!-- indicates that the hello.js file is a node.js application 
    to be handled by the iisnode module -->
 
    <handlers>
      <add name="iisnode" path="server.js" verb="*" modules="iisnode" />
    </handlers>
    
     <rewrite>
      <rules>
        <rule name="myapp">
          <match url="myapp/*" />
          <action type="Rewrite" url="server.js" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Once you have the server up and running, you can configure several clients to send or subscribe messages to/from the Faye server. This is how a client application implemented in Node.js looks like,

var faye = require('faye');
 
var client = new Faye.Client('http://localhost/node/faye-node/myapp/faye',{
     timeout: 120
 });
 
client.subscribe('/one', function(message) {
    console.log('something received: ' + message.result );
 });
 
var publication = client.publish('/one',{ result: 'other message from one'});
 
publication.callback(function(){
    console.log('message sent');    
    client.disconnect();
});
 
publication.errback(function(err){
    console.log(err);
});
 

As you can see, the complete URL is used on the client side to connect to the server. A client for Faye can also be implemented within a browser,

<html>
  <head>
    <script type="text/javascript" 
        src="http://localhost/node/faye-node/myapp/faye.js">
        </script>
    <script type="text/javascript" 
        src="http://localhost/node/faye-node/static/jquery.js">
        </script>
  </head>
  <body>
    <script type="text/javascript">
      
      var client = new Faye.Client('http://localhost/node/faye-node/myapp/faye',{
        timeout: 120
      });
      
      function publish() {
    var publication = client.publish('/one',{ result: 'message from one'});
        publication.callback(function(){
          alert('message sent');
        });
      }
    </script>
    <span onclick="publish();">Click me!</span>
    <h1>Home.html</h1>
    <ul class="container">
    </ul>
  </body>
</html>

Faye will provide an URL for downloading the client library in the browser (myapp/faye.js).

Download the complete sample from here

Posted by cibrax | 2 comment(s)
Filed under: , , ,

If you are using SQL Azure nowadays, you probably know that there are only a few alternatives for making backups of your existing data.

  • You can use SQL Azure Data Sync, which provides bi-directional data synchronization and data management capabilities allowing data to be easily shared across SQL Azure databases within multiple data centers. This implies you need at least one additional database for backing up your data, and SQL Azure databases are not necessarily cheap to keep them around without any functional use.
  • You can use third party tools like the ones offered by Cerebrata or RedGate to synchronize SQL Azure databases with On-Premises databases or dump your data to files

Or you can use Hgdbackup, an OS alternative started by Bertrand Le Roy that uses the SQL BCP command line tool to persist your database data into text-based files.  As this was exactly what I was needing for an Azure project, I decided to contribute some code to that tool for storing the backup files to the Blob Storage in Azure. Therefore, you can now specify in the tool the Azure storage account you want to use to store your backup files, or restore your database from. 

The tool uses the raw REST API for the Blob Storage service so the Azure SDK or the binaries included on it are not required. This means the tool is very simple to distribute or run in a server with minimal requisites.

The following examples illustrates how you can run the tool for making a new backup or restore an existing database.

Backup Example

Hgdbackup.exe /S:tcp:YOUR_Server.database.windows.net /D:YOUR_DB /U:YOUR_USER /P:YOUR_PASSWORD /A:YOUR_BLOB_ACCOUNT /K:YOUR_BLOB_KEY /T:"Server={0},1433;Database={1};User Id={2};Password={3};Trusted_Connection=False;Encrypt=True;"

Restore Example

Hgdrestore.exe /S:.\SQLExpress /D:YOUR_DB  /C:YOUR_BLOB_CONTAINER /A:YOUR_BLOB_ACCOUNT /K:YOUR_BLOB_KEY

The backup tool supports an additional argument “C:” for passing the container where you want to store the text files with the data. If you don’t provide a container name, the tool will generate a new container for you.

The good thing about this tool is that it is an open source initiative so you are free to contribute, give feedback or improve it as I did with this support for the blob storage.

Posted by cibrax
Filed under: , ,

We have been working a lot lately with PowerShell as part of our star product at Tellago Studios, “Moesion”. One of the main features we provide in Moesion is the ability to execute PowerShell commands remotely in a given server using a web mobile interface (You can read more in my previous post about Moesion).

One of the things we realized in all this time is that PowerShell lacks of a central repository where IT guys or we, the developers, can easily grab and reuse commands.  All the commands or modules are basically spread across multiple places or websites, like personal blogs, TechNet or CodePlex projects to name a few making the search of them very hard. You are usually limited to use your favorite search engine and copy what you find. In addition, there is not an easy way to reuse, extend or version these commands, which also limits any contribution that you could make to the community. 

My friend Jose wrote a great post the other day about the importance of reusing PowerShell modules, and what is the mechanism to reuse them. Jose, however, based his post in a custom implementation using a GIT repository for storing the modules.

We have NuGet in the .NET platform for sharing and reusing existing libraries or code, so why can’t just leverage it for reusing PowerShell modules as well ?. Some teams in Microsoft are using NuGet for distributing libraries and binaries so it would be a great thing for all of us if they also distribute the scripting interfaces in PowerShell using NuGet. This applies to the .NET OS community as well.

In fact, it looks like Andrew Nurse had the same idea and implemented a project for this in BitBucket, PsGet.

Posted by cibrax
Filed under: , ,
More Posts « Previous page - Next page »