Sunday, December 7, 2014

Microsoft Prism MVVM for Windows Store Apps

Presentation:  December 9th, 2014

This communication will race over PRISM MVVM for Windows Runtime and beyond.  In itself there is nothing new in this presentation, however, placed in the context of the new Azure study group, mastering this Microsoft technology gains relevance.  The case study of this communication, "Gasoline Performance Auditor" is a learning tool which will serve well as a medium to exercises to originate from the Azure study group.

So, my December 9th presentation is posted here (download).  Join this journey and get the presentation in advance.

From design...



  • Identify Views
  • Create ViewModels
  • Commanding and Behaviors
  • Navigation
  • Design data repositories and services
  • Dependency Injection

To Something more Elaborated...



We could start our discussion here.

Sunday, November 16, 2014

WPF Prism MVVM: My Learning Experience

Motivation

We have became accustomed to using design patterns to solve common and complex problems that recur often in software engineering and also in our lives.  A common pattern that applies to presentation XAML based solutions is the Model-View-ViewModel pattern or MVVM.  This pattern applies when creating solutions targeting Windows Store Applications (Win RT), Windows Phone, WPF systems and Silverlight applications and it is consider best practice for these kinds of solutions.

Since I joint the Metro Vancouver Windows Platform Developer Group I have been exposed to refreshed ways of building Windows Store Applications and to best practices on how to build them.  Recently at the user group we had a presentation by Mike Wuetherick, technical lead from Plenty Of Fish with the title "Building Windows Apps: Lessons from the PlentyOfFish Team".  The framework that Mike talked about in his work was MVVM Light which is widely used when creating XAML based solutions.

There is nothing wrong in implementing the MVVM pattern from the ground up however delegating on a mature framework such as MVVM Light or Microsoft PRISM always produce benefits including reducing implementation time and also the number of defects introduced "while re-inventing the wheel".  These frameworks also resolve complex issues in an elegant and simple way allowing us to focus on our business case instead of dedicating resources to duplicate what other teams have already accomplished.

This note starts me on a journey to rediscover the MVVM design pattern under the umbrella of PRISM in preparation for a 10 minutes presentation that I am planning to deliver at the BC .Net User group for the month of December of 2014 and because I had the opportunity to create a small WPF solution, I decided to implement the PRISM pattern and then move the learned concepts into the creation of a small Windows Store Application, possibly creating a Universal App.

So, here we go!

MVVM

This study does not dive into MVVM, nor it demonstrates its awesomeness; it just uses it.  The first time I heard about this pattern was in 2011 when I was taking a Silverlight course from Medhat Elmasry at BCIT.  However, it is worth mentioning that MVVM (Model-View-ViewModel) is an architectural pattern used widely in software engineering which originated from Microsoft.  This pattern is largely based on the Model-View-Controller (MVC) pattern (saying this has caused me grief in the past with some folks).  

MVVM helps separate the business and presentation logic of an application from its user interface (UI).  It supports event driven programming, and it is the recommended pattern when creating solutions using .NET platforms and XAML.

Installing Prism MVVM for WPF

Why use Prism in the first place?

The framework encourages good practices, modularity, view discovery using an Experience mechanism which associates a ViewModel with its View.  This helps add semantics and conventions to our solution.  By the same token, one of the great benefits of MVVM is that solutions can be designed with testability in mind.  

Although not explored in this note, PRISM MVVM works very well with other frameworks such as Unity for dependency injection.  The Unity framework was also created by the Microsoft Practice and Pattern team:  these folks are smoking!

Adding PRISM to a solution is very simple and it can be downloaded from CodePlex or installed via NuGet.  I like easy, so I went NuGet for this note.  



Once the framework has been installed expand the reference node in solution explorer and you will notice 7 new references including Prism.Mvvm, which provides the MVVM framework subject of this note.  



It is also worth mentioning Prism.PubSubEvents which is used as event aggregator to address tightly coupled .Net events.  Event aggregators are also used within the PRISM framwork to send  messages between modules and between different objects.  Another interesting library that has been added to the project is the Prism.ServiceLocation which offers a navigation service within the Prism framework.  These are important features of the Prism framework which I will soon return to.

Using Prism MVVM for WPF

The application used to apply this pattern as a proof of concept,a learning tool, is very simple and what it does is load a collection of players, from different teams with their high score and the number of stars that they have collected.  Assume that your business analyst have provided you with this screenshot:



From the "design" document two views are identified; a MainWindowView and a PlayerItemView.  From these views, properties of the ViewModels that support these views are identified.

Note that this View uses an ItemsControl which could be used in PRISM as a Region where other views can be placed.  Regions are not discussed in this note.


So, what does a model able to support MainWindowView needs?
  • ICommand property to Fetch data.
  • ICommand property to Clear data.
  • Observable Collection of Player Item View Models

What does a model able to support PlayerItemView needs?
  • Player Name.
  • Team Name.
  • Team Color.
  • High Score.
  • Total Stars available.
  • Total Stars obtained.

You can take a look at the implementation of these View Models by downloading the sample code.  It is very simple.  Note that although it is not required by PRISM, the ViewModels were defined in their respective interfaces.

Views, PRISM IView and View - ViewModel Discovery

In a basic implementation of PRISM, and this note is just that, each view which is associated to a ViewModel needs to implement Microsoft.Practices.Prism.IView.  This is required by the PRISM discovery mechanism.

The way the View and ViewModel are associated is by Experience.  Experience is a string which forms part of the name of the View and ViewModel and it is shared by both objects.  For example; experience string Main:

Experience: Main  > View:  MainWindow > ViewModel:  MainWindowViewModel

Note that this is just a convention and it can be changed.  However, this mechanism only works when the property AutoWireViewModel is set to true in the prism ViewModelLocator object.

From MSDN:
Prism’s ViewModelLocator class has an attached property, AutoWireViewModel that when set to true will try to locate the view model of the view, and then set the view’s data context to an instance of the view model. To locate the corresponding view model, the ViewModelLocationProvider first attempts to resolve the view model from any mappings that may have been registered by the Register method of theViewModelLocationProvider class. If the view model cannot be resolved using this approach, for instance if the mapping wasn't created, the ViewModelLocationProvider falls back to a convention-based approach to resolve the correct view model type. This convention assumes that view models are in the same assembly as the view types, that view models are in a .ViewModels child namespace, that views are in a .Views child namespace, and that view model names correspond with view names and end with "ViewModel."
In this basic implementation I used the convention approach, the experience string, and placed Views in the Views namespace and ViewModels under the ViewModels name space and named the objects as per the convention requirement


 The in the XAML of the view a reference to PRISM is includes and the AutoWireViewModel is set.

Note that you need to include xmlns:prism="clr-namespace:Microsoft.Practices.Prism.Mvvm;assembly=Microsoft.Practices.Prism.Mvvm.Desktop"

In the above example you can see that nor the XAML or the code behind of MainWindow contain a reference to the ViewModel.  The framework is associating these two together through the ViewModelLocator.  The ViewModelLocator is a new feature for PRISM WPF which is also included in PRISM for Windows RT.

PRISM also offers other mechanisms for this association by registering a view type against a region name.  This discovery approach uses RegionManager and it is not discussed here.

Design Time

Although not required by PRISM WPF, the development experience can be enhanced by using design time ViewModels.  For this reason, it is recommended to define ViewModels with an interface which is implemented by a runtime and a design time view model respectively.  There is some duplication in doing this, however, a clear advantage can be seen in the next image.  


Using a Design time ViewModel provides advantages while working with the designer or Blend.

In the above example interface IPlayerItemViewModel defines the view model which is implemented by a view model object which will be used at run time and a design time view model used only at design time and not used at run time.  



Note that in the designer view the value converters code work and convert the enum Team TeamColor into the name and the Brush to color the background of the layout container.  The design time values set in the constructor of the design time view model are displayed in the designer.  This is great because it is providing us with a real look and feel of the view while we are designing it without the need to run the project to see what it would look like.

Time to Reflect:  When Using MVVM, does this mean no code behind?

This could be up for debate and we have a "binary" number of schools out there: "No-Code-Behind" versus "Yes-Code-Behind"... there is no in between because even if you place "just a little bit" of code behind, well, that is "Yes-Code-Behind", right? 

I belong to the "It-Depends-What-It-does-Yes-Code-Behind" school, which is pretty much in the basement of the "Yes-Code-Behind" school.  I feel that if the code behind does work which concerns to the UI logic then it would be "OK" to place it in the code behind and this does not break the MVVM pattern.

I would be breaking the pattern in the case that the code behind was executing code which concerns to the business or application logic; like for instance talking to a service or repository to get or update data which is really the responsibility of the ViewModel.

Which one is your school? 

Conclusion - A Basic PRISM Implementation

  1. Add the framework through NuGet to your solution.
  2. Every view which has a ViewModel must implement IView.
  3. Views use ViewModelLocator.AutoWireViewModel set to true.
  4. Take into account an Experience string when naming a view and its view model.
  5. Optional:  Use a design time ViewModel which facilitates your work in the design and using Blend because you see in the designer the view at design time.

Download the Sample Code

The sample project was created using Visual Studio 2013 Ultimate and you can download it from the following location:  DOWNLOAD.

References:

  1. Developer's Guide to Microsoft Prism for WPF
  2. Implementing the MVVM Pattern using the Prism Library 5.0 for WPF
  3. Pattern and Practices - Prism for WPF
  4. Pattens and Practices - Prism for the Windows Runtime:  This article provides guidance to developers on how to use modern practices, however, it targets Windows RT.
  5. Visual Studio 2013 Ultimate trial.  It does not get easier than this.  You can also get a lot done with the Express edition.
  6. Getting Started with Prism’s new ViewModelLocator:  A punchy simple example by Brian Lagunas.
  7. Developing Universal Windows Apps with C# and XAML:  MSDN Channel 9 Course on building Windows Apps masterfully delivered by Jerry Nixon and Daren May.
  8. IValueConverter Interface:  MSDN article explaining how to use value converters to apply custom logic to a binding.

Thursday, September 18, 2014

Threat Modeling at the BC .Net User Group with Dana Epp

Gathering at the local .Net User Group​

Yesterday, September 17th, 2014, I attended a magistral lecture by Dana Epp at the .Net BC User group entitled "Making Threat Modeling Fun and Easy".  During the presentation Dana explained the STRIDE Threat Model in detail and associated every term of the acronym with real live examples and stories about how data and services have been compromised.  Scary stuff!

STRIDE

Although you can read about this paradigm in one of the references that I provide in this note I would like to mention in very few words what this means:



​S
​Spoofing Identity
T
​Tampering with Data
​R
​Repudiation
​I
​Information Disclosure
​D
​Denial of Service
​E
​Elevation of Privilege

Data Flow Diagrams to Identify Risks 

He also explained through Data Flow Diagrams how our data could be at risk every time it crosses a boundary and that mitigation of these risks must be taken into account seriously at design time and not after the fact.  


Microsoft provides software engineers with a free tool to create Data Flow Diagrams diagrams to create a model of the system and once the graph is created the tool will identify each risk and mark them as "High" risk until it is reviewed.  While reviewing the result of the analysis of the tool assessment engineers can mitigate these risks by addressing these vulnerabilities in their design.  In the case that we are satisfied by the mitigation the risk then the item could be marked as "mitigated".



Microsoft Threat Modeling Tool 2014 - Analysis View

We would then design and implement, and unit test, the system making sure that the identified risks have been properly mitigated in the implementation of the system.  The unit test will prove that the implementation works but also need to exploit these boundaries and validate that threats have been mitigated. 

But we are not done yet!  QA Engineers will then base their test case design on the threat model of the system and try to validate the mitigation and obliterate the system.

After Dana finished his presentation we had a little break followed by creating two big working groups where attendants discussed the learned concepts using a risk analysis game card.  This activity was refreshing and sometimes I wish we could do more of these sessions because we get to exchange ideas and thoughts...  we learn more this way.

I rate the meeting as very top quality, delivered by one of our own, Dana, who was supported by one of his colleagues.  Some times I wonder the reason we do not get higher attendance to these events when the entrance is always free, it has been like that for a number of years thanks to the user group sponsors.

This meeting was graciously sponsored by BCIT and the Burnaby office of TekSystems.  The references provided bellow will get you introduced to the main concepts of the meeting and will get you going using the Threat Modeling Tool.


"If you wish to make an apple pie from scratch, you must first invent the universe"
                                                                                                                        Carl Sagan

References:


  1.  Microsoft Threat Modeling Tool 2014:  This is the same threat modeling tool used at Microsoft and it is free!
  2. Definition of the STRIDE Threat Model.  MSDN article where the terminology is defined. 
  3. Introducing Microsoft Threat Modeling Tool 2014.  In this article the reader is introduced to the paradigm of how to use the Threat Modeling Tool during the Security Development Lifecycle (SDL).

Sunday, July 6, 2014

Windows Phone 8 and Beyond: A Data Driven Application and The Return of the Jedi Knight. Part I Getting Started and Localization of a Windows Phone 8 App

Introduction

In the past when I was introduced to Windows Phone development (WP7) I was a little disorganized and although the goal was to publish to the Windows Phone Store my cool apps were not ready.  My WP7 apps had limited usage.  So, even if I would like to undust those apps and deploy them to the store I have to rethink the way I build them.

So, I need to retrain myself and I intend to document my journey.  The reader might find the following posts useful but I am doing this as my own journal.  This are my references and experiments.


The application that I am creating is very simple and it is helping me to learn new concepts and revisit already learned techniques.  The application has an Internet Browser and the user is able to browse to the requested page, add/remove URLs to a favourite collection.  The favourite collection is sorted by date added (Created When) where the most recent entry is at the top.  The user is able to delete favourites.  The application will contain a settings or configuration area where the user is able to define sorting order, display total count of favourite and set parameters to automatically purge old favourites.  The application will also have a navigation bar like any regular browser with Back, Forward, List Favourites and add to favourites buttons as well as a menu item to navigate to settings.  The application would use resources to facilitate localization based on user region and language preferences.

I thought that this simple app would allow me to stretch all my muscles and set me on the right track.  However, this inspiration did not come out of the blue

Motivation: Succeeding in the Windows Phone Store

Recently I went to a presentation at the British Columbia .Net User Group and the subject was how to be successful in the Windows Phone Store.  The presenter was one of the organizers of the Metro Vancouver Windows Phone Development Group, Nora Sabau.  Her presentation was not about coding but about guidelines to follow, common sense and what not to lose track of when designing a Windows Phone application.  I would like to think that Nora's main take home ideas were the following:

How to be Successful in the Windows Phone Store

  1.  "WOW" your users.
  2. Have a marketing plan for your application.
  3. "The Price is Right!": not too expensive, not too cheap... use "The Force" to get it right.
  4. Localization of the application.  Do not forget the World; it is bigger than Burnaby.
  5. Target devices (Windows Phone 7, 7.1, 8.0, 8.1).
  6. Create an app that the user would not want to remove by exploiting social media, usage of the Internet, entertainment, usefulness.
  7. Quality, quality and more quality!
The above are "take away homes" thoughts because the presentation was much richer than that.  On the way home, while racing through the asphalt of the "Number One" highway, I imagine what "Obi-Wan" would tell me, if he had a chance: "Its is time to complete your training and become a Jedi, but first you need to face your fears". :)

All right, I need to face the music and create an action plan which would cover some of the above key thoughts.  Here is the plan for this training session :
  1.  Download the WP SDK and take a look at sample code.
  2. Create a simple Data Driven WP 8 application.
    1. Customize the application tile.
    2. Localize the application.
    3. Use the MVVM Pattern.
    4. Use of IsolatedStorageSettings to storing application specific settings. 
    5. Use SQL Compact.
    6. Try different ways to create a DataContext.
      1. Code generation using tooling (SQL Server Compact Toolbox).
      2. Code First with ADO.Net Entity Framework.

Download the SDK

Getting the SDK is a snap.  After installation make sure that the BIOS settings support Hyper-V otherwise the emulator will fail to start.  Once the SDK is set you can get started... Trust The Force and learn from sample code provided, those are great!

Localization of a Windows Phone 8 Application

I believe that in the design process localization should be decided early and this is because localizing a WP app, as of any other application, requires the use of resource files and it is easier to add values to these files as we go rather than searching and replacing strings from views at the end of the project with their corresponding localized resource.

But this is easy, I like easy!  To help novice Jedi WP Developers, Microsoft has placed XAML and C# comments providing hints as to how to localize the application.  I used those hints to localize my app combined with MSDN and Channel 9 resources.

A required file for localization is the "AppResources.resx" which allows us to store name - value pairs which can be accessed from XAML or C#.  The objective becomes to author different versions of this file for different languages then the OS of the phone would select the correct file depending on the user localization settings.

Authoring Different Resource Files

Assume that you have created your application and all strings, labels, captions, etc are using the AppResources.resx resource file.  To create additional resources based on supported culture view the property of the project, not the solution, and select the languages that the application intends to support from the "Supported Culture" section in the "Application" tab.  After selecting the desired languages save and note that Visual Studio creates the respective resource files, AppResources.es.resx, and AppResources.fr.resx for Spanish and French respectively.

Note that the created files are identical copies of the original AppResources.resx.  Now you can edit the values of these files, not the keys, with the translated strings.


In Application Tab select a Supported Culture and save the file.  Visual Studio creates the corresponding files.  Open those files and edit the Values.  The key needs to stay the same.

Binding to Localized Resources Directly from XAML

Binding to a localized resource from the XAML is very easy:

Content="{Binding Path=LocalizedResources.GoBtnContent, Source={StaticResource LocalizedStrings}}"

In the Path, the LocalizedResources refers to the AppResources.resx content and the property is the key name of the localized string in the resource file.  The source "StaticReource LocalizedStrings" refers to the class LocalizedStrings which is used by the framework to select the appropriate resource file based on the user regional + language settings.  Leave this class alone for now as I do not thing you need to touch it.

Localizing Resources from C#

Resources can be localized from C# code as well.  To me, it seems more laborious this way and I would only do it from C# code in case that I cannot find an easy way to bind the resource from XAML like we saw above and localizing the ApplicationBar seems to be the case.  However, the solution to the problem was suggested in the hints and comments added by Microsoft:  thank you!

The following code snippet adds four buttons and a menu item, all localized, to the application bar.

Call BuildLocalizedApplicationBar() from the constructor.

To see localization in action we need to select Settings in the emulator and access "language + region".  The following figure shows two different settings; Spanish and English.  So, it works!



Part II

For Part II, soon to be published, I will document how I created a compact database to use with this Data Driven application.  The tools available such as SQL Server Compact Toolbox and ADO.Net Entity Framework Code First, revisit binding and MVVM.  

What Obi-Wan has to Say

"Jose, none of these techniques are new, they are part of an ancient religion and I encourage your to continue and complete your training and have fun while at it".

Thank you Ben!


To Windows Phone Developers, old and new, with apps or just mere ideas:  "I look forward to seeing them in action", Obi-Wan Kenobi, Episode IV, A New Hope 1977  

References

Friday, June 27, 2014

Did you Know That... an event handler will execute in JavaScript as many times as registered when the event is triggered. How to disallow that?

Recently I have been looking at JavaScript files written by, perhaps, less experienced JavaScript developers and noticed that  in some instances the code was calling a function which was manually wiring an event and that this function was being called more than once.

The problem with this is that the event handler will be executed as many times as the event was registered and this could have a performance impact or have other unwanted consequences.  So, how to stop registering events in JavaScript more than once?  Being "careful" might work for small projects but code can grow very quickly and it is just as easy to register the event again.

This note is trying to explore different ways or techniques to avoid registering an event more than once and therefore avoid the negative consequences that might bring the execution of the event handler multiple times.

UnBind and Bind Event

The easiest way to prevent an event from being wired to an element more than once would be to unbind all bound events and bind the event again.  This technique would work well.  I often yank code like that into a common area where it could be reused from anywhere in the code.


Figure 1: Line 8 unbinds all click events and binds a single one. Line 7 is only there fore sanity just in case that the callback handler is not a function


Tests for Registered Events

A different way of accomplishing the same result would be to test if the event has been already bound to the element. In the case that the event has already been bound then the event is not manually bound.


Figure 2: The event is registered if and only if not registered previously. This variant is a bit more involved and it is essentially different from what was presented in Figure 1.

None of this is new, as a matter of fact the above techniques can be found all over the internet.  The important issue here is that one has to be careful when binding events manually.  Multiple binding could be the cause of unnecessary server posts taxing in performance and unexpected results.

However, the above techniques would be useless if the team does not adopt them at large and the code is littered with event bindings indiscriminately.  But always keep in mind that "If the Scatman can do it, so can you".


Friday, February 7, 2014

Server Side Data Pagination using jQuery.DataTables

Introduction:  Server Side or Client Side Pagination

Often when a project needs to display a collection of data on the client an earlier question is "do we need pagination"  and if the answer is "why, yes!" then another question with bigger implications pops up:  "will the pagination take place on the client or on the server?".  The answer now depends on requirements:  Data set size, is sorting and filtering required.

Client side pagination is great for displaying a small data set with a few hundred records.  A simple AJAX call to the server should suffice.  Loading subsequence pages, and sorting and filtering would be very fast because the entire collection resides in memory on the client side.

However, when the data set is very large, or large enough, like a few thousand records, server side pagination gains more relevance.  With server side pagination large amount of data do not need to be send down the wire to the client improving the client perceived response time.  Filtering and sorting of the data on the server is also desirable and will increase performance when dealing with large data sets.  As a result pages load faster than if the client were dealing with the entire collection.

Client Side Pagination with DataTables

DataTables is a very simple to use jQuery AJAX enabled plug-in which with very little effort can display a collection of objects in a grid, or table, and can also provide paging, sorting and filtering.



The above function is very simple and it loads a collection of products to DataTables.  In the above scenario there is no ajax to the server for pagination, sorting, or filtering and instead DataTables will do everything using the local collection of products.  For a POST/PUT (add new/update existing) the collection will need to be retrieved again and the table needs to be recreated again.

The "products" json would look like something like this.




Server Side Pagination

In the case that we have thousands and more thousands of products then the above approach will cause problems and make the application seem slow.

The solution is Server Side pagination and serve a page of data to the client on demand.  Server side pagination would be simple to implement using LINQ Enumerable.Skip(number_of_records_to_skip) to bypass a specific number of records and Enumerable.Take(number_of_records_to_return) to return a specific number of records, "the page".

An alternative would be to use PagedList, which is essentially the same with the difference that instead of providing the number of records to skip PagedList requires the page number and the number of records to return:

Using Skip and Take

foreach (var product in queryProducts.Skip(model.RecordNumber).Take(pageMaxSize))
{
        // TODO
}

Using PagedList

...
var pageNumber = (iDisplayStart / iDisplayLength) + 1;
...
foreach (var product in queryProducts.ToPagedList(pageNumber, pageMaxSize))
{
         // TODO
}
The server side code looks like this:



The above method is a WEB API action.  The way the WEB API service was setup falls outside of the scope of this note.  I leave you with a reference related to WEB API, in particular how I setup Dependency Injection for my ProductController in the case the reader is interested in DI to a WEB API controller.

Because it is relevant to the next section related to how the data table is setup, I would like to show you the DTO that the action is returning.



This DTO contains two properties which are very important for DataTables to work correctly and display your data and paginate as you intend.  The properties are Count which is serialized as "iTotalRecords" and TotalDisplayRecords which is serialized as "iTotalDisplayRecords". iTotalRecords is the total number or records which are the database; this is the entire collection beforeapplying filtering and iTotalDisplayRecords is the count of records after filtering has been applied to the data.  For this reason we need to execute the IQueryable before the pages are processed in the for-each loop.

Setting up the DataTable is now a little different because it is now ajax enabled.  Note that the configuration object now contains two important parameters 'bServerSide" and "sAjaxSource" to instruct DataTables that processing is now done server side.  Now it is up to the server side to do the heavy lifting.  The configuration sPaginationType full_numbers is telling DataTables to display numbers for each page for the user to access directly a specific page.



This example is very simple.  I learned about the parameters that DataTables sends to the server in the ajax call by inspecting the request.

Conclusion


  1. Use DataTables for a cool and efficient way to display data in a grid
  2. Data pagination is done server side using an IQueriable extension, PagedList.  PagedList can be obtained through Nuget.
  3. Data pagination can also be carried out with LINQ Skip and Take and it is very simple.
  4. DataTables manages: Pagination, Filtering, and Sorting of the data by sending to a server action parameters containing the required information: page size, sort order, filter by, etc.
  5. Paginate on the server in the case that it makes sense due to the size of the data.


References

  1. LINQ Skip: http://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx
  2. LINK Take:  http://msdn.microsoft.com/en-us/library/bb503062(v=vs.110).aspx
  3. PagedList:  PagedList is a library that enables you to easily take an IEnumerable/IQueryable, chop it up into "pages".  The Paged:List project also providesm with an Html Helper, PagedList.Mvc, for displaying the data on the client.
  4. DataTables:   DataTables is a very simple to use jQuery plugin.  This data table plug in can be loaded with json data resulting from an ajax call or it can also perform server side processing.
  5. jqGrid:   Is an AJAX enabled javascript control which can be used as an alternative to DataTables.  It is also very simple to use, very well documented and supported by the community.
  6. Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application:  A nice article in the asp.net site which features PagedList and PagedList.Mvc.
  7. Supporting OData Query Options:  Paginating OData
  8. Setup DI in a WEB API Controller 

Thursday, January 16, 2014

Did you Know that one can do this? Passing a Delegate Func<T, TResult> parameter to a function as an argument of a LINQ query

Why on earth would you want to do that?

True, true but I came across a problem a few days ago while designing a TDD unit test and this was the situation:  a great number of these tests needed to query a collection of objects which contain XML strings which needed to be de serialized into different objects.

One thing that the test "knew" ahead of time was the type of the object and based of this type the collection needed to be queried accordingly...  then I thought that I needed a "callback", just like in JavaScript when we pass executable code as an argument of a function?  ... a callback, right?  The same I needed here, for me to encapsulate all this mundane code into a helper function instead of writing this over an over in every test.

Passing a Func<T, TResult> as a parameter of a method

It is simple; take a look at the signature of my test helper function.  This is the call back signature, and what I want it to do once it will be executed, in the LINQ colleciton.Where, is defined in the body of the unit test code and it is a validation predicate.


Note how the test method now calls this utility passing this "callback" delegate Func as a parameter.


With that little trick I managed to encapsulate all the utility code in one place and reuse it.  All I needed to do was change the type of object that I wanted and the func delegate.

Overkill?  Maybe, but I think that it makes cleaner code.

References:

A1 Repo: Simple Pagination for WCF Service Operation

It is never a good idea to paginate on the client.  This post is about a simple pagination for a WCF service operation.  For this work I nee...