Sencha Touch 2 Models – hasMany Associations, C# Example

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'
        }
    }
});

[Read more...]

Ext JS with ASP.NET MVC: Session Timeout Notifications

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?

Ext JS with ASP.NET MVC: GridPanel Paging

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?

Ext JS With ASP.NET MVC Sample

This is a simple example of how you can use Ext JS and ASP.NET MVC together. The scenario is the same I have used in my previous Ext JS with PHP articles: I am going to display a number of fictitious categories using an Ext JS combo box. In this case, the combo box items’ data – the categories – will be served by an ASP.NET MVC application.

The MVC application

When I create the ASP.NET MVC application, Visual Studio builds a default folder structure where the main components of the application are distributed like this:

  • The Controllers folder is where you put Controller classes that handle URL requests
  • The Models folder will contain classes that represent and manipulate data
  • Views is the folder where you put UI template files that are responsible for rendering output
  • Scripts is where you put JavaScript library files and scripts
  • Content is where you put CSS and image files, and other non-dynamic/non-JavaScript content
  • App_Data is where you store data files you want to read/write

Large applications will likely use multiple Visual Studio projects, but I will stick to this default structure in order to keep the example simple.

The View

In a model-view-controller scenario the View renders entities from the Model into a form suitable for interaction. The View in this example is the html page containing the Categories combo box.

I called this page combo.html, and the Ext JS components I use are a ComboBox and a JsonStore:

Ext.onReady(function() {

    var categoriesStore = new Ext.data.JsonStore({
        url: 'http://localhost/MvcApp/Categories',
        root: 'Categories',
        fields: ['Id', 'Name']
    });

    var combo = new Ext.form.ComboBox({
        store: categoriesStore,
        displayField: 'Name',
        valueField: 'Id',
        typeAhead: true,
        mode: 'remote',
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a category...',
        selectOnFocus: true,
        applyTo: 'categories-combo'
    });
});

The Controller

To adhere to the default url routing rules in ASP.NET MVC, the Controller is named CategoriesController. This will permit that requests to the  http://localhost/MvcApp/Categories url in the view (combo.html) get routed to my Controller.

CategoriesController will handle the View requests and will ask the Model to produce the needed data:

public JsonResult Index() {

    CategoriesContainer container = CategoriesDataContext.GetCategories();

    return  this.Json(container);

}

When a request is made to the http://localhost/MvcApp/Categories url, the Index() method will be executed. Note that the return value of Index() is of type JsonResult and not ActionResult. This indicates that the method returns JSON-encoded data. The encoding is acomplished with the call to Controller.Json() .

CategoriesContainer and CategoriesDataContext are part of the Model. Let’s now take a look at them.

Building the Model

The term “model” refers to the objects that represent the data of the application, as well as the corresponding domain logic with the business rules and validation. CategoriesContainer is  a Class that exposes an array of Category objects:

public class CategoriesContainer
{
    public Category[] Categories { get; set; }
}

A key point here is that when serialized to JSON, an instance of CategoriesContainer will have the signature the View’s JsonStore is expecting.

CategoriesDataContext creates the categories data. In a real-world application this would likely be more involved than simply hard-coding the data. :-)

public class CategoriesDataContext
{
    public static CategoriesContainer GetCategories() {
        Category[] categoriesArray = new Category[10];
        for (int i = 0; i < 10; i++) {
            Category category = new Category { Id = i, Name = "Category " + i.ToString() };
            categoriesArray[i] = category;
        }
        CategoriesContainer container = new CategoriesContainer();
        container.Categories = categoriesArray;
        return container;
    }
}

And last, the definition of a category can be something as simple as this Category Class:

public class Category
{
    public int Id {get;set;}
    public string Name {get;set;}
}

Downloads

Download the full sample: ExtJS_With_ASP_MVC.zip

How to Spy On a Windows Program: Tracking Main Window Activation

In this article I will walk you through the creation of a sample program that, each time I use any application on my pc, will record the application name, window title and time. While I do this, I will touch on techniques that, used for evil in spyware, are also applied with noble goals in areas like time tracking, application monitoring and computer-aided learning.

Practical information about this subject is hard to find. So, if you have ever been curious about how spyware programs work, how you can keep tabs on what a user does on a computer or how applications behave, read along.

Windows Architecture

To understand how you can “spy” on a running Windows program,  you first need to be familiar with the concept of event-driven applications.

Unlike applications that make function calls to obtain user input, Windows-based applications are event-driven. This simply means that they wait for the system to pass input to them.

The system passes all input for an application – for example, when the user types, moves the mouse, or clicks a control such as a scroll bar – to the various windows in the application. This input is passed in the form of messages. Besides the system, other applications can also generate windows messages.

If we could somehow inspect this message traffic, then we would have a way to know what it is that the system or other applications are asking any application to do. This is where you can put Windows Hooks to good use.

Windows Hooks

The MSDN documentation defines a hook as a point in the system message-handling mechanism where an application can install a subroutine to monitor the message traffic in the system and process certain types of messages before they reach the target window procedure.

There are different types of hooks, each providing access to different aspects of the system’s message handling mechanism. For example, keyboard hooks allow you to monitor keyboard messages (keyloggers make use this type of hook), mouse hooks allow you to monitor mouse messages and WindProc hooks allow you to monitor all messages processed by the Window Procedure, the message handling function in any window.

Armed with this knowledge, let’s go back to my sample program.

Tracking Window Activation

We know that when an application window becomes active, it is because the system sent it a message asking it to do so. Then, a way to track application usage is to install a system-wide hook that will inspect the messages the system sends to any application asking it to activate its main window.

To write my sample program I used C#, and to save time used an excellent Windows Hooks library written by Chris Wilson. In my sample program this is what I do:

  1. Install a global Shell hook. This type of hook allows me to intercept the messages sent by the system when a top-level window is activated.
  2. Upon intercepting a message indicating a top-level window activation, I record the time, the name of the application the window belongs to and the text displayed in the window’s title bar.

Sounds good? Let’s look at each step in detail.

The sample program is a Windows Form application with just one form.

Thanks to the excellent hooks library I am using (you can read more about it at The Code Project), all I need to do to be able to intercept top-level windows activation messages is subscribe to the WindowActivated event and install my shell hook. I subscribe to the event right inside the constructor for my only form.

public Form1()
{
    InitializeComponent();
    // Instantiate our GlobalHooks object
    hooks = new GlobalHooks(this.Handle);
    hooks.Shell.WindowActivated +=
        new GlobalHooks.WindowEventHandler(hooks_ShellWindowActivated);
}

The hook is installed and uninstalled by pushing the “Start Monitoring” and “Stop Monitoring” buttons.

private void button1_Click(object sender, EventArgs e)
{
    hooks.Shell.Start();
}
private void button2_Click(object sender, EventArgs e)
{
    hooks.Shell.Stop();
}

Once the hook is installed, the message handling function of my form will start receiving not only messages directed to it, but also the messages intercepted by the shell hook.

Shell hooks intercept a variety of messages. Since I am just interested in top-level windows activations, I forward the messages to a utility function in the hooks library, which filters them and fires the WindowActivated event when the intercepted event indicates a top-level window activation.

protected override void WndProc(ref Message m)
{
    // Send the messages to the library for filtering.
    if (hooks != null)
    hooks.ProcessWindowMessage(ref m);
    base.WndProc(ref m);
}

Within the WindowActivated event handler, I use the window handle contained in the event arguments to lookup the application name and the window caption. Then I just display them in a listbox, together with the time the window was activated.

private void hooks_ShellWindowActivated(IntPtr Handle)
{
    // Insert information at the top of the list.
    listBox1.Items.Insert(0,"");
    listBox1.Items.Insert(0, "Window caption: " + GetWindowCaption(Handle));
    listBox1.Items.Insert(0,"Application: " + GetModuleName(Handle));
    listBox1.Items.Insert(0,string.Format("Time: {0}", DateTime.Now.ToLongTimeString()));
    listBox1.Items.Insert(0, "Window activation!");
}

You might have noticed how once you know when a top-level window was activated it becomes really easy to compute the time any application was actively used. I will leave the exercise to you.

Grabbing the window’s caption is accomplished with a call to the GetWindowText API function.

[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder title, int size);
private string GetWindowCaption(IntPtr Hwnd)
{
    // This function gets the name of a window from its handle
    StringBuilder caption = new StringBuilder(256);
    GetWindowText(Hwnd, caption, 256);
    return caption.ToString().Trim();
}

Obtaining the application’s executable name is a a little more involved, yet easy.

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd,
  out uint lpdwProcessId);
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess,
    [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
[DllImport("psapi.dll")]
public static extern uint GetModuleFileNameEx(IntPtr hProcess,
  IntPtr hModule, [Out] StringBuilder lpBaseName,
  [In] [MarshalAs(UnmanagedType.U4)] int nSize);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hHandle);
private string GetModuleName(IntPtr Hwnd)
{
    uint processId = 0;
    GetWindowThreadProcessId(Hwnd, out processId);
    IntPtr hProcess = OpenProcess(ProcessAccessFlags.QueryInformation |
      ProcessAccessFlags.VMRead, true, processId);
    StringBuilder FileName = new StringBuilder(256);
    GetModuleFileNameEx(hProcess, IntPtr.Zero, FileName, 256);
    CloseHandle(hProcess);
    return FileName.ToString().Trim();
}

And that is it. I hope you found the topic interesting and the sample useful. Here’s the source for the sample: HooksSample

How to Embed Images in the Body of an Email Message

Another very simple C# sample based on a mail merge application I have been working on. This time I would like to show you how to use the System.Net.Mail facilities to programmatically embed images in the html body of an email.

public static void SendMessage(string server,
    string from, string to, string cc, string bcc,
    string subject, string body, List<string> attachments,
    string[] embeddedFiles)
{
    MailMessage message = new MailMessage(from, to);
    message.Subject = subject;
    string[] ccArray = cc.Split(';');
    if (ccArray.Length > 0)
    {
        foreach (string address in ccArray)
        {
            if (address.Length > 0)
            {
                message.CC.Add(new MailAddress(address));
            }
        }
    }
    string[] bccArray = bcc.Split(';');
    if (bccArray.Length > 0)
    {
        foreach (string address in bccArray)
        {
            if (address.Length > 0)
            {
                message.Bcc.Add(new MailAddress(address));
            }
        }
    }
    message.IsBodyHtml = true;
    if (null != embeddedFiles && embeddedFiles.Length > 0)
    {
        foreach (string filePath in embeddedFiles)
        {
            string fileName = Path.GetFileName(filePath);
            body = body.Replace(fileName, "cid:" + fileName);
        }
        AlternateView view = AlternateView.CreateAlternateViewFromString(body,
            null,MediaTypeNames.Text.Html);
        foreach (string filePath in embeddedFiles) {
            LinkedResource res = new LinkedResource(filePath);
            res.ContentId = Path.GetFileName(filePath);
            view.LinkedResources.Add(res);
        }
        message.AlternateViews.Add(view);
    } else {
        message.Body = body;
    }
    foreach (string file in attachments) {
        Attachment data = new Attachment(file);
        message.Attachments.Add(data);
    }
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    client.Send(message);
}

The trick here consists in creating an AlternateView instance for the body of the email and adding the images to this view via LinkedResource instances. Also, note how the paths to the original images inside de html body are replaced with unique identifiers that map to their embedded siblings.

More details on this approach can be found here.

Programmatically Accessing Mail Merge Fields in MS Word Documents

I have been working on a mail merge application that will allow for sending messages from a desktop computer by connecting directly to an SMTP server and not using the installed email client.

Based on this application’s code, this simple C# example shows how to programmatically replace a mail merge field in a Microsoft Word document with a desired value.

using Word = Microsoft.Office.Interop.Word;
...
public static void ReplaceMailMergeField(string msWordFileName,
    string mailMergeFieldName, string mailMergeFieldDesiredValue)
{
    object docName = msWordFileName;
    object missing = Missing.Value;
    Word.MailMerge mailMerge;
    Word._Document doc;
    Word.Application app = new Word.Application();
    // Hide MS Word's window.
    app.Visible = false;
    doc = app.Documents.Open(ref docName,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing);
    mailMerge = doc.MailMerge;
    // Try to find the field name.
    foreach (Word.MailMergeField f in mailMerge.Fields)
    {
        // Assuming the field code is: MERGEFIELD  "mailMergeFieldName"
        if (f.Code.Text.IndexOf("MERGEFIELD  \"" + mailMergeFieldName +"\"") > -1)
        {
            f.Select();
           // Replace selected field with supplied value.
            app.Selection.TypeText(mailMergeFieldDesiredValue);
        }
    }
    // Save changes and close MS Word.
    object saveChanges = Word.WdSaveOptions.wdSaveChanges;
    doc.Close(ref saveChanges, ref missing, ref missing);
    app.Quit(ref missing, ref missing, ref missing);
}

I hope you find this sample helpful.