Jorge Ramon

  • Home
  • New Here?
  • Articles
    • All
    • Sencha Touch
    • jQuery Mobile
    • ExtJS
  • Books
  • About

How to Seed Users and Roles in an ASP.NET MVC Application

November 9, 2015 1 Comment

This is a quick tip for those of you working on .NET web applications. In this article I will show you how to pre-populate an ASP.NET MVC web application with initial user accounts and roles. This is helpful in web apps that use their own membership database to store individual user accounts.

4

I learned this trick from an article I found on the internet years ago. I would love to give credit to the original author, but I don’t keep the link to the article.

Let’s get started.

Continue Reading →

Tagged With: .Net Tutorial 1 Comment

Sencha Touch 2 Models – hasMany Associations, C# Example

September 18, 2012 4 Comments

In this tutorial you will learn how to use the hasMany association, a feature of Sencha Touch models that allows you to connect two models in a one-to-many relationship. The model configs you will learn about in this post are the following:

  • hasMany
  • belongsTo

The back-end code for this tutorial is in C#. I also published a version of this Sencha Touch tutorial using PHP.

Let’s create a simple Sencha Touch application with the following files:

In the model/Hotel.js file, you will define a Hotel model like so:

Ext.define('App.model.Hotel', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            { name: 'id', type: 'int' },
            { name: 'name', type: 'string' },
            { name: 'address', type: 'string' },
            { name: 'status', type: 'int' }
        ],
        hasMany: {
            model: 'App.model.Room',
            name:'rooms'
        }
    }
});

Continue Reading →

Tagged With: .Net Tutorial, Sencha Touch Tutorial 4 Comments

ExtJS with ASP.NET MVC: Session Timeout Notifications

March 27, 2011 3 Comments

In this article I will explain one approach you can take when you need to handle session timeouts in your ExtJS + ASP.NET MVC applications. The goal of this approach is simply to alert the user when her server session has timed out.

These are the basic steps you will follow when implementing this approach:

  1. Before an AJAX request is handled on the server side, determine if the session timed out. If the session timed out, respond with a “session timed out” code. If it didn’t, proceed to handle the AJAX request.
  2. Intercept the AJAX responses on the client side. When the “session timed out” code is detected, inform the user.

Intercepting ExtJS AJAX requests on the server

Suppose you have a FeesBilled and AccountsReceivable ExtJS data stores like so:

App.DetailsStore = function (config) {
    var config = config || {};
    Ext.applyIf(config, {
        fields: ['Id', 'Name', 'Amount'],
        root: 'records',
        totalProperty: 'total',
        remoteSort: true,
        sortInfo: {field:'name',direction:'asc'}
    });
    App.DetailsStore.superclass.constructor.call(this, config);
};
Ext.extend(App.DetailsStore, Ext.data.JsonStore);

var feesBilledStore = new FeesStore ({
    url: 'accounting/feesbilled
});
var accountsReceivableStore = new FeesStore ({
    url: 'accounting/accountsreceivable
});

Requests sent from these stores will be handled by the following ASP.NET MVC action methods:

public ActionResult FeesBilled(int start = 0, int limit = 0, string sort = "name", string dir = "asc")
{
    EmployeeModel empl = Session["empl"] as EmployeeModel;
    return DL.GetFeesBilled(start, limit, sort, dir, empl);
}

public ActionResult AccountsReceivable(int start = 0, int limit = 0, string sort = "name", string dir = "asc")
{
    EmployeeModel empl = Session["empl"] as EmployeeModel;
    return DL.GetAccountsReceivable(start, limit, sort, dir, empl);
}

As you can see, these action methods need an EmployeeModel instance that is stored in a session variable. And you need to guarantee that the session exists and is valid before passing the EmployeeModel instance to the data access layer of the system.

 

Then, how do you determine if the user’s session has timed out before these requests are processed?

You can accomplish this in ASP.NET MVC with a custom action filter. Action filters are custom attributes that allow you to perform logic either before an action method is called, or after an action method runs.

This is an action filter you can use to check for session timeouts:

public class AjaxSessionExpiredFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext context = HttpContext.Current;
        // Check if session is supported.
        if (context.Session != null)
        {
            if (context.Session.IsNewSession)
            {
                // If this is a new session and an old session cookie exists, then old session timed out.
                string sessionCookie = context.Request.Headers["Cookie"];
                if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") > -1))
                {
                    context.Response.Write("error=sessiontimeout");
                    context.Response.End();
                }
            }
        }

        base.OnActionExecuting(filterContext);
    }
}

Notice that you need to override the filter’s OnActionExecuting method. This method is fired before the action method executes.

 

Armed with this custom action filter, you can simply decorate the controller methods like so:

[AjaxSessionExpiredFilter]
public ActionResult FeesBilled(int start = 0,
            int limit = 0, string sort = "name", string dir = "asc")
{
    EmployeeModel empl = Session["empl"] as EmployeeModel;

    return DL.GetFeesBilled(start, limit, sort, dir, empl);
}

[AjaxSessionExpiredFilter]
public ActionResult AccountsReceivable(int start = 0,
            int limit = 0, string sort = "name", string dir = "asc")
{
    EmployeeModel empl = Session["empl"] as EmployeeModel;

    return DL.GetAccountsReceivable(start, limit, sort, dir, empl);
}

After decorating the methods with the custom action filter, every time the methods are called and the session has timed out, the response generated will be “error:sessiontimeout”.

 

Your ExtJS application needs to catch and handle this response. Let’s see how it’s done.

Handling session timeout in ExtJS

In your ExtJS application, you can check for the session timeout code utilizing a handler function for the requestcomplete event of the Ext.Ajax class. As Ext.Ajax is a singleton, your requestcomplete handler will run for any AJAX requests that completed successfully.

A simplified version of the handler could look like this:

Ext.Ajax.on('requestcomplete', function (conn, response, options) {
    if (response.responseText.indexOf("error=sessiontimeout") > -1) {
        Ext.Msg.alert('Session Timeout', 'Your session has timed out. Please refresh this page to start a new session.');
    }
});

And that’s all it takes. Want to give it a try?

Tagged With: .Net Tutorial, ExtJS Tutorial 3 Comments

ExtJS with ASP.NET MVC: GridPanel Paging

March 20, 2011 4 Comments

In this article I describe one of my favorite approaches for implementing gridpanel dataset paging in ExtJS + ASP.NET MVC projects.

Assume you have a “feesBilledStore” JsonStore instance configured like so:

var FeesStore = function (config) {
    var config = config || {};
    Ext.applyIf(config, {
        fields: ['Id', 'Name', 'Amount'],
        root: 'records',
        totalProperty: 'total'
    });
    FeesStore.superclass.constructor.call(this, config);
};
Ext.extend(FeesStore, Ext.data.JsonStore);

var feesBilledStore = new FeesStore ({
	url: 'fees/feesbilled
});

How do you feed the feesBilledStore JsonStore from an ASP.NET MVC controller?

 

When you use paging with your ExtJS gridpanels, along with the paged results, you need to supply your data store the actual size of the recordset. This is the value used to calculate the number of pages available, which, among other things, is displayed in your paging toolbar.

In my ExtJS + ASP.NET MVC projects, I tend to connect the server-side models with the ExtJS gridpanels with the help of a class that I name PagedRecords:

public class PagedRecords
{
	public int TotalRecords { get; set; }
    public dynamic Records { get; set; }
}

PagedRecords nicely maps my data models to the gridpanel ExtJS views I use. The Records property will store the recordset’s page to be rendered by the gridpanel, and the TotalRecords property stores the actual size of the recordset.

 

When converted to Json, an instance of PagedRecords results in a javascript object that will provide the data and the recordset size needed by the ExtJS gridpanel and the pagingtoolbar bound to it.

Using the PagedRecords class, the MVC Contoller method that will feed my hypothetical feesBilledStore would look like this:

public ActionResult FeesBilled(int start = 0, int limit = 15) {

	PagedRecords result = DataRepository.GetFeesBilledPaged(start, limit);

	return Json(new { total = result.TotalRecords, records = result.Records }, JsonRequestBehavior.AllowGet);

}

And my data access routine would need to return an instance of PagedRecords like so:

public static PagedRecords GetFeesBilledPaged(int startRow, int pageSize)
{
	var totalRecords = db.GetFeesBilledCount();
	var fees = from f in db.GetFeesBilled()
		select new FeesBilledModel()
		{
			Id = (int)h.employee_id,
            Name = h.employee_name,
            Amount = (decimal)h.fees_billed
        };
    PagedRecords paged = new PagedRecords() { TotalRecords = totalRecords, Records = hours.Skip(startRow).Take(pageSize).ToList() };

    return paged;
}

What do you think?

Tagged With: .Net Tutorial, ExtJS Tutorial 4 Comments

  • 1
  • 2
  • Next Page »

Free Mobile User Interface Recipes Kit

Free Mobile User Interface Recipes Kit

Sign up to receive my posts via email and get a FREE Mobile User Interface Recipes Kit with mockups packages for three real-world mobile apps. You will save hours of design time when you use the kit to build your own apps.



I will never share your email address.

Get My Books

The beginner's guide to Sencha Touch apps
The beginner's guide to jQuery Mobile apps

Book: How to Build a jQuery Mobile Application

Topics

  • » jQuery Mobile Tutorials
  • » Sencha Touch Tutorials
  • » ExtJS Tutorials
  • » Books
  • » Tools
  • » .Net Tutorials
  • » BlackBerry Tutorials
  • » iOS Tutorials
  • » Node.js Tutorials
  • » Android Training
  • » BlackBerry Training
  • » iOS Training

Search

Contact Me

  •  Email: jorge[AT]jorgeramon.me
  •  Twitter: @MiamiCoder
  •  LinkedIn: Jorge Ramon


Don’t Miss the Free Updates

Receive free updates in your inbox.
Your address is safe with me.

Copyright © 2019 Jorge Ramon · The opinions expressed herein do not represent the views of my employers in any way · Log in