Sencha Touch Store Server-Side Sorting

In this article you are going to learn how to perform server-side sorting of the records in a Sencha Touch Store using a .Net backend. These are the topics that the tutorial covers:

  • Using a Sencha Touch Store’s sorters config
  • Using the Store’s remoteSort config
  • How a Sencha Touch Store tells the server endpoint to sort its data
  • How a .Net endpoint sorts data and sends it to a Sencha Touch Store

Creating the Sample App

The app we will use as a testbed is almost an exact copy of the one we used in the Sencha Touch Stores client-side sort tutorial I published recently.

You can use any version of Visual Studio to create your project. Once you create a Visual Studio Project for the app, make sure the app has the following directories:

Sencha Touch Store sort on server example

Now we need to include the Sencha Touch libraries in the index.html. My file looks like the screenshot below. Make sure that your file is pointing to the directory where you placed your copies of the Sencha Touch libraries.

Creating the Model

Next we need to create a Sencha Touch Model for the records that we will place in the Store. We will create a Product model to represent some fictitious products. In the Model directory, create the Product.js file and type the following model definition:

Ext.define('App.model.Product', {
    extend: 'Ext.data.Model',
    config: {
        idProperty: 'productCode',
        fields: [
            { name: 'productCode', type: 'string' },
            { name: 'productName', type: 'string' },
            { name: 'productLine', type: 'string' }
        ]
    }
});

Let’s add model to the models config of the app in the app.js file.

Ext.application({
    name: 'App',
    models: ['Product'],
    launch: function () {
 
    }
});

Creating the Store

We will also create the ProductsRemote.js file in the Store directory. This is the definition of the store:

Ext.define('App.store.ProductsRemote', {
    extend: 'Ext.data.Store',
    config: {
        model: 'App.model.Product',
        autoSync: false,
        proxy: {
            type: 'ajax',
            api: {
                read: '../../services/collectibles.ashx'
            },
            reader: {
                rootProperty:'products'
            }
        },
        sorters: [{
            property: 'productCode',
            direction: 'ASC'
        }],
        remoteSort:true
    }
});

Pay attention to the remoteSort config. This config defines if the sort will be performed on the client or deferred to the server. This config’s value is false by default. We are setting it to true so the Store will delegate the sorting to the server.

The Store will talk to the server through its proxy. We declared a proxy that points to the services/collectibles.ashx .Net handler, which we will create next.

Let’s not forget to declare the Store in the stores config of the app:

Ext.application({
    name: 'App',
    models: ['Product'],
    stores: ['ProductsRemote'],
    launch: function () {
 
    }
});

A Server-Side Handler to Send Data to a Sencha Touch Store

We will write this handler in C#. Let’s create a services directory in the app, and then add a generic handler called Collectibles.ashx to the directory. The handler should look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace STSort.services
{
    /// <summary>
    /// Summary description for Collectibles
    /// </summary>
    public class Collectibles : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Note the reference to the Newtonsoft.Json namespace. This is provided be the Json.NET library, which we need to add as a reference to the Visual Studio project:

Sencha Touch Store server side sort project

We will leave the handler empty for the time being so we can create a few model classes that will help us send sorted data to the Sencha Touch app.

The Server-Side Product Model

The first server-side model that we need the equivalent of the Product model in the Sencha Touch app. Let’s add a Product.cs file in the services directory, and type the following code in the file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace STSort.services
{
    public class Product
    {
        [JsonProperty(PropertyName = "productCode")]
        public string ProductCode { get; set; }

         [JsonProperty(PropertyName = "productName")]
        public string ProductName { get; set; }

         [JsonProperty(PropertyName = "productLine")]
        public string ProductLine { get; set; }
    }
}

Similar to the client-side Product model we defined in the model/Product.js file, the server-side Product Class has the ProductCode, ProductName and ProductLine properties.

We decorated each property with the JsonProperty attribute provided by the Json.Net library. This attribute allows us to change the names of the Class’s properties when they are serialized to Json. In this case we want each serialized property’s name to match the name of its equivalent property in the Product model of the Sencha Touch app. For example, ProductName becomes productName when serialized to Json.

The ProductsResult Model

When you send data to a Sencha Touch store through its data reader, you need to use an object with at least two properties – a “success” property that tells the Store whether the request to the server was successful, and a property that contains an array of records with the data for the Store. The next model we will create will help us do just that. It will contain a list with the records to be sent to the ProductsRemote Store, and a boolean Success property so we can tell the Store that its request was processed without issues.

In the services directory, create the ProductsResult.cs file and type the following class definition:

public class ProductsResult
{
    [JsonProperty(PropertyName = "success")]
    public bool Success { get; set; }

    [JsonProperty(PropertyName = "products")]
    public List<product> Products { get; set; }
}

When serialized to Json, an instance of the ProductResult class will become a string with a format similar to the sample below, which is a format that the Store’s data reader can understand:

{"success":true,"products":[{"productCode":"S18_1097","productName":"1940 Ford Pickup Truck","productLine":"Trucks and Buses"},{"productCode":"S10_1949","productName":"1952 Alpine Renault 1300","productLine":"Classic Cars"},{"productCode":"S12_4473","productName":"1957 Chevy Pickup","productLine":"Trucks and Buses"}]}

The Sorter Model

The third model that we need will help us extract the sort parameters sent by the ProductsRemote Store from the http request. It is critical that you understand how to do this, because this is how the Sencha Touch Store tells the server endpoint what type of sorting it needs.

The sort parameters sent by the Store define the data model’s properties that the Store’s data need to be sorted by, and the sort direction for each model property. Note that I am saying “properties” instead of “property” because, as you already know, you can sort a Sencha Touch Store by multiple model properties.

Let’s create the Sorter.cs file in the services directory. The Sorter Class will look like this:

public class Sorter
{
    [JsonProperty(PropertyName = "property")]
    public string Property { get; set; }

    [JsonProperty(PropertyName = "direction")]

    public string Direction { get; set; }
}

When we create an instance of the Sorter class, the value of the Property property is the name of a data model’s property that we want to sort by. The value of the Direction property defines whether we want to sort ascending of descending. Here is an example so it is easier for you to understand:

Sorter s = new Sorter() 
{
	Property = "ProductCode",
	Direction = "ASC"
};

At this point we have three server-side helper Classes that will allow us to send sorted data to the ProductsRemote Store in the Sencha Touch app. Let’s see how the sorting takes place.

Creating Dummy Records for the Sencha Touch Store

Back in the Collectibles.ashx handler, the first step we will take is to create a products list with a few dummy products that we will send to the Sencha Touch app:

public void ProcessRequest(HttpContext context)
{
    // Create a few dummy products.
    var products = new List</product><product>()
    {
        new Product() {
            ProductCode = "S10_1678",
            ProductName = "1969 Harley Davidson Ultimate Chopper",
            ProductLine = "Motorcycles"
        },
        new Product() {
            ProductCode = "S10_1949",
            ProductName = "1952 Alpine Renault 1300",
            ProductLine = "Classic Cars"
        },
        new Product() {
            ProductCode = "S10_2016",
            ProductName = "1996 Moto Guzzi 1100i",
            ProductLine = "Motorcycles"
        },
        new Product() {
            ProductCode = "S10_4698",
            ProductName = "2003 Harley-Davidson Eagle Drag Bike",
            ProductLine = "Motorcycles"
        },
        new Product() {
            ProductCode = "S12_1666",
            ProductName = "1958 Setra Bus",
            ProductLine = "Trucks and Buses"
        },
        new Product() {
            ProductCode = "S10_4757",
            ProductName = "1972 Alfa Romeo GTA",
            ProductLine = "Classic Cars"
        },
        new Product() {
            ProductCode = "S12_4473",
            ProductName = "1957 Chevy Pickup",
            ProductLine = "Trucks and Buses"
        },
        new Product() {
            ProductCode = "S18_1097",
            ProductName = "1940 Ford Pickup Truck",
            ProductLine = "Trucks and Buses"
        }
    };
}

In a real-world app you will likely retrieve these products from a database. I am hard-coding the list in order to keep this tutorial short.

Capturing the Sort Parameters Sent by the Sencha Touch Store to the Server

This is probably the most important part of this tutorial. After creating the products list, we need to find out if the ProductsRemote Store in the Sencha Touch app needs these products sorted in any particular way. We can do this by checking if the query string of the request contains the “sort” key.

The sort query string parameter is sent by the Store’s proxy on behalf of the Store when we define a sorters config, or when we call any of the sort methods we are already familiar with. We are going to capture this parameter using the following code:

public void ProcessRequest(HttpContext context)
{
    // Create a few dummy products.
    // (Omitted for brevity)

    Sorter[] sorters = null;
    string sortersJson = context.Request.QueryString["sort"];

    if (sortersJson != null)
    {
        sorters = JsonConvert.DeserializeObject<sorter []>(sortersJson);
    }
}

The value of the sort parameter is a Json representation of the sorters object in use by the Store. This object can contain one ore more model properties to sort by. In the code above we de-serialize this object it into the sorters array, which ends up containing one ore more instances of the Sorter Class that we created a few minutes ago.

Having captured the sorting information sent by the Sencha Touch Store, we can go ahead and sort the data models that wee will send to the Store.

Performing the Sever-Side Sort for the Sencha Touch Store

Remember that Sencha Touch Stores can perform multiple sorts, therefore we need to loop through the sorters array like so:

public void ProcessRequest(HttpContext context)
{
    // Create a few dummy products. (Omitted for brevity)

    // Capture sort parameters sent by the Sencha Touch Store (Omitted for brevity)
    

    if (sorters.Length > 0)
    {
        foreach (Sorter sorter in sorters)
        {
            switch (sorter.Property)
            {
                case "productCode":
                    if (sorter.Direction.ToUpper() == "ASC")
                    {
                        products = products.OrderBy(p => p.ProductCode).ToList();
                    }
                    else
                    {
                        products = products.OrderByDescending(p => p.ProductCode).ToList();
                    }
                    break;
                case "productName":
                    if (sorter.Direction.ToUpper() == "ASC")
                    {
                        products = products.OrderBy(p => p.ProductName).ToList();
                    }
                    else
                    {
                        products = products.OrderByDescending(p => p.ProductName).ToList();
                    }
                    break;
                case "productLine":
                    if (sorter.Direction.ToUpper() == "ASC")
                    {
                        products = products.OrderBy(p => p.ProductLine).ToList();
                    }
                    else
                    {
                        products = products.OrderByDescending(p => p.ProductLine).ToList();
                    }
                    break;
                default:
                    break;
            }
        }
    }
}

For each sorter in the sorters array, we are inspecting the value of the Property and Direction properties so we can sort as desired. Sorting in .Net is a simple process using Linq’s OrderBy and OrderByDescending methods.

Sending Sorted Data to the Sencha Touch Store

We can send the sorted data to the Sencha Touch Store with a few lines of code:

public void ProcessRequest(HttpContext context)
{
    // Create a few dummy products. (Omitted for brevity)

    // Capture sort parameters sent by the Sencha Touch Store (Omitted for brevity)
    
    // Perform the sort (Omitted for brevity)

    var result = new ProductsResult()
    {
        Success = true,
        Products = products
    };
    context.Response.ContentType = "application/json";
    context.Response.Write(JsonConvert.SerializeObject(result));
}

Here’s where the ProducsResult Class becomes helpful. To send the sorted products list to the Sencha Touch app, we create an instance of the ProductsResult Class, set its Success property to true, and load the sorted products list into the Products property. Finally, we Json-serialize the ProductsResult instance and send it to the app using the Response.Write method.

And that is what it takes to do Sencha Touch Store server-side sorting. As you have seen, the only thing you need to do inside the Sencha Touch app is set the Store’s remoteSort config to true. The action occurs on the server, where you need to capture the sort parameters sent by the Store and sort the Store’s data before sending it to the app.

If you run the app in Google Chrome and open the developer Console, you should be able to see the log generated by the code:

Sencha Touch Store server side sort example

Download the Source Code

Download from GitHub: Sencha Touch Store Server Side Sort by MiamiCoder

Are You Getting Started with Mobile Web Apps?

If you are just getting started with mobile web development, MiamiCoder’s Sencha Touch and jQuery Mobile books will teach you, step by step, how to create Sencha Touch and jQuery Mobile applications. If you like to learn by doing, these books are ideal for you.

Want to learn more?

Sign up for MiamiCoder’s Newsletter and get free articles and news:



MiamiCoder will never sell your email address.