Sunday, 29 September 2013

Using jQuery Mobile Table Options With ASP.NET GridView

I think many of you are aware of the FriendlyUrls feature added to ASP.NET Web Forms 4.5. It is available by default with Visual Studio 2012 if you have installed Web Tools update 2012.2 or later and it is available by default in Visual Studio 2013 RC as well. FriendlyUrls makes URLs of the web forms application friendly and it enables the option of creating views for mobile devices as well. In the pages specific to mobile devices, we can use the front-end mobile frameworks like jQuery mobile or Sencha Touch.

The default ASP.NET Web Forms template contains an optimized master page for mobile view, Site.Mobile.Master. This will be the default master page for all mobile specific pages.

Using front-end frameworks with server control is a bit tricky, but it is possible to use. In this post, we will see the way to use jQuery mobile’s table options with ASP.NET GridView.

Let’s make the server control ready. In the mobile page, add a GridView and bind data to it. Following is the mark-up of the GridView and the Select method that binds data from Customers table of Northwind database:


<asp:GridView runat="server" ID="gvCustomers" SelectMethod="GetCustomers"></asp:GridView>

public IQueryable GetCustomers()
{
    NorthwindEntities ctx = new NorthwindEntities();
    return ctx.Customers.Take(10).Select(c => new { c.ContactName, c.CompanyName, c.City, c.Phone, c.Region });
}

I chose 5 properties to make the output simpler. The page should contain the view port metadata tag and the scripts and styles needed for jQuery mobile.
<meta name="viewport" content="width=device-width" />
<link href="Content/jquery.mobile.theme-1.3.2.min.css" rel="stylesheet" />
<link href="Content/jquery.mobile.structure-1.3.2.min.css" rel="stylesheet" />
<link href="Content/jquery.mobile-1.3.2.min.css" rel="stylesheet" />
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/jquery.mobile-1.3.2.js"></script>

The root div in the Site.Mobile has to be marked with data-role attribute to make jQuery mobile act on the content contained in the page.
<form id="form1" runat="server">
    <div data-role="page" id="home">
        <!-- Rest of the default mark-up -->
    </div>
</form>

Let’s make the GridView appear as the table in the demo on the jQuery Mobile site, so that the user will have an option to see some of the less necessary columns only when they are needed. To enable them, the GridView should be rendered as a table with thead and tbody. This can be done by setting the TableSelection property of the header row after data is bound to the GridView as shown below:
protected void gvCustomers_DataBound(object sender, EventArgs e)
{
    gvCustomers.HeaderRow.TableSection = TableRowSection.TableHeader;
}

To make the rendered table look like table in the demo on jQuery mobile site, following client properties have to be applied on the table:

  • Some CSS classes have to be applied on the table
  • data-role and data-mode attributes on the table
  • data-priority attribute on less important columns

These properties can be set in the DataBound event of the GridView. Add the following statements to the DataBound event of the GridView:

gvCustomers.CssClass = "ui-responsive table-stroke";
gvCustomers.Attributes.Add("data-role", "table");
gvCustomers.Attributes.Add("data-mode", "columntoggle");

var headerCells = gvCustomers.HeaderRow.Cells;
headerCells[3].Attributes.Add("data-priority", "2");
headerCells[4].Attributes.Add("data-priority", "2");

With this, we are done with applying the required settings. Load the page on a mobile emulator; it should look as shown below:




Happy coding!

Wednesday, 11 September 2013

A Better Way of Using ASP.NET SignalR With Angular JS

A few days back, I blogged on using SignalR and Angular JS together and on Implementing SignalR stock ticker sample using Angular JS(Part 1 and Part 2). In those posts, I have used the traditional call-back model to call the functions defined in controller to modify data whenever an update is received from the server.

One of the readers sent me feedback saying that we have a better way to use SignalR and Angular JS together. The way to go is using event methods defined on $rootscope object. This approach is based on publishing and subscribing events. As events can be published from anywhere and subscribed from anywhere, the source and destination will remain completely unaware of each other. Both of them have to depend on just one object, $rootScope.

Official documentation on scope contains details on each method defined on $rootScope. We will be using the following methods for publishing and subscribing the events:

  • $emit(name, args): Publishes an event with specified name with given arguments
  • $on(name, listener): Subscribes to an event with specified name. Listener is a function containing logic to be executed once the event has occurred

To manage SignalR’s client functionality, it is better to create a service, as services are singletons. There will be only one instance of the service in entire application. This behaviour of services makes it possible to have multiple SignalR client pages in the applications and they can be kept in sync without putting any extra amount of effort.

Let’s modify the example discussed in the post titled Hooking up ASP.NET SignalR with Angular JS to use event model. Server hub, references and structure of the HTML page remains the same as past. The only components to be modified are Controller and Service.

Service carries the responsibility to initialize a connection to the hub and call the SignalR’s server methods. Once a response is received from the server, we will broadcast an event from the service with data received.


app.service('signalRSvc', function ($, $rootScope) {
    var proxy = null;
 
    var initialize = function () {
        //Getting the connection object
        connection = $.hubConnection();
 
        //Creating proxy
        this.proxy = connection.createHubProxy('helloWorldHub');
 
        //Starting connection
        connection.start();
 
        //Publishing an event when server pushes a greeting message
        this.proxy.on('acceptGreet', function (message) {
            $rootScope.$emit("acceptGreet",message);
        });
    };
 
    var sendRequest = function () {
        //Invoking greetAll method defined in hub
        this.proxy.invoke('greetAll');
    };
 
    return {
        initialize: initialize,
        sendRequest: sendRequest
    }; 
});


To keep the things simple, I kept names of the server hub event and event rose using $emit the same. The names can be different. Let’s modify the controller to have a listener to the event raised by the service. Following is the implementation of the controller:

function SignalRAngularCtrl($scope, signalRSvc, $rootScope) {
    $scope.text = "";
 
    $scope.greetAll = function () {
        signalRSvc.sendRequest();
    }
 
    updateGreetingMessage = function (text) {
        $scope.text = text;
    }
 
    signalRSvc.initialize();
 
    //Updating greeting message after receiving a message through the event

    $scope.$parent.$on("acceptGreet", function (e,message) {
        $scope.$apply(function () {
            updateGreetingMessage(message)
        });
    });
}


Now open the modified page on multiple browsers and click the Greeting button randomly from all browsers. Messages printed on all browsers should be updated whenever the button is clicked. This behaviour is same as it was earlier. We just adopted a better approach to make it work.

Happy coding!

Sunday, 8 September 2013

Restricting Number of Suggestions in jQuery UI Auto Complete Using Underscore.js

jQuery UI’s autocomplete widget can be used with an array of objects or we can take complete control with by defining a function that emits the list of suggestions to be displayed. Restricting the count of suggestions to a given number is slightly tricky. There are several ways to skin this cat. In this post, we will see one of the ways to achieve the same using Underscore.js.

To make the number of suggestions configurable, a data- attribute can be used.

<input type="text" id="txtName" data-count="5" placeholder="Your name..." />

We need to define a source function to take control over suggestions to be displayed and filter data from the collection using underscore.js and value of the data-count attribute on the element. The source function should perform the following tasks:
  • Select a list of entries from the collection that contain the term entered using _.filter() function
  • Take first n(n being value of data-count attribute) entries from the filtered list using _.take() function
  • Pass the values selected in step 2 to response

var names=["Alex", "Andrew", "Andrea", "Anna", "Abbie", "Abraham", "Aisha", "Albert", "Albina", "Alisha", "Barbie", "Bailey", "Barton", "Bernardo", "Blaise", "Bobbie", "Blossom", "Brianna", "Buddy", "Byron", "Caesar", "Caleb", "Celicia", "Chalmer", "Chandra", "Cindi", "Clarence", "Codie", "Corey", "Cyrus"];
var textBox = $("#txtName");
textBox.autocomplete({
    minLength: 2,
    source: function(request, response){
        var filteredNames = _.take(_.filter(names, function(name){
            return name.toLowerCase().indexOf(request.term.toLowerCase()) != -1;
        }), textBox.data("count"));
        response(filteredNames);
    }
});

You can play with the sample on jsfiddle.


Happy coding!

Thursday, 5 September 2013

Exploring Web API OData Query Options

As I mentioned in the post on CRUD operations using Web API, OData has a lot of query options. The full listing of standard query options can be found on the official OData site. In this post, we will explore the query options supported by Web API and we will also see how to use these query options from .NET clients through LINQ queries.

Query support on Web API Data can be enabled in following two ways:

  • At the method level, by setting Queryable attribute on the Get method

    [Queryable]
    public IQueryable<Customer> Get()
    {
        .....
    }
  • When application starts, by calling EnableQuerySupport method on HttpConfiguration object

    GlobalConfiguration.Configuration.EnableQuerySupport();

To be able to explore more options, we will be using the Northwind database. Create an ADO.NET Entity Data model with following tables:

  • Customers
  • Orders
  • Employee

Let’s make these entities available to the Web API OData endpoint by adding them to an EDM model. Following statements accomplish this:


    var modelBuilder = new ODataConventionModelBuilder();
    modelBuilder.EntitySet<Customer>("Customers");
    modelBuilder.EntitySet<Order>("Orders");
    modelBuilder.EntitySet<Employees>("Employees");
    Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
    GlobalConfiguration.Configuration.Routes.MapODataRoute("ODataRoute", "odata", model);

Add a Web API controller named CustomersController and modify the code as:


public class CustomersController : ODataController
{
    NorthwindEntities context = new NorthwindEntities();

    public IQueryable<Customer> Get()
    {
        return context.Customers;
    }
}

Now we are all set to test the service. Run the project and change the URL on the browser to:


 localhost:<port-no>/odata

You should be able to see entries for each entity collection we added.



Now that the service is up and running, create a client project and add the service reference of the service just created (You may refer to my post on consuming OData from .NET clients post for setting up the client). Also, create a container object by passing URL of the Web API OData service.

Now that we have service and the client ready, let’s start exploring the different to query the service.

$filter:

All OData query options are query string based. $filter is the most basic and the most powerful of them. As the name suggests, $filter is used to select data out of a collection based on some conditions. The type conditions vary from simple equal to operator to string and date filtering operations.

As we already know, the following URL fetches details of all customers in the Northwind database:

    http://localhost:<port-no>/odata/Customers

Let’s add a condition to fetch details of customers with title Owner. Following URL gets the values for us:

    http://localhost:<port-no>/odata/Customers?$filter=ContactTitle eq 'Owner'

This filter can be applied from .NET client using the LINQ operator Where. Following is the query:


 var filteredCustomers = container.Customers.Where(c => c.ContactTitle == "Owner");

The above query is not fired in-memory. Instead, it generates the above URL by parsing the expressions passed into the LINQ operators. The generated URL can be viewed during debugging. Following screen-shot shows the URL generated by the above query:



As we see, it is same as the URL that we typed manually.

To select all customers with contact Ana at the beginning of their ContactName can be fetched using following URL:

 http://localhost:<port-no>/odata/Customers?$filter=startswith(ContactName,'Ana') eq true
The above query uses the OData function startswith() to compare initial letters of the field value. The corresponding LINQ query is:
    container.Customers.Where(c => c.ContactName.StartsWith("Ana"))

Similarly, endswith() can be used to compare suffix of a string. We can also check if a string is contained in a field using substringof() function.

 http://localhost:<port-no>/odata/Customers?$filter=substringof('ill',CompanyName)%20eq%20true

The corresponding LINQ query is:

    container.Customers.Where(c => c.CompanyName.Contains("ill"))

To get list of all customers with length of their names greater than 10 and less than 20, the URL is:
 http://localhost:<port-no>/odata/Customers?$filter=length(ContactName) gt 10 and length(ContactName) lt 20


You must have already guessed the LINQ query to achieve the same.

    container.Customers.Where(c => c.ContactName.Length > 10 && c.ContactName.Length < 20)

$filter supports querying based on numbers, dates and even checking types. You can get the full listing on the official site for OData.

$orderby:

Result can be ordered based on a field using $orderby operator. Syntax of specifying the operator is same as that of $filter operator. Following URL and the LINQ query fetch details of customers with names of the countries ordered in ascending order:

    http://localhost:<port-no>/odata/Customers?$orderby=Country 
    container.Customers.OrderBy(c => c.Country)

To make the order descending, we just need to specify the keyword desc at the end of the above URL.

$top and $skip

The server collections can be divided into pages from client using the $top and $skip operators. These operators are assigned with numbers that indicate the number of entries to be selected from the top or the number of entries to be skipped from the beginning of the collection.

Following URL and LINQ query select first 10 customers in the Customers table.


    http://localhost:<port-no>/odata/Customers?$top=10
    container.Customer.Take(10)

Syntax of using $skip is similar to that of $top, as $skip also expects a number to be passed in. Both $skip and $top can be used together to fetch data in several chunks. Following URL fetches 10 customers starting with index 40.

    http://localhost:<port-no>/odata/Customers?$skip=40&$top=10
    container.Customers.Skip(40).Take(10)

Paging can be forced from server side as well. If an entity set contains very huge amount of data, the requested client will have to wait for a long time to get the entire response from the server. This can be prevented by sending data in chunks from the server using server side paging. To get next set of values, the client has to send a new request to the server.

Server side paging:

Paging can be enabled on the server using PageSize property of the Queryable attribute. Following snippet applies a page size of 20 while returning a collection of customers:

    [Queryable(PageSize=20)]
    public IQueryable<Customer> Get()
    {
        return context.Customers;
    }
It can also be applied globally across all entity sets by setting the property to configuration object when the application starts, as follows:
    IActionFilter filter = new QueryableAttribute() { PageSize=20 };
    config.EnableQuerySupport(filter);
If you hit the URL to get all customers on your favorite browser after applying above changes, you will be able to see only 20 entries with a link to next set at the end of the result set, as shown in the following screen-shot:



As the URL is passed as a property of the JSON object, it can be easily extracted in any JavaScript client to send request for next set of values. But it is a bit tricky from .NET client. The collection LINQ query written on the client has to be converted to a DataServiceCollection to get the URL of the next request. It is shown below:


    var firstSetOfCustomers = new DataServiceCollection<Customer>(container.Customers);
    var nextSetOfCustomers = new DataServiceCollection<Customer>(container.Execute<Customer>(firstSetOfCustomers.Continuation.NextLinkUri));

Count of records on all pages can be obtained using the query option $inlinecount operator in the above query.
    http://localhost:<port-no>/odata/Customers?$inlinecount=allpages

    var firstSetOfCustomers = new DataServiceCollection<Customer>(container.Customers.IncludeTotalCount());

$expand:

ASP.NET Web API team added support of $expand and $select options in its latest release, which is version 5.0.0-rc1. It is built into Visual Studio 2013 Preview. In Visual Studio 2012, the NuGet package can be upgraded to the pre-release version.

$expand is used to include values of navigation properties of the queried entity set. The interesting part is the results of the navigation properties of the inner entity set can also be included in the result set. Following URL and LINQ query fetch details of Customers, their Orders and the details of the Employee who placed the Order.

    http://localhost:<port-no>/odata/Customers?$expand=Orders/Employee
    container.Customers.Expand("Orders/Employee");

The above query navigates till two levels down the entity set. Depth of the navigation can be controlled using the MaxExpansionDepth property on the Queryable attribute.
    [Queryable(MaxExpansionDepth=1)]
    public IQueryable<Customer> Get()
    {
        return context.Customers;
    }

This configuration can be applied on HttpConfiguration object when the application starts.

    IActionFilter filter = new QueryableAttribute() { MaxExpansionDepth=1 };
    config.EnableQuerySupport(filter);
After applying the above changes, the client cannot navigate to more than one level down the entity set.

$select:

A client can request for projected results based on its need. A list of properties to be fetched can be specified while querying the service to get only those properties. Following are a sample URL and the LINQ query:


    http://localhost:<port-no>/odata/Customers?$select=CustomerID,ContactName
    container.Customers.Select(c => new { ID = c.CustomerID, Name = c.ContactName });

Happy coding!