How to patch the Ajax Control Toolkit CalendarExtender to add Decade support and InitialView – Part 4

April 15, 2009

Missed the rest of the article? Click here for Part 1

Ok, so now we have a decade view. If you keep clicking on the title of the calendar, you’ll eventually get to decade view. Hopefully it works as good for you as it does for me.

Next step is to create an InitialView so that you can set the calendar to show the Decade when you first click the calendar image.

To add any class that you want to have access on both the server and the client, you need to add a class file to the Calendar folder. I simply right-clicked on the CalendarPosition.cs file, then clicked Copy. Then I Pasted the file into the Calendar folder, and renamed it “InitialView”.

Initial View cs file

Initial View cs file

Now we need an enumeration so that we can set the view.  Change the code in the file so that the class name is InitialView, and it contains Day, Month, Year and Decade, as follows:

//S2 - Add Initial View so that you can choose a starting view for your date selection. You might want to do this
//so that selection of the date is more efficient.</pre>
namespace AjaxControlToolkit
{
    /// <summary>
    /// The initial view of the calendar
    /// </summary>
    public enum InitialView
    {
        Day = 0,
        Month = 1,
        Year = 2,
        Decade = 3
    }
}
//E2

Again, we are really just copying the CalendarPosition enumeration. To get this to be recognised in javascript, copy the three code blocks that make up the client side javascript block for CalendarPosition, then modify the code to be consistent with the InitialView that we are trying to achieve.

Original code:

AjaxControlToolkit.CalendarPosition = function() {
    /// <summary>
    /// Position of the popup relative to the target control
    /// </summary>
    /// <field name="BottomLeft" type="Number" integer="true" />
    /// <field name="BottomRight" type="Number" integer="true" />
    /// <field name="TopLeft" type="Number" integer="true" />
    /// <field name="TopRight" type="Number" integer="true" />
    /// <field name="Right" type="Number" integer="true" />
    /// <field name="Left" type="Number" integer="true" />
    throw Error.invalidOperation();
}
AjaxControlToolkit.CalendarPosition.prototype = {
    BottomLeft: 0,
    BottomRight: 1,
    TopLeft: 2,
    TopRight: 3,
    Right: 4,
    Left: 5
}
AjaxControlToolkit.CalendarPosition.registerEnum('AjaxControlToolkit.CalendarPosition');

 Additional code, add at the bottom of the CalendarBehavior.js file just below the code for registering the CalendarPosition enum:

//S2 Initial View. This is the code that synchronises the server side enum with the client side enum
AjaxControlToolkit.InitialView = function() {
    /// <summary>
    /// View of the calendar opened when the user selects the calendar
    /// </summary>
    /// <field name="Day" type="Number" integer="true" />
    /// <field name="Month" type="Number" integer="true" />
    /// <field name="Year" type="Number" integer="true" />
    /// <field name="Decade" type="Number" integer="true" />
    throw Error.invalidOperation();
}
AjaxControlToolkit.InitialView.prototype = {
    Day: 0,
    Month: 1,
    Year: 2,
    Decade: 3
}
AjaxControlToolkit.InitialView.registerEnum('AjaxControlToolkit.InitialView');
//E2

Still in the CalendarBehavior.js file, scroll to the top. We need to declare the _initialView variable and set it’s initial default value. Find the code that initialises the popup position. This is how the default Calendar Position is set. It is also the variable that we are copying.

Original code:

this._popupPosition = AjaxControlToolkit.CalendarPosition.BottomLeft;

Modified code:

this._popupPosition = AjaxControlToolkit.CalendarPosition.BottomLeft;
//S2 - set the initial default in javascript
this._initialView = AjaxControlToolkit.InitialView.Day;
//E2

To be consistent with the other client script variables, we create getters and setters. Simply copy the ones for popupPosition:

Original code:

 get_popupPosition: function() {
   /// <value type="AjaxControlToolkit.CalendarPosition">
   /// Where the popup should be positioned relative to the target control.
   /// Can be BottomLeft (Default), BottomRight, TopLeft, TopRight.
   /// </value>
   return this._popupPosition;
},
set_popupPosition: function(value) {
  if (this._popupPosition != value) {
    this._popupPosition = value;
    this.raisePropertyChanged('popupPosition');
  }
},

 

Modified code:

 get_popupPosition: function() {
   /// <value type="AjaxControlToolkit.CalendarPosition">
   /// Where the popup should be positioned relative to the target control.
   /// Can be BottomLeft (Default), BottomRight, TopLeft, TopRight.
   /// </value>
   return this._popupPosition;
},
set_popupPosition: function(value) {
  if (this._popupPosition != value) {
    this._popupPosition = value;
    this.raisePropertyChanged('popupPosition');
  }
},
//S2 - set and get variables for javascript initialView, copied off first day of week
get_initialView: function() {
  /// <value type="AjaxControlToolkit.InitialView">
  /// The initial view of the calendar, day, month, year or decade
  /// </value>
  return this._initialView;
},
set_initialView: function(value) {
  if (this._initialView != value) {
     this._initialView = value;
     this.invalidate();
     this.raisePropertyChanged("initialView");
  }
},
//E2

The final bit of javascript code is where we switch between modes of the calendar. This occurs in the show function. Basically, when the calendar needs to show, it calls the method this._switchMonth(null, true); so that the correct month is selected in the calendar. I think we should leave this to do it’s work. Instead, I will use the internal function _switchMode to switch between the different calendar views.

Original code:

show: function() {
  /// <summary>
  /// Shows the calendar
  /// </summary>
 

  this._ensureCalendar();

  if (!this._isOpen) {

     var eventArgs = new Sys.CancelEventArgs();
     this.raiseShowing(eventArgs);
     if (eventArgs.get_cancel()) {
        return;
     }

     this._isOpen = true;
     this._switchMonth(null, true);
     this._popupBehavior.show();
     this.raiseShown();
   }
},

Modified code:

show: function() {
  /// <summary>
  /// Shows the calendar
  /// </summary>
 

  this._ensureCalendar();

  if (!this._isOpen) {

     var eventArgs = new Sys.CancelEventArgs();
     this.raiseShowing(eventArgs);
     if (eventArgs.get_cancel()) {
        return;
     }

     this._isOpen = true;
     this._switchMonth(null, true);
     //S2 - We've let the code create the calendar, now switch the calendar to the initial view that we want.
     //Note that we only want this to happen if a date has not already been selected, as they may want to
     //change only some of the date
     if (this._selectedDate == null) {
        var _initialView = this.get_initialView();
        switch (_initialView) {
           case AjaxControlToolkit.InitialView.Day:
              this._switchMode("days");
              break;
           case AjaxControlToolkit.InitialView.Month:
              this._switchMode("months");
              break;
           case AjaxControlToolkit.InitialView.Year:
              this._switchMode("years");
              break;
           case AjaxControlToolkit.InitialView.Decade:
              this._switchMode("decades");
              break;
         }
     }
     //E2           
     this._popupBehavior.show();
     this.raiseShown();
   }
},

Now the last thing we need to do is to ensure that there is a method of setting the InitialView on the calendar extender. This is done in the CalendarExtender.cs file.

Scroll down to the code that handles to PopupPosition property. Copy and Paste that, and rename CalendarPosition to InitialView, popupPosition to initialView (case sensitive) and set the default value to InitialView.Day. It should now look like the following:

 //S2 - This is how to get a variable from the server to the client.
[DefaultValue(InitialView.Day)]
[ExtenderControlProperty]
[ClientPropertyName("initialView")]
public virtual InitialView InitialView
{
  get { return GetPropertyValue("InitialView", InitialView.Day); }
  set { SetPropertyValue("InitialView", value); }
}
//E2

Add a text box to a page, attach a calendar extender, then add the attribute InitialView=”Decade” and when you click on the calendar, it will open in decade view. But it will only do this if there isn’t a date already selected. If there is a date already in the text box, then the calendar will open in Day view. This is by design.

Remember to update the assembly version. This is a custom variation to the AjaxControlToolkit, so we don’t want it pretending it’s the original. Under the properties folder in the AjaxControlToolkit project, double-click on the AssemblyInfo.cs file. Change the AssemblyVersion and AssemblyFileVersion attributes. I changed mine as follows:

[assembly: AssemblyVersion("3.0.20822.*")]
[assembly: AssemblyFileVersion("3.0.20822.0")]

And that’s pretty much it!

Got messed up somewhere along the line? Here’s the source code complete with patch so you can see where you went wrong. http://cid-5e237543fffb2891.skydrive.live.com/self.aspx/Public/DecadeView.zip


How to patch the Ajax Control Toolkit CalendarExtender to add Decade support and InitialView – Part 3

April 15, 2009

Now for the code. The vast majority of the code for the Calendar Extender control resides in the CalendarBehavior.js file. This is found in the AjaxControlToolkit source code under the Calendar folder.

To add support for decade, we need to copy the year code and modify it to look like a decade view. So the first thing to do is to find the variables that support year view and copy them.

Original code:

this._years = null;
this._yearsTable = null;
this._yearsBody = null;

Modified code:

this._years = null;
this._yearsTable = null;
this._yearsBody = null;
//S1 - Decades variables
this._decades = null;
this._decadesTable = null;
this._decadesBody = null;
//E1   

Note that I have tagged my code. If I modify code, I start the tag with an S. Where I finish the modification, I finish the tag with an E. In this case, it’s the first modification, so I have tagged it with S1 and E1.

Next, we need to add the modes to the calendar extender control. Go to the lines of code that show the modes.

Original code:

this._modes = {"days" : null, "months" : null, "years" : null};
this._modeOrder = {"days" : 0, "months" : 1, "years" : 2 };

Modified code:

//S1 - Decade view
//    this._modes = {"days" : null, "months" : null, "years" : null};
//    this._modeOrder = {"days" : 0, "months" : 1, "years" : 2 };
this._modes = { "days": null, "months": null, "years": null, "decades": null };
this._modeOrder = { "days": 0, "months": 1, "years": 2, "decades": 3 };
//E1

Note that I have commented out the original code, and added the new code. The new lines show “decades” and put the decades in correct mode order. Not too sure here, but I believe this is needed for animations. Note that commenting out the old code helps me in case I make a mistake and need to go back.  They can always be cleaned up later!

When the calendar is created, it creates the entire content of the calendar in a method called _buildBody. We need to add a method to the calendar extender to support the building of the Decade view. And we do this just below the line that builds the year view.

Original code:

_buildBody: function() {
 /// <summary>
 /// Builds the body region for the calendar
 /// </summary>
 this._body = $common.createElementFromTemplate({
   nodeName: "div",
   properties: { id: this.get_id() + "_body" },
   cssClasses: ["ajax__calendar_body"]
 }, this._popupDiv);
 this._buildDays();
 this._buildMonths();
 this._buildYears();
},

Modified code:

_buildBody: function() {
/// <summary>
/// Builds the body region for the calendar
/// </summary>
  this._body = $common.createElementFromTemplate({
    nodeName: "div",
    properties: { id: this.get_id() + "_body" },
    cssClasses: ["ajax__calendar_body"]
  }, this._popupDiv);
  this._buildDays();
  this._buildMonths();
  this._buildYears();
  //S1 - Create the html elements for the calendar decade view
  this._buildDecades();
  //E1       
},

Next we need to add in the function that actually builds the decades. To do this,  I have copied the method _buildYear and renamed it “_buildDecades”, then I have renamed all the references from “year” to “decade”. The display of a year is basically a table of cells. So I reuse this mechanism to build a table of decade cells. But decades are not the same as years – they take up more space than years. 2000-2009 is not the same as 2000. So after a fair bit of mucking around, I settled on a 3 by 3 grid of decades. Here’s the code:

New code :

_buildDecades: function() {
   /// <summary>
   /// Builds a "decades" view for the calendar
   /// </summary>

   var id = this.get_id();

   this._decades = $common.createElementFromTemplate({
      nodeName: "div",
      properties: { id: id + "_decades" },
      cssClasses: ["ajax__calendar_decades"],
      visible: false
   }, this._body);
   this._modes["decades"] = this._decades;

   this._decadesTable = $common.createElementFromTemplate({
      nodeName: "table",
      properties: {
        id: id + "_decadesTable",
        cellPadding: 0,
        cellSpacing: 0,
        border: 0,
        style: { margin: "auto" }
      }
   }, this._decades);

   this._decadesBody = $common.createElementFromTemplate({ nodeName: "tbody", properties: { id: id + "_decadesBody"} },    this._decadesTable);

   // this is the bit of code that determines the rows (i) and cells (j) that the decades go into.
   // so there are 9 cells.
   for (var i = 0; i < 3; i++) {
      var decadesRow = $common.createElementFromTemplate({ nodeName: "tr" }, this._decadesBody);
      for (var j = 0; j < 3; j++) {
         var decadeCell = $common.createElementFromTemplate({ nodeName: "td" }, decadesRow);
         var decadeDiv = $common.createElementFromTemplate({
            nodeName: "div",
            properties: {
               id: id + "_decade_" + i + "_" + j,
               mode: "decade",
               decade: ((i * 3) + j)
            },
            events: this._cell$delegates,
               cssClasses: &#91;"ajax__calendar_decade"&#93;
         }, decadeCell);
      }
   }
},
&#91;/sourcecode&#93;

Lesser known fact: you can actually add custom attributes to just about any tag. In this case, the tag inside the cell (td) is a div. Using Ajax methods, I simply add an id, mode and decade property. The decade property is used to determine the decade number (0 to 9) that will be used to calculate the decade to be displayed. The current decades to show is actually generated when you click on the Year Title bar. That bit of code is actually required in the _performLayout function. Before we move on, note that I have renamed the css classes to support decades. I will show you the css class mods later. For now, we'll move onto the _performLayout method.

Internally, the calendar extender calls the different views "modes". In the _performLayout function, it selects a mode based on the current visible date. Inside this function, there is a case statement. It is used to render the calendar modes.

Original (pseudo) code:

&#91;sourcecode language='javascript'&#93;
_performLayout: function() {
  /// <summmary>
  /// Updates the various views of the calendar to match the current selected and visible dates
  /// </summary>

//code to initialise the layout and get the current view

switch (this._mode) {
   case "days":
   //code to generate day view
   break;
   case "months":
   //code to generate month view

   break;
   case "years":
   //code to generate year view
   break;
}

//code to set the today bar

}

You’ll need to add a case statement for handling the decade view, as follows:

 Modified code:

 
//S1 – This code generates the decade values for the currently visible decade                         
   case “decades”:
   // the following line is where it rounds down to the start of the current decade
   var minDecade = (Math.floor(visibleDate.getFullYear() / 10 ) * 10 );
   for (var i = 0; i < this._decadesBody.rows.length; i++) {       var row = this._decadesBody.rows[i];       for (var j = 0; j < row.cells.length; j++) {          var cell = row.cells[j].firstChild;   // the following line calculates the decade for the 8 decades prior to the current decade (9 total)          cell.date = new Date(minDecade + ((cell.decade - 8 ) * 10 ), 0, 1, this._hourOffsetForDst);          if (cell.firstChild) {             cell.removeChild(cell.lastChild);          } else {             cell.appendChild(document.createElement("br"));          }          //the following line generates the decade text to be displayed in each cell.          var decadeString = (minDecade + ((cell.decade - 8 ) * 10 )).toString() + "-" + (minDecade + ((cell.decade - 8 ) * 10 ) + 9 ).toString();          cell.appendChild(document.createTextNode(decadeString));          $common.removeCssClasses(cell.parentNode, ["ajax__calendar_other", "ajax__calendar_active"]);          Sys.UI.DomElement.addCssClass(cell.parentNode, this._getCssClass(cell.date, 'y'));       }    }    if (this._title.firstChild) {       this._title.removeChild(this._title.firstChild);    }    //the following sets the text for the title bar. Note that we are at the top level, so clicking on this bar does nothing    this._title.appendChild(document.createTextNode(( minDecade - 80 ).toString() + "-" + ( minDecade + 9 ).toString()));    this._title.date = visibleDate;    //I have enabled the previous and next arrows. They skip 90 years each way - the start of the next batch of decades    this._prevArrow.date = new Date(minDecade - 90, 0, 1, this._hourOffsetForDst);    this._nextArrow.date = new Date(minDecade + 90, 0, 1, this._hourOffsetForDst);    break; //E1 [/sourcecode] Note comments inline. The next bit of code occurs when you click on a cell. When clicking on the cell, it changes the mode to a different mode (if it's year or month) or if it's the day view, it sets the date, closes the calendar and  inserts the formatted date into the text box. Go to the _cell_onclick function, find the following code: [sourcecode language='javascript']  case "title":   switch (this._mode) {      case "days": this._switchMode("months"); break;      case "months": this._switchMode("years"); break;   }   break; [/sourcecode]  We add in the new mode: Modified code: [sourcecode language='javascript']  case "title":   switch (this._mode) {      case "days": this._switchMode("months"); break;      case "months": this._switchMode("years"); break; //S1 - enable the clicking on the title to change to a decade view      case "years": this._switchMode("decades"); break; //E1                      }   break; [/sourcecode] All internal methods, of course, nothing special here. Now, in the same function, _cell_onclick, find the case "year" code block. I copied this block and made modifications to support decade. Original code: [sourcecode language='javascript']  case "year":   if (target.date.getFullYear() != visibleDate.getFullYear()) {      this._visibleDate = target.date;   }   this._switchMode("months");   break; [/sourcecode] Modified code: [sourcecode language='javascript']  case "year":    if (target.date.getFullYear() != visibleDate.getFullYear()) {       this._visibleDate = target.date;    }    this._switchMode("months");    break; //S1 - On clicking a decade, switch to year view        case "decade":   if (target.date.getFullYear() != visibleDate.getFullYear()) {     this._visibleDate = target.date;   }   this._switchMode("years");   break; //E1                        [/sourcecode] Note how similar the year switching code is to the decade switching code . Final code changes are to clean up the generated decade table, cells and divs. Go to the "dispose" function and copy the code that cleans up the year code. Rename all references from "year" to "decade". Original code: [sourcecode language='javascript']  if (this._yearsBody) {   for (var i = 0; i < this._yearsBody.rows.length; i++) {      var row = this._yearsBody.rows[i];      for (var j = 0; j < row.cells.length; j++) {         $common.removeHandlers(row.cells[j].firstChild, this._cell$delegates);      }   }   this._yearsBody = null; } [/sourcecode] Modified code: [sourcecode language='javascript']  if (this._yearsBody) {   for (var i = 0; i < this._yearsBody.rows.length; i++) {      var row = this._yearsBody.rows[i];      for (var j = 0; j < row.cells.length; j++) {         $common.removeHandlers(row.cells[j].firstChild, this._cell$delegates);      }   }   this._yearsBody = null; } //S1 - Clean up decade variables          if (this._decadesBody) {   for (var i = 0; i < this._decadesBody.rows.length; i++) {     var row = this._decadesBody.rows[i];     for (var j = 0; j < row.cells.length; j++) {       $common.removeHandlers(row.cells[j].firstChild, this._cell$delegates);     }   }   this._decadesBody = null; } //E1        [/sourcecode] Note how similar the year dispose code is to the decade dispose code. Finally, you need to add css styles to the calendar to support decades. This is found in the Calendar.css file. After a little bit of tinkering with the styles using IE Dev Toolbar, I settled on the following additional styles, which you can simply add to the bottom of the file. [sourcecode language='css']  /*S1*/ .ajax__calendar_decade {height:44px;width:55px;text-align:center;cursor:pointer;overflow:hidden;} .ajax__calendar .ajax__calendar_decade {border:1px solid #ffffff;} .ajax__calendar .ajax__calendar_active .ajax__calendar_decade {background-color:#edf9ff;border-color:#0066cc;color:#0066cc;} .ajax__calendar .ajax__calendar_other .ajax__calendar_decade {background-color:#ffffff;border-color:#ffffff;color:#646464;} .ajax__calendar .ajax__calendar_hover .ajax__calendar_decade {background-color:#edf9ff;border-color:#daf2fc;color:#0066cc;} /*E1*/ [/sourcecode] And that's it, you now have a decade view! Click for Part 4 >>


How to patch the Ajax Control Toolkit CalendarExtender to add Decade support and InitialView – Part 2

April 15, 2009

In my previous article, I explain a problem with the current Ajax Control Toolkit Calendar Extender control when selecting birthdates – it simply takes too many clicks of the mouse. In this article, I explain my solution to this problem.

Firstly, I introduce the decade view. This allows the user to select from one of 9 decades displayed, as follows:

Calendar Extender Decade View

Calendar Extender Decade View

To get here, you simply click on the Title bar in the Year view:

Year View title click

Year View title click

Ok, so that allows you to remove 3 clicks, but it adds 1 click. But what if you were able to open the calendar in decade view?

Then you would simply select the decade,

Calendar Extender Decade View

Calendar Extender Decade View

then the Year,

Calendar Extender 70s View

Calendar Extender 70s View

then the Month

Calendar Extender 1970 Month View

Calendar Extender 1970 Month View

and finally the Day.

 

Calendar Extender May 1970 Day View

Calendar Extender May 1970 Day View

Bingo, 4 clicks!

Click for Part 3 >>


How to patch the Ajax Control Toolkit CalendarExtender to add Decade support and InitialView – Part 1

April 15, 2009

This is an educational article intended to show how to enhance the publicly available Ajax Control Toolkit Calendar Extender control.  All code here is added to a fresh download of the Ajax Control Toolkit. All code here is provided under the Microsoft Public Licence.

You can download the code for the latest version (20820) of the Ajax Control Toolkit from here: http://www.codeplex.com/AjaxControlToolkit

The licence is available here: http://ajaxcontroltoolkit.codeplex.com/license

In this case, I am intending to improve the usability of birthdate selection.

Currently, when the user wants to enter a birthdate into the text box attached to the Calendar Extender control, they click in the text box, or click on the calendar image next to the text box. The calendar extender control then pops up a Day view, as follows:

Calendar Extender Day View

Calendar Extender Day View

But we want a birthdate, so you don’t want to select a day here as it will potentially be from the wrong month or year, so what you do to select a different month is to click on the Title bar. That’s the bit that shows “April, 2009”. The calender extender control then pops up the Month view, as follows:

Calendar Extender Month View

Calendar Extender Month View

Next, you want the year, so you click on the Title bar again. That now shows “2009”. The calendar extender control then pops up the Year view, as follows:

Calendar Extender Year View

Calendar Extender Year View

Ok, so say we want 26 May 1970. We now need to choose a different decade. But clicking on the title doesn’t allow you to select a new decade. Instead, you need to use the arrows to go forward or backwards between decades. So you would click the left arrow in the top left corner 3 times to get to the decade that you want, the 1970s, as follows:

Calendar Extender 1970-1979 year view

Calendar Extender 1970-1979 year view

Then you need to click on the year you want, 1970. On selection, it switches back to the month view. You click the month that you want, May, then it switches to the Day view. You can then select the day that you want, 26. On selecting this, the calendar closes, and the text box is populated with 26/05/1970 (or whatever your date format is for the selected region and setting in the calendar extender). That’s a lot of work to select a birthdate.

That’s a total of 9 mouse clicks. Using this innovation, I have managed to get this down to 4 mouse clicks.

Click here for Part 2 >>