Wednesday, November 20, 2013

Working with Sencha EXTJS and WCF Service (Fetch Data)

JavaScript frameworks are the next future in application development. They provide a very effective, fast and modern way to develop and maintain the web application which gives it a desktop application look and feel.

Sencha EXTJS is one of the many available such frameworks.

I'm into MS technologies mainly ASP.NET.
Following is a basic example of how to connect to WCF services using EXTJS into ASP.NET application.

On WCF service project -

Create a WCF service which returns a list of users to the consumer (If you are looking for the EXTJS with WCF solution then I think I dont need to tel how to create a WCF service :))

The most important thing to do at WCF side -

Add following code in the global.asax of WCF solution -

  protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

This code is required to handle request with uri having additional params.

The Store   
Ext.define('My.store.Users', {
    extend: 'Ext.data.Store',
    model: 'AM.model.User',
    autoLoad: true,
    proxy: {
        type: 'ajax',       
            url: 'http://localhost/EXTJSService/RestService.svc/getUsers',
        reader: {
            type: 'json',
            root: 'GetUsers'
        }
    }
});

Here url is the path of your WCF service, in this example its hosted on the same machine, localhost.

root is the root element if the resultant JSON data (in most of the examples you will find it "d:")

View -
Ext.define('My.view.user.List', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.userlist',
    title: 'All Users',
    store: 'Users',
    initComponent: function () {
        this.columns = [
            { header: 'ID', dataIndex: 'ID', flex: 1 },
            { header: 'Name', dataIndex: 'FirstName', flex: 1 },
            { header: 'Email', dataIndex: 'Email', flex: 1 }
        ];
        this.callParent(arguments);
    }
});

Important things to note is the mapping of fields in the grid, these should map to the field names in the JSON data.

Hope you find it useful.
Enjoy....