Silverlight 2 Page Switching

Silverlight 2 represents a giant leap forward for developers of Rich Internet Applications (RIAs); the ability for .NET developers to leverage their programming skills in the wide variety of languages supported by the .NET framework permits for a wide degree of flexibility in application development. However, as with all new techniques there are shortcomings and areas that need extra work from developers.  One area within Silverlight 2 that falls into this category is page switching.

Jesse Liberty has a great two part tutorial on switching pages effectively in Silverlight: Part 1, Part 2.  However, this method has a rather serious design flaw: it fails to reuse the interface when switching.  This means that if I have two pages with the same interface, I am essentially recreating the interface for each page.  While I can certainly encapsulate static portions in user controls, the fact remains that I am still reloading these each time.

Building on Jesse’s tutorial I took things one step further and allowed the user to Switch pages in content area similar to how things are handled with ASP .NET Master Pages.  This technique combines the effectiveness of Jesse’s switching method with a more modular design.  This technique, however, pales in comparison to the flexibility offered in the Silverlight 3 Navigation Framework, which should be used exclusively once available.

To begin you will at least four pages, as shown below:2009-06-23_1130

In this case we are using Page.xaml as the main page that will  host the others, thus we define a new instance of Page.xaml as the RootVisual in App.xaml.cs.  The Page.xaml XAML markup looks like this:

2009-06-23_1133

Notice the two areas I have marked:

  1: xmlns:local="clr-namespace:TransitionApplication"
  2: 
  3: <local:Switcher x:Name="Switcher" Height="110" Width="300"
  4:                 HorizontalAlignment="Center" VerticalAlignment="Center" />

In this code we are simply creating a reference back to our application and including a user control called Switcher into the application markup.  The code for switcher is rather unique as it does not contain any markup, this is intentional.  Basically we will use Switcher to load other pages into the given content area. The code-behind for Switcher looks like such:

   1:  public partial class Switcher : UserControl
   2:  {
   3:       public Switcher()
   4:       {
   5:           InitializeComponent();
   6:   
   7:           if (Content == null)
   8:           {
   9:                Content = new Page1();
  10:           }
  11:       }
  12:       
  13:       public void Navigate(UserControl ucControl)
  14:       {
  15:            Content = ucControl;
  16:       }
  17:  }

The purpose of this code is to provide a means for the parent page to navigate to new pages via the Navigate method.  By default we will load Page1 into the application when it is first started.

From this point, our event handlers in the main page will suffice to perform the switch, an example is provided below, this is from Page.xaml.cs:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

   1:  public partial class Page : UserControl
   2:  {
   3:       public Page()
   4:       {
   5:            InitializeComponent();
   6:       }
   7:   
   8:       private void Button1_Click(object sender, RoutedEventArgs e)
   9:       {
  10:            Switcher.Navigate(new Page1());
  11:       }
  12:   
  13:       private void Button2_Click(object sender, RoutedEventArgs e)
  14:       {
  15:            Switcher.Navigate(new Page2());
  16:       }
  17:  }

This is pretty simple, each button set the Content of the Switcher to the respective page.  Of course this is a simple example, but you can get an idea of how this could could work in a larger application.
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Fluent NHibernate and a New Project

This week marked the end of my stint on one of the biggest projects we have had in the last year.  Things went very well, as the remaining members of the team begin to move into the final beta phase, I am being reassigned as a billable consultant to a company in Holland, MI. The upside of this assignment is I get to work with PHP which is one of the first languages I did serious programming in and was my forte in college.  Getting the opportunity to work with it for the first time since I became strictly .NET is going to be fun, challenging, and exciting; its an opportunity that I am very much looking forward to.  The only downside is my current 10m commute to work now becomes an hour long commute as I must be onsite in Holland, but I think its well worth it.

One of the other happenings is I have finally started to take a serious looking into NHibernate as something that RCM may go to from our current open source custom framework (The Kinetic Framework).  Its part of the normal aging process for a framework.  NHibernate is highly touted and looks to be a good alternative to using the still not ready for prime time Entity Framework.  However, one of the long standing problems with NHibernate, is configuration and that really is true for most ORMs that exist today.  Microsoft has generally released good tools built into Visual Studio to aid programmers in configuring the ORM products it releases, this is not the case for NHibernate.  To counter this, Fluent NHibernate was created that allows you to “fluently” define mappings for entity objects.

The main advantage behind this notion of fluent programming is that we take procedures that normally are relegated to external programming and bring them under the control of the compiler, to allow for easier compile time checking.  An example of this is Microsoft LINQ – where developers are able to querying databases (for example) using standard type safe C# code as opposed to passing a string off to a black box (the database) and magically getting a rectangular result set.

This is the same idea with Fluent NHibernate which removes the XML configuratioin files and allows you to define this configuration using C#, below is an example:

   1:  public class SeriesMap : ClassMap
   2:  {
   3:       public SeriesMap()
   4:       {
   5:            Id(x => x.SeriesId);
   6:            Map(x => x.Name).WithLengthOf(100).Not.Nullable();
   7:            References(x => x.Studio).TheColumnNameIs("StudioId");
   8:            HasMany(x => x.Seasons).WithKeyColumn("SeasonId");
   9:            HasManyToMany(x => x.Genres)
  10:                .WithTableName("SeriesGenres")
  11:                .WithParentKeyColumn("SeriesId")
  12:                .WithChildKeyColumn("GenreId");
  13:       }
  14:   }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This being the mapping file, it would help to show you what the entity itself looks like:

   1:  public class Series
   2:  {
   3:       public virtual int SeriesId { get; set; }
   4:       public virtual string Name { get; set; }
   5:       public virtual IList Seasons { get; set; }
   6:       public virtual Studio Studio { get; set; }
   7:       public virtual IList Genres { get; set; }
   8:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Note that we define properties we want NHibernate to “fill” as virtual.  But take note of the correlation between the property names and the calls to properties in the mapping class.  The link below will provide more of a reference to the various calls available from the mapping class:

http://wiki.fluentnhibernate.org/show/HomePage & http://fluentnhibernate.org/

Once you have these classes in place you can use the standard NHibernate calls, either via the Criteria API or HQL (Hibernate Query Language) to extract your data. Also have a look at the Linq to NHibernate project. While it is still in its infancy stages it has great potential. I think Linq and NHibernate are actually made for each other as the DataContext pattern that Microsoft employs to track changes matches very well with the repository pattern employed by NHibernate, I look forward to some great stuff in the future from the meshing of these two technologies.

My first development experience with Surface

Microsoft has been generating a lot of buzz with Surface and this concept of Natural User Interface (NUI).  To briefly describe it, you have to think about to the way computer applications were originally designed; with command line interfaces (CLI).  Operating systems, such as Windows, brought the graphical user interface (GUI) to fame.  GUIs have been in heavy use for the better part of a two decades, however, with GUIs there is still a level of indirection between the user and the system.

Enter NUI, which is what Microsoft is billing as the next popular form of application interface design.  NUI strives to make interaction very similar to how we interact with everyday objects; this is the goal.

Recently I had a chance to actually use a Surface and then, at CodeMash, actually learn how existing WPF code can be easily transformed into Surface ready WPF.  After about a month of speaking with my contacts at Microsoft I was finally given the go ahead to download the exclusive Surface SDK and this evening I had the opportunity to program my first application and play with the simulator.

For myself not being graphically inclined, creating these ultra rich and vibrant applications is not easy; mostly from the graphical perspective as writing code does not change much.  But it really is enticing playing with the simulator and just seeing what is possible and thinking of the many uses for these types of applications.  So I wrote a simple application that utilizes the fly out keyboard with the Surface Textbox and then says ‘Hello’ to the person who enter’s their name.

Overall, developing on the Surface is very simple and straightforward.  Having existing knowledge of WPF will certainly help, but is not required, I will keep a running update of my continuing ventures in Surface.

Data Driven Programming with JQuery – Part 1

Data Driven programming is centered around the idea that data is central to user interaction and that an application should work only with data on the client side.  In this matter, the application adheres strictly to the less is more principle of Ajax development, in that we send only what the server needs and we return only what the client needs.  You can think of it as a push/pull model where our client will push only what it has to, to the server and then pull only what it ABSOLUTELY needs and display the information on the client.

Because of their strict adherence to the “less is more” principle of Ajax development as well as heavily relying on the use of JavaScript Object Notation (JSON) as a transmission protocol, data driven application ends to be much lighter and perform better over traditional web applications.

To actually properly develop these types of applications a framework, such as JQuery is essential, and also this methodology makes use of a number of features of JavaScript/JQuery.  JQuery selectors, in particular, are crucial to designing a lighter applications.  By having a thorough understanding of these selectors we are able to write less code which is more concise.  To briefly review the basic JQuery selectors allow us to select elements by ID, Class, and Tag Name, like such:

$("#someId");   // returns all elements with id="someId:
$(".someClass"); // returns all elements with class="someClass"
$("span");  // returns all  on the page
$("span input"); // returns all  within 
$("span > input"); // returns all  direct children of any 

These work very well as basic selectors and really become the foundation of any application, however, when you begin to get into cases where JQuery is working on a generated HTML layout, such as with ASP .NET you quickly find yourself having to make concessions on the cleanliness and conciseness of your HTML to assist JQuery with target elements whose ID is constantly changing.  For example, when I first started programming with JQuery I tried all sorts of ways to simplify targeting an element inside multiple Naming Containers.  Now I have a solid understanding Attribute and Filter based selection like such:

$("input[maxlength]");  // returns all  with attribute maxlength
$("input[id=someId]");  // returns all  with id="someId"
$("input[id$=someId");  // returns all  whose id ends with "someId"
$("input[id^=someId"); // returns all  whose id starts with "someId"
$("input[id*=someId"); // returns all  whose id contains "someId"

This type of selection works VERY well with ASP .NET due to the fact that the NamingContainer always place the ID the developer users at the end we can make good use of the $= syntax to select these elements.  The next set of selectors are Filters, which are based heavily on CSS3 and their primary use is to “filter” the set of all HTML elements on a page to a subset based on criteria and state.  The aim with filters in general is to give CSS developers more control over how elements look and act depending on their state.  Here are a few of them:

$(":text"); // returns all elements with type="text"
$(":visible"); // returns all elements not visible
$(":radio");  // returns all elements with type="radio"
$(":checked"); // returns all elements that are checked

Using JQuery selectors, in particular those outside the realm of the basic selectors, can greatly simplify the code you have to write and amplify the ways you have to target elements.  But why is understanding this so important:

When we design software we often talking about coupling and cohesion, mostly relating to class maintainability.  The same principles apply here.  Designs will change and, in the past, this often meant that JavaScript had to change with it.  However, with advanced frameworks like JQuery, it doesn’t have to as you can know properly separate your design from your interaction and thus allow changes to made that do not, or have little impact on your interaction layer.

So now that we have covered JQuery selectors there is one final piece of technology to talk about: JSON.  In the past, many developers used XML as the primary protocol for transmitting data back to the server, and while JavaScript is very good for parsing XML (mainly because its use in parsing the DOM), it is a very heavy protocol and contains a lot of bloat that we do not need.  JSON is a much simpler protocol that utilizes the serialization of JavaScript objects and transmits a string back to JavaScript which is then evaluated into a simple JavaScript objects.  Most of the JQuery widgets utilize JSON as the means for supplying the data we will display, because of its clean format and immense flexibility.

As an example of data driven programming I am going to show how one might construct a filterable grid that permits adding of new data.  Something to notice is the lack of use for hidden fields.  We store all state data using JavaScript closure, which I will explain later.  So the first part is to understand the nature of templates, since each row in the grid will share the same HTML, so here is what the main table could look like:

<table id="dataTable">
    <thead>
         <tr>
              <th></th>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Age</th>
         </tr>
    </thead>
    <tbody>
          <tr>
             <td class="rowIndex"></td>
             <td class="firstname"></td>
             <td class="lastname"></td>
             <td class="age"></td>             
          </tr>
    </tbody>
</table>

Because this is a table, to make it easier for us to target specific sections, I am using the

and

tags.  Our goal here is to take the rowTemplate HTML and store it somewhere that we can easily reuse it.  That place is the JQuery data cache, as shown below:

var $row = $("#dataTable > tbody");
if ($row.data("rowTemplate") == null) {
     $row.data("rowTemplate", $row.html());
}

Using JQuery, each element on the page can be given a data cache to store relevant data in. This data is stored in the JavaScript engine and is tracked by JQuery, you will find no reference to this data anywhere in the HTML source. When I say each element, I mean “each element”, thus you could store the original data presented in each row and read it without fear of the user modifying it with a tool such as FireBug and knowing the data is unique.  In this case I am storing the template HTML to the table because contextually it is the table body that cares about the HTML. In addition, we could be adding/removing rows, so storing the HTML on the rows themselves would not be a good idea.

In modern JavaScript it is considered bad practice to create lengthy amounts of HTML in JavaScript primarily for maintainability concerns as well as bloat and added coupling, remember we want to separate the HTML from the JavaScript as much as we can, that is why we are targeting a block of HTML and storing it with JavaScript.  This way the block can be updated without much change to

The follow code uses the ChainJS plugin to create a row based on the template for each item in the array – the template is defined by the HTML contained within the targeted block:

var $body = $("#dataTable > tbody");
$body.empty().html($body.data("rowTemplate"))
    .items( jsonResult ).chain(function() {
    var data = this.item();
});

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Note: I always precede any stored references to JQuery objects with a “$”, this is merely my convention, and is not anything official or leveraging anything special.

So what is happening here.  We make a reference to the tbody element with JQuery (this may already exist from when you checked the cache) and we call empty.  empty() will clear all the HTML from within the targeted node; we write our code this way to permit easy rebinding as we filtering or reorder the results.  Next we access the data cache for the “tbody” and place the HTML we stored earlier into the tbody, this is the beauty of this technique, we can now very easily and cleanly reuse this HTML as much as we like.

The next call starts the chaining process: we pass a variable (jsonResult) to the items functions that expects an array of JSON objects.  This prepares the set for display, and our call to chain finishes the process.  chain takes an optional anonymous function called a builder.  In many ways this builder is similar to the ItemDataBound and RowDataBound events, and they operate the same way.  Finally we make a call to item() within the builder to get a reference to the current item being bound; note also that $(this) would reference the current container (in this case

).

One of the interesting things about ChainJS is you do get some primitive automatic binding for your data based on class name; if you recall the HTML excerpt above:

<tbody>
          <tr>
             <td class="rowIndex"></td>
             <td class="firstname"></td>
             <td class="lastname"></td>
             <td class="age"></td>             
          </tr>
</tbody>

In this case, if the JSON objects in the set contained properties firstname, lastname, age then the values of these fields would be placed in the elements with the corresponding class names BEFORE the builder function is executed.  When the builder function executes it also contains the scope of variables inside and outside the function, thus the follow can be done:

var index = 0;
$row.empty().html($row.data("rowTemplate")).items(
    jsonResult ).chain(function() {

    var data = this.item();
    $(this).find(".rowIndex").text(index++);
});

In this case you see that even though index is declared outside the anonymous function we have the ability to see it and update it.

So this should give you an idea of what you can do understand the use of data centric principles as they relate to application design.  Remember, by leveraging new tools and the advanced features of modern frameworks like JQuery you can cut out working directly with HTML by utilizing templates and the JQuery data cache. Finally, you can add a layer of obfuscation to hide your codes purpose as well as the data from the transparent web.

In the next posting, well talk about how to utilize this strategy to clean-up event binding code as well as how the use of a service oriented approach and the related positives and negatives with that approach.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

CodeMash 2009 – In Review

I had the chance to attend CodeMash 2009 in Sandusky, OH at the Kalahari Resort.  Apart from being truly impressed with such a fantastic venue I had the chance to attend a number of remarkable sessions with some great speakers and enjoy great conversation with a number of influencers in the industry.

Among the topics I had the chance to take in were Microsoft Surface, Test Driven Development, Groovy and Grails, Soft Skills, and Water Sliding.  I mention the last one because the hotel has an awesome and tremendously large indoor waterpark and I had the chance with some downtime on Wednesday to take it all in, complete with at least 10 water slides, many of which are at least 5 stories tall. 

But back to technology, I really did enjoy the Surface presentation the most out of all the great presentations I attended.  It was interesting to see how the NUI style interface is developing and how computer system interfaces have continued to evolve ever closer to the ultimate goal of interacting like real objects, from old Command Line Interface systems, to some of the great Graphic User Interfaces of today, and to the Natural User Interfaces (NUI) of tomorrow. It was especially impressed with how easy it is to convert normal WPF XAML to Surface XAML, it really is no more then including a new namespace and preceding control names with “Surface”.  Special thanks to Jennifer Marsman (@jennifermarsman)

But perhaps the one session that opened my eyes the most was the very first session I attended in which we spoke about Test Driven development and the idea of exploring how a system COULD be laid out through mocking.  Basically starting with no real code, just interface definitions and gaining an understanding of how you could architect the system to determine what makes sense and what does not.  I really wish this was something that we could do in the future at RCM, I think it might help many design a more concise set of rules around their code and build the principles and habit essential to TDD.  Special thanks to Phil Japikse (@skimedic)

But for all the great sessions, CodeMash 2009 would not have been complete without the people and the many friends I have made in the tech community over the past year.  I got a chance to get a hands on lecture about Dependency Injection (using Ninject) from the master himself: Nate Kohari (@nkohari). I got to sit down and eat with some of the greatest minds and the most awesome people, such as Leon from Telligent (@fallenrogue) whom I shared JavaScript horror stories with and talked about Prototype and its future in the industry with the rapid adoption of JQuery.  Everyone was nice, even when I asked them to teach me to play poker, they were nice enough to not take all of my money or laugh when I had to play Rock Band on the easiest settings cause I am terrible, LOL.

In the end, it was a great time with great people and I learned a great deal.  I cant wait to go back to RCM and start to permeate these ideas and explore the new technologies and techniques that I have been exposed to.  And finally, I express my most sincerest and profound gratitude to the innumerable number of volunteers who made it so awesome.  Thank You and we will see you next year.

ASP .NET MVC Authentication Strategies

During the weekend I decided to try out a few strategies for protecting content against anonymous users.  During this I got the chance to explore creating custom attributes as well as gaining a better understanding of how routing really works. Ultimately I came up with a very decent solution but not the most desirable in my mind.

First Attempt: Custom Attribute
For the first attempt I took the standard ActionFilterAttribute and derived from it to create the following attribute class:

public class IsAuthenticatedAttribute : ActionFilterAttribute
{
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
          if (!HttpContext.Current.User.Identity.IsAuthenticated)
          {
               string redirectPath = FormsAuthentication.LoginUrl;
               HttpContext.Current.Response.Redirect(redirectPath, true);
          }
     }
}

This is a very rudimentary example of deriving from the ActionFilter attribute, I have seen examples where a custom attribute is used for logging and other reporting features. What happens in this example is we are override the OnActionExecuting method from the base class, so before the method this is decorating is executed this code will execute.  As you can see, if the user is not authenticated we redirect to the login url specified in the web.config.

This is not a bad strategy, and is the strategy I am using at present within my application. However, it was not the approach I was looking for, mainly because I still have to remember to put the attribute on the methods.  What I really would like is a single place that enforces the requirement that a user must be logged in for certain action to take place.  Furthermore, I would like to be able to split up a controller’s functionality for its admin and non admin actions.

Second Attempt: Routing

Based on my requirements, I naturally decided to look at routing as a means to prevent access to a particular path (aka namespace).  To begin, I created a directory under controllers (an Area as the term is known in the MVC world) called Admin and a controller called Series here to compliment the Series controller in the parent directory.

My first attempt was to institute a specific route for the admin actions and apply a constraint to the route that requires the user to be logged in, if they wish to access it, below is the following code I created:

routes.MapRoute(
     "Admin",
     "Admin/{controller}/{action}/{id}",
     new { controller = "Series", action = "Index", id = 0 },
     new {
          isLoggedIn = new AuthenticatedPathConstraint()
     },
     new string[] { 
          "AnimeManager.Controllers.Admin"
     }
);

The fourth parameter to MapRoute is a listing of the constraints to apply to this route.  Constraints are classes that implement IRouteConstraint and are passed in via an arbitrary property name in an anonymous class:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

public class AuthenticatedPathConstraint : IRouteConstraint
{
     #region IRouteConstraint Members
     public bool Match(HttpContextBase httpContext, Route route,
          string parameterName, RouteValueDictionary values,
          RouteDirection routeDirection)
     {
          if (routeDirection != RouteDirection.UrlGeneration)
          {
               if (!httpContext.User.Identity.IsAuthenticated)
               {
                    httpContext.Response.Redirect(
                         FormsAuthentication.LoginUrl);
                    return false;
                }
                return true;
          }
           return true;
     }
     #endregion
}

The next parameter is a set of strings representing namespaces to search. When the MVC framework looks for controllers it, by default, re-curses through the Controllers directory and makes a string list of all controller names. Thus if you have controllers with the same name, even in a different space, you will get a server error with respect to the inherent ambiguity created.  The strings provided to the fifth parameter of MapRoute serves to restrict the namespaces where MVC will look for potential controllers.

Now, I want to return to the constraint to explain a small, but critical, piece to this.  The comparison against the RouteDirection enum is very important.  Using ActionLink from the Html helper will invoke the routing mechanism as well as accessing a particular Url.  Because of the way we are doing the redirection we want to allow UrlGeneration to occur regardless of state.  To clarify, if we dont have this logic, when generating the link the page will never load and redirect endlessly.

To actually properly use this feature we need to use the GenerateLink Html Helper extension method as such:

<%= Html.GenerateLink(
     "test", "Admin", "Index", "Series",
     new RouteValueDictionary(new { id = 12 }), null)
%>

Using GenerateLink we can actually describe which route we want to use to generate the final link.  Remember anytime we call ActionLink we invoke the underlying routing system to generate the final URL, the same is true for GenerateLink, except it allows to tell what path we wish to use in the routing table.  Because of this, I decided to keep a Default route map and place all subsequent routes following and refer to them by name as needed.

Conclusion

Both strategies do a good job in minimizing the amount of code needed to protect functionality and consolidating the logic to determine authentication status to a single place.  I personally prefer the level of control I can get using Attributes over routing, granted the routing system still need a bit more work and research, I think it could be a very acceptable method in the future.

InfoPath 2007 Task Edit Form : Reading Responded Data

Recently, I got the chance to get my hands dirty with SharePoint Workflow.  It was quite the challenge, in particular because of some oddities that, given all products were Microsoft based, I had a hard time understanding why certain things were so out of sync.  One of these was the reason that the XML transmitted on the update operation from the InfoPath Task Edit form was not a document, but rather a fragment.  And why the SharePoint API was ill-equipped to handle this.  In the end, as with many things within our solution, this required custom code to appease both InfoPath and SharePoint.

Below is the code for completing this operation

   1:  XmlReaderSettings set = new XmlReaderSettings();
   2:  set.ConformanceLevel = ConformanceLevel.Fragment;
   3:   
   4:  using (XmlReader reader = XmlReader.Create(

5: new StringReader(afterProperties.ExtendedProperties["TakeOwnership"].ToString()), set)

   6:  )
   7:  {
   8:       while (reader.Read())
   9:       {
  10:            switch (reader.LocalName)
  11:            {
  12:                case REMAININGDAYS_LOCAL_NAME:
  13:                     if (reader.Read())
  14:                          if (int.TryParse(reader.Value, out daysRemaining))
  15:                               reader.Read();
  16:                     break;
  17:                case ISTAKEOWNERSHIP_LOCAL_NAME:
  18:                     if (reader.Read())
  19:                          if (bool.TryParse(reader.Value, out isTakeOwnership))
  20:                               reader.Read();
  21:                     break;
  22:                case CHANGEREMAININGWORKDAYS_LOCAL_NAME:
  23:                     if (reader.Read())
  24:                          if (int.TryParse(reader.Value, out changeRemainingDays))
  25:                               reader.Read();
  26:                     break;
  27:            }
  28:       }
  29:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

I choose this example because it also shows a means to parse out multiple values coming back.  The key to code is is Line #2.  We are telling the XMLReader that this XML is a fragment and not a whole document, which is the default expectation.  From there, knowing that the XML reader is a SAX based XML parser, we do reads checking various properties.  The logic is essentially as follows:

  • Perform a Read
  • Check the Local (tag) name
  • For a match, perform another read to get to the internal value
  • If the value is not empty and parses to what we expect, perform another read to get to the end element
  • When the loop comes back around, it will either be at the end of the document, or the next read will take it to the next element

This is not the most efficient means to read this XML, but it does get the job done.  If there is no value passed, the Try call will fail. The code will continue to iterate until it comes to a node with a name it is expecting, at which point it will again try to read the value, or the document ends and the loop terminates.

Dont call it Ajax, Please

Recently the computer industry, in particular, the web programming realm, has seen the rise of technology called Ajax. Its actually quite funny, because all this “new” technology is, is a combination of existing technologies that have been around since the late 90s. So to call Ajax new is technically incorrect, it is simply a new way to use these technologies. This is the same set of ideas that were behind DHTML that was used by websites in the mid 90s: use existing technologies together to create new effects on a website to enhance the user experience.

DHTML really is nothing but a combination of Javascript and CSS. Javascript doing what it does best – manipulate the DOM with CSS to generate effects that make the page more interactive to the user. But DHTML is, like Ajax, not a new technology, it was simply a new way to use existing technologies. Ajax stands for Asynchronous Javascript and XML, technologies that have been around since the early days of the Internet. Again, we are using Javascript to enact DOM changes on the client side to make the page appear to be more desktop like, which is the final goal for any webapps – to function on the web as a desktop app functions on the desktop.

What really bothers me is, people who call simple DOM manipulation, such as hiding elements on the fly with display: none and show elements with display = “”. This is not Ajax, this is Ajax:

// setup the request object – if we can
var request;
try {
request = new XMLHttpRequest();
}
catch (error) {
try {
request = new ActiveXObject( “Microsoft.XMLHTTP” );
} catch (error) {
return true;
}
}

// open the request and be prepared to handle the response, it exists
request.open( ‘get’, url, true );
request.onreadystatechange = function() {
if ( request.readyState == 1 ) {
simplexhr.loading();
}

if ( request.readyState == 4 ) {
simplexhr.complete();
if ( /200|304/.test( request.status ) ) {
simplexhr.retrieved( request );
}
else {
simplexhr.failed( request );
}
}
}

// send
request.send( null );
return false; // this ensures that the link is not followed ()

DOM manipulation has been something Javascript has been able to do for years, something it was designed to do. I even question half of Microsoft Ajax Atlas Controls as to whether they are really Ajax, but rather simple encapsulations of DOM manipulation with underlying JS logic. To me, Ajax is about going out to a server and getting XML to manipulate. Nowhere in the acronym do we talk about DOM manipulation as being part of it. This is basically DHTML not Ajax. DOM manipulation is certainly an integral part of the Ajax process as it allows you put the data into the page – but this is DOM Scripting not Ajax.

Just a rant and my two cents – have fun coding 🙂