Mobile Zone is brought to you in partnership with:

Jorge is the author of three software development books: "Building a Sencha Touch Application", "How to Build a jQuery Mobile Application", and the "Ext JS 3.0 Cookbook". He runs a software development and developer education shop that focuses on mobile, web and desktop technologies. Jorge is a DZone MVB and is not an employee of DZone and has posted 52 posts at DZone. You can read more from them at their website. View Full User Profile

Sencha Touch Store Server-Side Sorting

05.01.2014
| 5376 views |
  • submit to reddit

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.

Published at DZone with permission of Jorge Ramon, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)