muğla escort escort aydın escort çanakkale bayan escort balıkesir escort bayan tekirdağ gebze escort mersin escort bayan escort buca escort edirne

Blog Archive

Filter by: C#

Compilers are what make the software world function.  Really, where would we be without ‘em?  But compilers are like clans – you stick with the family.  Just like Romeo and Juliet, you can’t marry your enemies sister’s cousin, it just ends up in tragedy.  For the longest time, the .Net and C# world has been considered an “enterprise” thing, and by that we do not mean Captain Kirk and Spock:  .Net is for corporations, not the web.  It’s not Nodejs.  It’s slow.  It’s for the nerds who ain’t the cool nerds.  So take your compiler and stay on your side of the street.

Well, these days technology is a lot like the Berlin wall coming down, and like the union of the eastern and western European countries, the lines are blurred with static compiled languages of C# and Javascript.  You see, these days you compile C# code to Javascript.  In fact, a dirty secret is that you could do that for many years now.

DuoCode Is The New Kid On The Block

A new entry in this field is DuoCode.  From the site:

“DuoCode is an alternative compiler, powered by Microsoft® Roslyn, and integrated in Visual Studio.

It magically cross-compiles your C# 6.0 code into high-quality readable JavaScript code, enabling rapid development of web applications utilizing the extensive features of the C# language, the Visual Studio IDE, and the .NET Framework base class libraries.

Development in C# with Visual Studio brings great productivity wins, thanks to strong-typing, code completion, compile-time error checking, static analysis, code navigation and refactoring.

Develop HTML5 applications using strongly-typed and documented class-definitions of the entire DOM class library (including HTML, CSS, SVG and WebGL definitions).”

DuoCode works with Visual Studio and will compile assemblies from multiple projects to Javascript.  DuoCode claims to support LINQ, classes, Generics, lambda expressions, extension methods, and many features that are the strengths of C#.

The Question:  Should All C# Capabilities Be Ported To Javascript?

Does Javascript need type checking and casting?  Yes, no need to check that a int is not a string, but tying yourself to a compiler for Javascript is going to introduce a different type of workflow for your client side development.  Part of the refreshing aspects of Javscript is not having to compile constanctly.  ”You have to ‘build’ your website, hehe …” meant you have to sit and wait for Visual Studio to compile and deploy before you could debug.  One of the main reasons for adpating MVC and leaving ASP.Net Webforms behind was to get away from the stilted, awkward development process when you wanted to examine an issue with your app’s UX.  Compiling your Javascripts feels a bit like a step backwards.

That said, LINQ and lambda expressions are a really good thing.  They’re like power tools for your boilerplate code. Javascript, while having tools like underscoreJS and lodash, is still an open field in this respect.  That’s not to say that there are no alternatives and efforts to build those type of capabilities; indeed, there are hundreds of open source projects and other efforts to create better functionality, and with EM6 on the horizon things like iterators will become part of the new Javascript specification.

Quite Hemming and Hawing – Why Would I Need This?

Ok, under what circumstances will you need this capability, and more importantly, is the generated Javascript any good?  In response to the former query, you may have a series of objects that are tested, run on your server, and you want those to

also run in your UX.  Maybe you have a state machine and a process that you want to run on a mobile device and instead of transpiling it to Mono or Swift you want to go the HTML 5 route.  Or, perhaps you want to port a portion of your code base to nodeJS for message brokering.  This could help tremendously.

Yet lurking in the background here is this:  what does the ported Javascript look like, and if there are issues where do you go to fix them?  Are they a Javascript issue, or are the origins from C#, compounded by the code compiling to Javascript?

So what do you think?  

This is the fourth in a series of posts for ApprovaFlow, an alternative to Windows Workflow written in C# and JSON.Net.  Source code for this post is here.

[gigya src="" width="250" height="40" flashvars="" wmode="window"]

Last Time on ApprovaFlow

In the previous post we discussed how the Pipe and Filter pattern facilitated a robust mechanism for executing tasks prior and after a transition is completed by the workflow state machine.  This accomplished our third goal and to date we have completed:

Model a workflow in a clear format that is readable by both developer and business user. One set of verbiage for all parties.  Discussed in Simple Workflows With ApprovaFlow and Stateless.

•  Allow the state of a workflow to be peristed as an integer, string, etc.  Quickly fetch state of a workflow.  Discussed in Simple Workflows With ApprovaFlow and Stateless.

•  Create pre and post processing methods that can enforce enforce rules or carry out actions when completing a workflow task.  Discussed in ApprovaFlow:  Using the Pipe and Filter Pattern to Build a Workflow Processor

These goals remain:

• Introduce new functionality while isolating the impact of the new changes. New components should not break old ones

• Communicate to the client with a standard set of objects. In other words, your solution domain will not change how the user interface will gather data from the user.

• Use one. aspx page to processes user input for any type of workflow.

• Provide ability to roll your own customizations to the front end or backend of your application.

It’s the Small Changes After You Go Live That Upset You

The goal we’ll focus on next is Introduce new functionality while isolating the impact of the new changes. New components should not break old ones, as it’s the small upsetters that lurk around the corner that your users will think up that will keep you in the constant redeployment cycle. If we implement a plug-in system, then we can prevent the new features from breaking the current production system. Implementing these changes in isolation will lead to faster testing, validation and happier users.

We lucked out as our implementation of the Pipe And Filter pattern forced us to create objects with finite functionality.  If you recall each step in our workflow chain was implemented as a filter derived from FilterBase and this lends itself nicely to creating plug-ins.  The Pipe and Filter pattern forces us to have a filter for each unique action we wish to carry out.  To save data we have a SaveData filter, to validate that a user can supply a Trigger we have the ValidateUserTrigger, and so on.

“Great, Sensei, but aren’t we still constrained by the fact that we have to recompile and deploy any time we add new filters?  And, if I have to do that, why bother with the pattern in the first place?”

Well, we can easily reduce the need for re-deploying the application through the use of a plugin system where we read assemblies from a share and interrogate them by searching for a particular object type on application start up.  Each new feature will be a new filter.  This means you will be working with a small project that references ApprovaFlow to create new filters without disturbing the existing architecture.   We’ll also create a manifest of approved plug-ins so that we can control what is used and institute a little security since we wouldn’t want any plugin to be introduced surreptitiously.

Plug-in Implementation

The class FilterRegistry will perform the process of reading a share, fetching the object with type FilterBase, and register these components just like we do with our system components.  There are a few additions since the last version, as we now need to read and store the manifest for later comparison with the plug-ins.  The new method ReadManifest takes care of this new task:

<pre><code>private void ReadManifest()
string manifestSource = ConfigurationManager.AppSettings["ManifestSource"].ToString();

Enforce.That(string.IsNullOrEmpty(manifestSource) == false,
“FilterRegistry.ReadManifest – ManifestSource can not be null”);

var fileInfo = new FileInfo(manifestSource);

if (fileInfo.Exists == false)
throw new ApplicationException(“RequestPromotion.Configure – File not found”);

StreamReader sr = fileInfo.OpenText();
string json = sr.ReadToEnd();

this.approvedFilters = JsonConvert.DeserializeObject>>(json);


The manifest is merely a serialized list of FilterDefinitions. This is de-serialized into a list of approved filters.With the approved list the method LoadPlugin performs the action of reading the share and matching the FullName of the object type between the manifest entries and the methods in the assembly file:


public void LoadPlugIn(string source)
Enforce.That(string.IsNullOrEmpty(source) == false,
“PlugInLoader.Load – source can not be null”);

AppDomain appDomain = AppDomain.CurrentDomain;
var assembly = Assembly.LoadFrom(source);

var types = assembly.GetTypes().ToList();

types.ForEach(type =>
var registerFilterDef = new FilterDefinition();

// Is type from assembly registered?
registerFilterDef = this.approvedFilters.Where(app => app.TypeFullName == type.FullName)

if (registerFilterDef != null)
object obj = Activator.CreateInstance(type);
var filterDef = new FilterDefinition();
filterDef.Name = obj.ToString();
filterDef.FilterCategory = registerFilterDef.FilterCategory;
filterDef.FilterType = type;
filterDef.TypeFullName = type.FullName;
filterDef.Filter = AddCreateFilter(filterDef);



That’s it. We can now control what assemblies are included in our plug-in system.  Later we’ll create a tool that will help us create the manifest so we do not have to managed it by hand.

What We Can Do with this New Functionality

Let’s turn to our sample workflow to see what possibilities we can develop.  The test CanPromoteRedShirtOffLandingParty from the class WorkflowScenarios displays the capability of our workflow.  First lets review our workflow scenario.  We have created a workflow for the Starship Enterprise to allow members of a landing party to request to be left out of the mission.  Basically there is only one way to get out of landing party duty and that is if Kirk says it’s okay.  Here are the workflow’s State, Trigger and Target State combinations:

State Trigger Target State
RequestPromotionForm Complete FirstOfficerReview
FirstOfficerReview RequestInfo RequestPromotionForm
FirstOfficerReview Deny PromotionDenied
FirstOfficerReview Approve CaptainApproval
CaptainApproval OfficerJustify FirstOfficerReview
CaptainApproval Deny PromotionDenied
CaptainApproval Approve PromotedOffLandingParty

Recalling the plots from Star Trek, there were times that the medical officer could declare the commanding officer unfit for duty. Since the Enterprise was originally equipped with our workflow, we want to make just a small addition – not a modification – and give McCoy the ability to allow a red shirt to opt out of the landing party duty.

Here’s where our plugin system comes in handy.  Instead of adding more states and or branches to our workflow we’ll check for certain conditions when Kirk makes his decisions, and execute actions.  In order to help out McCoy the following filter is created in a separate project:


public class CaptainUnfitForCommandFilter : FilterBase
protected override Step Process(Step input)
if(input.CanProcess & input.State == “CaptainApproval”)
bool kirkInfected = (bool)input.Parameters["KirkInfected"];

if(kirkInfected & input.Answer == “Deny”)
input.Parameters.Add(“MedicalOverride”, true);
input.Parameters.Add(“StarfleetEmail”, true);
input.ErrorList.Add(“Medical Override of Command”);
input.CanProcess = false;

return input;


This plug-in is simple: check that the state is CaptainApproval and when the answer was “Deny” and Kirk has been infected, set the MedicalOverride flag and send Starfleet an email.

The class WorkflowScenarioTest.cs has the method CanAllowMcCoyToIssueUnfitForDuty() that demonstrates how the workflow will execute. We simply add the name of the plug-in to our list of post transition filters:

string postFilterNames = “MorePlugins.TransporterRepairFilter;Plugins.CaptainUnfitForCommandFilter;SaveDataFilter;”;

This portion of code uses the plug-in:


// Captain Kirt denies request, but McCoy issues unfit for command
parameters.Add(“KirkInfected”, true);

step.Answer = “Deny”;
step.AnsweredBy = “Kirk”;
step.Participants = “Kirk”;
step.State = newState;

processor = new WorkflowProcessor(step, filterRegistry, workflow);
newState = processor.ConfigurePipeline(preFilterNames, postFilterNames)

// Medical override issued and email to Starfleet generated
bool medicalOverride = (bool)parameters["MedicalOverride"];
bool emailSent = (bool)parameters["StarfleetEmail"];


Now you don’t have to hesitate with paranoia each time you need introduce a variation into your workflows. No more small upsetters lurking around the corner. Plus you can deliver these changes faster to your biggest fan, your customer. Source code is here.   Run through the tests and experiment for your self.

This is the second in a series of posts for ApprovaFlow, an alternative to Windows Workflow written in C# and JSON.Net. Source code for this post is here.

Last time we laid out out goals for a simple workflow engine, ApprovaFlow, with the following objectives:
• Model a workflow in a clear format that is readable by both developer and business user. One set of verbiage for all parties.
•. Allow the state of a workflow to be peristed as an integer, string. Quicky fetch state of a workflow.
•. Create pre and post nprocessing methods that can enforce enforce rules or carry out actions when completing a workflow task.
•. Introduce new functionality while isolating the impact of the new changes. New components should not break old ones
•.Communicate to the client with a standard set of objects. In other words, your solution domain will not change how the user interface will gather data from the user.
•. Use one. aspx page to processes user input for any type of workflow.
•. Provide ability to roll your own customizations to the front end or backend of your application.

The fulcrum point of all we have set out to do with ApprovaFlow is a state machine that will present a state and accept answers supplied by the users. One of Sensei’s misgivings about Windows Workflow is that it is such a behemoth when all you want to implement is a state machine.
Stateless, created Nicholas Blumhardt, is a shining example of adhering to the rule of “necessary and sufficient”. By using Generics Stateless allows you to create a state machine where the State and Trigger can be represented by an integer, string double, enum – say this sounds like it fulfills our goal:

•. Allow the state of a workflow to be persisted as an integer, string. Quicky fetch state of a workflow.
Stateless constructs a state machine with the following syntax:

var statemachine =
       new StateMachine(TState currentState);

For our discussion we will create a state machine that will process a request for promotion workflow. We’ll use:

var statemachine =
       new StateMachine(string currentstate);

This could very easily take the form of

&lt;int, int&gt;

and will depend on your preferences. Regardless of your choice, if the current state is represent by a primitive like int or string, you can just fetch that from a database or a repository and now your state machine is loaded with the current state. Contrast that with WF where you have multiple projects and confusing nomenclature to learn. Stateless just stays out of our way.
Let’s lay out our request for promotion workflow. Here is our state machine represented in English:

Step: Request Promotion Form
  Answer => Complete
  Next Step => Manager Review

Step: Manager Review
  Answer => Deny
  Next Step => Promotion Denied
  Answer => Request Info
  Next Step => Request Promotion Form
  Answer => Approve
  Next Step => Vice President Approve

Step: Vice President Approve
  Answer => Deny
  Next Step => Promotion Denied
  Answer => Manager Justify
  Next Step => Manager Review
  Answer => Approve
  Next Step => Promoted

Step: Promotion Denied
Step: Promoted

Remember the goal Model a workflow in a clear format that is readable by both developer and business user. One set of verbiage for all parties? We are very close to achieving that goal. If we substitute “Step” with “State” and “Answer” with “Trigger”, then we have a model that matches how Stateless configures a state machine:

var statemachine = new StateMachine(startState);

//  Request Promo form states
               .Permit(&quot;Complete&quot;, &quot;ManagerReview&quot;);

//  Manager Review states
               .Permit(&quot;RequestInfo&quot;, &quot;RequestPromotionForm&quot;)
               .Permit(&quot;Deny&quot;, &quot;PromotionDenied&quot;)
               .Permit(&quot;Approve&quot;, &quot;VicePresidentApprove&quot;);

Clearly you will not show the code to your business partners or end users, but a simple chart like this should not make anyone’s eyes glaze over:

State: Request Promotion Form
  Trigger => Complete
  Target State => Manager Review

Before we move on you may want to study the test in the file SimpleStateless.cs. Here configuring the state machine and advancing from state to state is laid out for you:

//  Request Promo form states
                    .Permit(&quot;Complete&quot;, &quot;ManagerReview&quot;);

//  Manager Review states
                     .Permit(&quot;RequestInfo&quot;, &quot;RequestPromotionForm&quot;)
                     .Permit(&quot;Deny&quot;, &quot;PromotionDenied&quot;)
                     .Permit(&quot;Approve&quot;, &quot;VicePresidentApprove&quot;);

//  Vice President state configuration
                      .Permit(&quot;ManagerJustify&quot;, &quot;ManagerReview&quot;)
                      .Permit(&quot;Deny&quot;, &quot;PromotionDenied&quot;)
                      .Permit(&quot;Approve&quot;, &quot;Promoted&quot;);

//  Tests
Assert.AreEqual(startState, statemachine.State);

//  Move to next state


The next question that comes to mind is how to represent the various States, Triggers and State configurations as data. Our mission on this project is to adhere to simplicity. One way to represent a Stateless state machine is with JSON:

{WorkflowType : &quot;RequestPromotion&quot;,
  States : [{Name : &quot;RequestPromotionForm&quot; ; DisplayName : &quot;Request Promotion Form&quot;}
    {Name : &quot;ManagerReview&quot;, DisplayName : &quot;Manager Review&quot;},
    {Name : &quot;VicePresidentApprove&quot;, DisplayName : &quot;Vice President Approve&quot;},
    {Name : &quot;PromotionDenied&quot;, DisplayName : &quot;Promotion Denied&quot;},
    {Name : &quot;Promoted&quot;, DisplayName : &quot;Promoted&quot;}
  Triggers : [{Name : &quot;Complete&quot;, DisplayName : &quot;Complete&quot;},
     {Name : &quot;Approve&quot;, DisplayName : &quot;Approve&quot;},
     {Name : &quot;RequestInfo&quot;, DisplayName : &quot;Request Info&quot;},
     {Name : &quot;ManagerJustify&quot;, DisplayName : &quot;Manager Justify&quot;},
     {Name : &quot;Deny&quot;, DisplayName : &quot;Deny&quot;}
StateConfigs : [{State : &quot;RequestPromotionForm&quot;, Trigger : &quot;Complete&quot;, TargetState : &quot;ManagerReview&quot;},
     {State : &quot;ManagerReview&quot;, Trigger : &quot;RequestInfo&quot;, TargetState : &quot;RequestPromotionForm&quot;},
     {State : &quot;ManagerReview&quot;, Trigger : &quot;Deny&quot;, TargetState : &quot;PromotionDenied&quot;},
     {State : &quot;ManagerReview&quot;, Trigger : &quot;Approve&quot;, TargetState : &quot;VicePresidentApprove&quot;},
     {State : &quot;VicePresidentApprove&quot;, Trigger : &quot;ManagerJustify&quot;, TargetState : &quot;ManagerApprove&quot;},
     {State : &quot;VicePresidentApprove&quot;, Trigger : &quot;Deny&quot;, TargetState : &quot;PromotionDenied&quot;},
     {State : &quot;VicePresidentApprove&quot;, Trigger : &quot;Approve&quot;, TargetState : &quot;Promoted&quot;}

As you can see we are storing all States and all Triggers with their display names. This will allow you some flexibility with UI screens and reports. Each rule for transitioning a state to another is stored in the StateConfigs node. Here we are simply representing our chart that we created above as JSON.

Since we have a standard way of representing a workflow with JSON de-serializing this definition to objects is straight forward. Here are the corresponding classes that define a state machine:

public class WorkflowDefinition
        public string WorkflowType { get; set; }
        public List States { get; set; }
        public List Triggers { get; set; }
        public List StateConfigs { get; set; }

        public WorkflowDefinition() { }

public class State
        public string Name { get; set; }
        public string DisplayName { get; set; }

public class Trigger
        public string Name { get; set; }
        public string DisplayName { get; set; }

        public Trigger() { }
public class StateConfig
        public string State { get; set; }
        public string Trigger { get; set; }
        public string TargetState { get; set; }

        public StateConfig() { }

We’ll close out this post with an example that will de-serialize our state machine definition and allow us to respond to the triggers that we supply. Basically it will be a rudimentary workflow. RequestionPromotion.cs will be the workflow processor. The method Configure is where we will perform the de-serialization, and the process is quite straight forward:

  1. Deserialize the States
  2. Deserialize the Triggers
  3. Deserialize the StateConfigs that contain the transitions from state to state
  4. For every StateConfig, configure the state machine.

Here’s the code:

public void Configure()
    Enforce.That((string.IsNullOrEmpty(source) == false),
                            &quot;RequestPromotion.Configure - source is null&quot;);

    string json = GetJson(source);

    var workflowDefintion = JsonConvert.DeserializeObject(json);

    Enforce.That((string.IsNullOrEmpty(startState) == false),
                            &quot;RequestPromotion.Configure - startStep is null&quot;);

    this.stateMachine = new StateMachine(startState);

    //  Get a distinct list of states with a trigger from state configuration
    //  &quot;State =&gt; Trigger =&gt; TargetState
    var states = workflowDefintion.StateConfigs.AsQueryable()
                                    .Select(x =&gt; x.State)
                                    .Select(x =&gt; x)

    //  Assing triggers to states
    states.ForEach(state =&gt;
        var triggers = workflowDefintion.StateConfigs.AsQueryable()
                                   .Where(config =&gt; config.State == state)
                                   .Select(config =&gt; new { Trigger = config.Trigger, TargeState = config.TargetState })

        triggers.ForEach(trig =&gt;
            this.stateMachine.Configure(state).Permit(trig.Trigger, trig.TargeState);

And we advance the workflow with this method:

public void ProgressToNextState(string trigger)
Enforce.That((string.IsNullOrEmpty(trigger) == false),
"RequestPromotion.ProgressToNextState – trigger is null");


The class RequestPromotionTests.cs illustrates how this works.

We we have seen how we can fulfill the objectives laid out for ApprovaFlow and have covered a significant part of the functionality that Stateless will provide for our workflow engine.   Here is the source code.

Some gifts just keep on giving, and many times things can just take on a momentum that grow beyond your expectation.  Bob Sherwood wrote to Sensei and pointed out that supports multiple column sorting.  All you do is hold down the shift key and click on any second or third column and DataTables will add that column to sort criteria.  ”Well, how come it doesn’t work with the server side solution?”  Talk about the sound of one hand clapping.  How about that for a flub!  Sensei didn’t think of that!  Then panic set in – would this introduce new complexity to the DataTablePager solution, making it too difficult to maintain a clean implementation?  After some long thought it seemed that a solution could be neatly added.  Before reading, you should download the latest code to follow along.

How DataTables.Net Communicates Which Columns Are Involved in a Sort

If you recall, DataTables.Net uses a structure called aoData to communicate to the server what columns are needed, the page size, and whether a column is a data element or a client side custom column.  We covered that in the last DataTablePager post.  aoData also has a convention for sorting:


In our example we are working with the following columns:


where column 0 is a custom client side column, column 1 is Name (a mere data column), column 2 is Center (another data column), column 3 is a custom client side column, and the remaining columns are just data columns.

If we are sorting just by Name, then aoData will contain the following:


When we wish to sort by Center, then by Name we get the following in aoData”



In other words, the first column we want to sort by is in position 2 (Center) and the second column(Name) is in position 1.  We’ll want to record this some where so that we can pass this to our order routine.  aoData passes all column information to us on the server, but we’ll have to parse through the columns and check to see if one or many of the columns is actually involved in a sort request and as we do we’ll need to preserve the order of that column of data in the sort.

SearchAndSortable Class to the Rescue

You’ll recall that we have a class called SearchAndSortable that defines how the column is used by the client.  Since we iterate over all the columns in aoData it makes sense that we should take this opportunity to see if any column is involved in a sort and store that information in SearchAndSortable as well.  The new code for the class looks like this:

public class SearchAndSortable
        public string Name { get; set; }
        public int ColumnIndex { get; set; }
        public bool IsSearchable { get; set; }
        public bool IsSortable { get; set; }
        public PropertyInfo Property{ get; set; }
        public int SortOrder { get; set; }
        public bool IsCurrentlySorted { get; set; }
        public string SortDirection { get; set; }

        public SearchAndSortable(string name, int columnIndex, bool isSearchable,
                                bool isSortable)
            this.Name = name;
            this.ColumnIndex = columnIndex;
            this.IsSearchable = isSearchable;
            this.IsSortable = IsSortable;

        public SearchAndSortable() : this(string.Empty, 0, true, true) { }

There are 3 new additions:

IsCurrentlySorted - is this column included in the sort request.

SortDirection - “asc” or “desc” for ascending and descending.

SortOrder - the order of the column in the sort request.  Is it the first or second column in a multicolumn sort.

As we walk through the column definitions, we’ll look to see if each column is involved in a sort and record what direction – ascending or descending – is required. From our previous post you’ll remember that the method PrepAOData is where we parse our column definitions. Here is the new code:

//  Sort columns
this.sortKeyPrefix = aoDataList.Where(x =&gt; x.Name.StartsWith(INDIVIDUAL_SORT_KEY_PREFIX))
                                            .Select(x =&gt; x.Value)

//  Column list
var cols = aoDataList.Where(x =&gt; x.Name == &quot;sColumns&quot;
                                            &amp; string.IsNullOrEmpty(x.Value) == false)

if(cols == null)
  this.columns = new List();
  this.columns = cols.Value

//  What column is searchable and / or sortable
//  What properties from T is identified by the columns
var properties = typeof(T).GetProperties();
int i = 0;

//  Search and store all properties from T
this.columns.ForEach(col =&gt;
  if (string.IsNullOrEmpty(col) == false)
    var searchable = new SearchAndSortable(col, i, false, false);
    var searchItem = aoDataList.Where(x =&gt; x.Name == BSEARCHABLE + i.ToString())
    searchable.IsSearchable = (searchItem[0].Value == &quot;False&quot;) ? false : true;
    searchable.Property = properties.Where(x =&gt; x.Name == col)



//  Sort
searchAndSortables.ForEach(sortable =&gt; {
  var sort = aoDataList.Where(x =&gt; x.Name == BSORTABLE + sortable.ColumnIndex.ToString())
  sortable.IsSortable = (sort[0].Value == &quot;False&quot;) ? false : true;
                sortable.SortOrder = -1;

  //  Is this item amongst currently sorted columns?
  int order = 0;
  this.sortKeyPrefix.ForEach(keyPrefix =&gt; {
    if (sortable.ColumnIndex == Convert.ToInt32(keyPrefix))
      sortable.IsCurrentlySorted = true;

      //  Is this the primary sort column or secondary?
      sortable.SortOrder = order;

     //  Ascending or Descending?
     var ascDesc = aoDataList.Where(x =&gt; x.Name == &quot;sSortDir_&quot; + order)
     if(ascDesc != null)
       sortable.SortDirection = ascDesc.Value;


To sum up, we’ll traverse all of the columns listed in sColumns. For each column we’ll grab the PorpertyInfo from our underlying object of type T. This gives only those properties that will be displayed in the grid on the client. If the column is marked as searchable, we indicate that by setting the IsSearchable property on the SearchAndSortable class.  This happens starting at line 28 through 43.

Next we need to determine what we can sort, and will traverse the new list of SearchAndSortables we created. DataTables will tell us what if the column can be sorted by with following convention:

bSortable_ColNumber = True

So if the column Center were to be “sortable” aoData would contain:

bSortable_1 = True

We record the sortable state as shown on line 49 in the code listing.

Now that we know whether we can sort on this column, we have to look through the sort request and see if the column is actually involved in a sort.  We do that by looking at what DataTables.Net sent to us from the client.  Again the convention is to send bSortColumn_0=1 to indicate that the first column for the sort in the second item listed in sColumns property.  aoData will contain many bSortColum’s so we’ll walk through each one and record the order that column should take in the sort.  That occurs at line 55 where we match the column index with the bSortColumn_x value.

We’ll also determine what the sort direction – ascending or descending – should be.  At line 63 we get the direction of the sort and record this value in the SearchAndSortable.

When the method PrepAOData is completed, we have a complete map of all columns and what columns are being sorted, as well as their respective sort direction.  All of this was sent to us from the client and we are storing this configuration for later use.

Performing the Sort

[gigya src="" width="204" height="40" flashvars="" allowScriptAccess="always" wmode="window" ](Home stretch so play the song!!)

If you can picture what we have so far we just basically created a collection of column names, their respective PropertyInfo’s and have recorded which of these properties are involved in a sort.  At this stage we should be able to query this collection and get back those properties and the order that the sort applies.

You may already be aware that you can have a compound sort statement in LINQ with the following statement:

var sortedCustomers = customer.OrderBy(x =&gt; x.LastName)
                                           .ThenBy(x =&gt; x.FirstName);

The trick is to run through all the properties and create that compound statement. Remember when we recorded the position of the sort as an integer? This makes it easy for us to sort out the messy scenarios where the second column is the first column of a sort. SearchAndSortable.SortOrder takes care of this for us. Just get the data order by SortOrder in descending order and you’re good to go. So that code would look like the following:

var sorted = this.searchAndSortables.Where(x =&gt; x.IsCurrentlySorted == true)
                                     .OrderBy(x =&gt; x.SortOrder)

sorted.ForEach(sort =&gt; {
             records = records.OrderBy(sort.Name, sort.SortDirection,
             (sort.SortOrder == 0) ? true : false);

On line 6 in the code above we are calling our extension method OrderBy in Extensions.cs. We pass the property name, the sort direction, and whether this is the first column of the sort. This last piece is important as it will create either “OrderBy” or the “ThenBy” for us. When it’s the first column, you guessed it we get “OrderBy”. Sensei found this magic on a StackOverflow post by Marc Gravell and others.

Here is the entire method ApplySort from DataTablePager.cs, and note how we still check for the initial display of the data grid and default to the first column that is sortable.

private IQueryable ApplySort(IQueryable records)
  var sorted = this.searchAndSortables.Where(x =&gt; x.IsCurrentlySorted == true)
                                                .OrderBy(x =&gt; x.SortOrder)

  //  Are we at initialization of grid with no column selected?
  if (sorted.Count == 0)
    string firstSortColumn = this.sortKeyPrefix.First();
    int firstColumn = int.Parse(firstSortColumn);

    string sortDirection = &quot;asc&quot;;
    sortDirection = this.aoDataList.Where(x =&gt; x.Name == INDIVIDUAL_SORT_DIRECTION_KEY_PREFIX +                                                                    &quot;0&quot;)

    if (string.IsNullOrEmpty(sortDirection))
      sortDirection = &quot;asc&quot;;

    //  Initial display will set order to first column - column 0
    //  When column 0 is not sortable, find first column that is
    var sortable = this.searchAndSortables.Where(x =&gt; x.ColumnIndex == firstColumn)
    if (sortable == null)
      sortable = this.searchAndSortables.First(x =&gt; x.IsSortable);

    return records.OrderBy(sortable.Name, sortDirection, true);
      //  Traverse all columns selected for sort
      sorted.ForEach(sort =&gt; {
                             records = records.OrderBy(sort.Name, sort.SortDirection,
                            (sort.SortOrder == 0) ? true : false);

    return records;

It’s All in the Setup

Test it out. Hold down the shift key and select a second column and WHAMO – multiple column sorts! Hold down the shift key and click the same column twice and KAH-BLAMO multiple column sort with descending order on the second column!!!

The really cool thing is that our process on the server is being directed by on the client.  And even awseomer is that you have zero configuration on the server.  Most awesome-est is that this will work with all of your domain objects, because we have used generics we can apply this to any class in our domain.  So what are you doing to do with all that time you just got back?

ActiveEngine Software by ActiveEngine, LLC.