A magical concoction Asp,WebApi,jQuery,KenodoUi,Knockout.js,WCF,Async,Moq

 

So the heading for this post is a little bit of a mouthful, but I want to tell you a story of how some of these technologies play together, so often in blog posts we are presented with a trivial example (I’m holding my hands up here too) and what we really want to see is that next step, i.e is the tech in question just a nice concept or can it be utilized practically?

Let me tell you what I’ve come up with, the application in question could be written with any web tech and just render some static html and we’re done. But we’re moving into web 3.0 (don’t google that I’ve just coined it!), where our ajax-ey applications are going to the new level.
We’ve all heard the stories of these 2.0 web applications that are many hundred thousand lines of code and hard to maintain, so can it be made easier? Of Course!

There are many new frameworks out these days, and to be hones it’s impossible to keep up with them all, the main thing to know is what they are for so you can investigate their effectiveness if needed; after your investigation you can decide if you want to continue the relationship a little further, in the post I will present some of the technologies I’ve encountered/like/love want to know better. I’ll explain where I used them and how,  hopefully you’ll see that they play quit well together.

WCF

I’m using WCF in the application to talk to some back end Java webservices, these webservices will supply the business objects that my web application is dealing with. I’m not sure I need to explain how I get a service reference but I’ll do so all the same, just right click on project References (or service references if that already exists) and choose the Add Service Reference Option

image

Type in the location the the webservice (a Soap webservice in my case) and press Go.

image

Give your service a meaningful namespace and click OK. That’s pretty much it, In my case I needed to perform addition Kerberos security configuration in the web.config but you’ll have to figure out what configuration you need for your own webservices yourself.

RavenDB or EF Code First (undecided)

Ok I really want to use RavenDB because I’ve used it in other project and I love the document database approach, it’s got some limitations for reporting etc, but it would be a good fit for our application. Also Entity Framework Code Fist is another good approach and we do already have SqlServer licenses so that’s pretty compelling… The great thing is i can pretty much decide later Smile for now I’m just writing my poco (Plain Old CLR ) objects.

WebApi

I love this tech, (btw: Microsoft if you’re listening please don’t break too much with the RTM version! please please). It allows me to offer a nice RESTFull service to my data (coming both from the WCF webservice and my application database), One of the beauties of this API is that it gives some clear direction on how to implement restfull services. MS developers previously we were faced with a decision between WCF and MVC Controllers, while it’s true now we are faced with a decision between Controllers and ApiControllers, for me it’s now clearer; I use my ApiControllers for data access, and I use my standard mvc controllers for rendering the view!

Confused? Look at this diagram

image

  • Here the browser makes a request, it gets routed to the MVC controller, this controller generates the html with with ever context is needed,
  • Once the browser loads the page we make a ajax request to the web api, the web api in turn makes an Async request to the java webservice thereby freeing up the ASP thread pool to service other requests and providing better scalability.
    How? : .net 4.5 async await

    image
  • When the response arrives back to the await the state machine restores the context and a (possibly) new thread picks up from where the first thread left off and returns the data to the browser.

To sum up, the advantages of the above approach are:

  1. A hugely more responsive experience for the end user, as compared with full page refreshes or even partial page refreshes (as in traditional Ajax).
  2. The server-side UI code is extremely simple, as it needs only to transmit an initial block of markup referencing the necessary JavaScript libraries. It doesn’t need to render data.
  3. Using WebAPI services as the basic data endpoint creates the opportunity to use multiple client technologies. For example, you could create a native smartphone application that connects to the same data endpoints without needing any additional server-side code.

 

jQuery

The data returned in in JSON format as we queries data via jQuery $.getJson() that sets the appropriate header (content negotiation is handled via Asp MVC4 for us).

image

Knockout.js

So this is one of the frameworks I knew about but had not used before. Those of you from a Silverlight/Wpf background will be familiar with the MVVM pattern and love the raw powerfull databinding capabilities. Knockout.js is one such javascript framework.

Markup

image

Javascript

image

Above you can see that I’ve got a DataFeedsViewModel, this is the top level view model ($root) that my html is databound to, looking at it with the markup you can see that I’m rendering an unordered list of suppliers IFF there are items in my array. The observable array is used so that the UX/GUI can update should the underlying list of array items change. Each list item has a click handler that is bound to the contentClick function in the $root view model, the beauty of this is the variable ‘e’ is just the single SupplierDetail object that was clicked!! nothing to do with any DOM elements…. nice..

 

KendoUI – by telerik

I’ve used telerik many times, silverlight/wpf/asp ajax etc, I also listen to lots of technical podcasts and had heard some interviews with the authors/designers of KendoUI so I decided to check it out for myself. The first control I used was the grid. Lets have a look at my markup and the associated javascript

Markup

image

Javascript

image

I’m using the revealing module pattern above to initialize my grid, you can see it’s using a kendoDataSource object to talk to the WebApi, the url parameter would be the url of my api,
/DataFeedApi for all records
/DataFeedApi?contentId=XXX for getting a subset of records from the WebApi

 

Moq

As I mentioned above I’m using WCF, WCF is composed of three concerns, the ABCs of WCF, (Address, Binding, Contract) is simple terms the Contract is the wsdl and when we add a service reference that a .net Interface gets generated for same.

The beauty of this is that in my Unit tests I can mock this interface so I don’t need a real connection to the webservice to test my concerns. For those of you that don’t use mocking frameworks, you should, it saves you creating endless dummy classes that implement interfaces just for testing.

 

image

Above you can see I’m mocking the interface DataContentActionsServiceType so that when I call the (It’s java hence the non standard .net naming convention IXxx)

  • getAllDataSupplierInfos method that I return ECB and APX.
  • getDataSupplierForCode(“APX”) returns the Netherland Stuff record.

That about sums up what I wanted to show, hope it encourages someone to start playing with any of the above technologies and see if you can leverage them in your own applications.

Brian.

Using DataTables.net with Asp MVC Web Api

 

So I’ve been working on Web application that uses the ASP MVC4 Web API. I like this approach especially as it will easily allow me to support other clients I/others may write in future, in so far as, it returns Json and is a RestAPI.

Now I’ve never used DataTables before so I’m trialling it as my client side html grid. However I quickly ran into problems with it and the expected Json Payload.

 

If you are familiar with the various .net Json serializers you’ll get some Json back with Key value pairs.

image

e.g.  {[“Name” : “Brian”, “Age” : “35”], [“Name” : “Brian1”, “Age” : “36”]}

This causes a major problem for DataTables in that it expects (by default)

e.g. {“Brian”, “35”], [“Brian1”,“36”]}

I say by default because maybe there is a way to configure this out of the box with column mappings and what not, however I can’t see the wood for the trees so my first approach will be to perform this data mapping myself, I’ll RTFM at a later date Smile

 

So where can I plug into the pipeline and map this data? fnServerData ! This function allows me to manage how I get and format the data, exactly what I need.

Here’s how I’ve implemented it.

image

 

I’m not saying it’s the best solution! May even have a few bugs, but it appears to do the trick for me for now.

Update:

I’ve now read the documentation: and it’s oh so simple to handle the ASP MVC Json array.

 

image

Moral of the story

Read the manual Smile

Ninject Dependency Resolution in ASP MCV4 WebApi

 

Ok so you’ve been using ASP MVC3+ and using Ninject as your Dependency Injection resolver. Now you want to start leveraging the Asp.WebApi and continue to use Ninject.

I was surprised to find it wouldn’t work out of the box! Ok I’m using the “out of the box” term a little lightly here as you have to (one approach) use Nuget to install some assemblies and generate some code

image

 

A little extra effort

Brad Wilson has provided an implementation of the IDependencyResolver for WebApi that you can use for now.

https://gist.github.com/2417226

What you need to do is copy that code into a file and then call it from your current NinjectWebCommon.cs by adding the highlighted line below:

image

 

Brian.

Pry it from my cold dead fingers

 

I usually try avoid getting into the OS / Browser etc drama, yawn….

But I found this blog post on Pluralsite tonight, and I can help but laugh, I’m with the 72% it turns out, I am asking myself did I pick that option because it was just funny however Smile

image

A little drama

Q: Will I use Windows8?  A: Yes I’ve been using it since developer preview.
Q: Am I bothered? A: Not really, it’s a new opportunity so I’m getting on board.
Q: Would I like the option to switch off Metro? A: Hell ya! (but I’m then back in Win7 ain’t I? maybe I sub consciously picked the correct answer).

Authenticate, Authorise WebApi with HttpClient

 

Hi all, I said I’d post this because I didn’t manage to find a suitable blog post or documentation indicating how to do this with the HttpClient (beta).  (bleeding edge again ey).

This post outlines how to create a simple test server that has a Json Logon endpoint.
Then it shows how to login with the .net 4.5 HttpClient class. Lots of other post I saw were trying to set Channels on this HttpClient, I’ll have to assume this was from the developer preview or the Wcf predecessor. It appears now the solution comes in the form of a HttpClientHandler!

It’s been a long day, up at 4am for a flight and then a long day at work, so lets cut to the chase…

Server

For setup, create a new MVC4 internet application

image

Why? because it gives me a AccountController with a JsonLogin action

image

Add a new ApiController

image

image

Add the Authorize attribute

image

Now we have a simple server setup for testing (no https etc, but lets not overcomplicate this just now).

Client

I just created a WPF client and called the following function on a button click.

private async void Login()
{
    var handler = new HttpClientHandler();
    CookieContainer cookieContainer = new CookieContainer();
    handler.CookieContainer = cookieContainer;
 
    var client = new System.Net.Http.HttpClient(handler);
 
    var content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        {"UserName", "brianbruff1"},
        {"Password", "password"}
    });
 
    var response = await client.PostAsync("http://localhost:2122/account/jsonlogin", content);
    response.EnsureSuccessStatusCode();
    var msg = await response.Content.ReadAsStringAsync();
 
    // just get the default value from the starter project
    response = await client.GetAsync("http://localhost:2122/api/values");
    response.EnsureSuccessStatusCode();
    var list = await response.Content.ReadAsAsync<List<string>>();
 
 
}

 

That’s it, next steps to clean up this code are all yours,  but hopefully I’ve helped someone out.
Remember to register the user the first time your run your MVC app, or your msg variable will indicate you couldn’t be logged on.


Remember to include Http.Formatters for the ReadAsAsync extension.

Brian.

Credit to @tomasmcguinness for pointing me in the right direciton (my other approach was to use PKI).
Credit to Microsoft for releasing the source so I could figure this out!

Deserializing Json

 

With this post I’m back to my lovely OneNote screen clippings, my last few postings were done on Windows8 and I’d no OneNote installed.

So you want to Deserialize Json in .NET! (C#)

How do you go about it?

There are a few approaches, many poeple are familiar with JSon.NET and using it like this

image

or

image

Some people may have done it the hard way

image

But if you add assembly System.Net.Http.Formatting.dll you’ll get a nice little extension ReadAsAsync<T>
http://msdn.microsoft.com/en-us/library/hh836073(v=vs.108).aspx

image

Enjoy!

ASP WebApi query single entity

 

What’s wrong with this?

 

   1:  public class UsersController : RavenController
   2:  {  
   3:      public User Get(int userId)
   4:      {
   5:          this.AutoSave = false;
   6:          var user = RavenSession.Load<User>(userId);
   7:          if (user == null)
   8:             throw new HttpResponseException("Unable to find user for it " + userId);
   9:          return user;
  10:      }
  11:   
  12:      // GET /api/values
  13:      public IQueryable<User> GetAll()
  14:      {
  15:          this.AutoSave = false;
  16:          return RavenSession.Query<User>();            
  17:      }        
  18:  }

The problem is the variable name used for getting a single user the function would never be called.

E.g. if we put http://localhost:65487/api/users/1 into our browser what will happen is the GetAll gets called!

What we need to call is

   1:  public class UsersController : RavenController
   2:  {  
   3:      public User Get(int id)
   4:      {
   5:          this.AutoSave = false;
   6:          var user = RavenSession.Load<User>(id);
   7:          if (user == null)
   8:              throw new HttpResponseException("Unable to find user for it " + id);
   9:          return user;
  10:      }
  11:   
  12:      // GET /api/values
  13:      public IQueryable<User> GetAll()
  14:      {
  15:          this.AutoSave = false;
  16:          return RavenSession.Query<User>();            
  17:      }        
  18:  }

Now you see that the Get takes a variable name of “id” this is key to getting this work.

 

Note: I’m using IQuerable as this allows me to add some query parameters to my request, e.g.

$filter
A Boolean expression for whether a particular entry should be included in the feed, e.g. Categories?$filter=CategoryName eq 'Produce'. The Query Expression section describes OData expressions.

$orderby
One or more comma-separated expressions with an optional “asc” (the default) or “desc” depending on the order you’d like the values sorted, e.g. Categories?$orderby=CategoryName desc.

$select
Limit the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description.

$skip
How many entries you’d like to skip, e.g. Categories?$skip=4.

$top-
Return entries from the top of the feed, e.g. Categories?$top=4

See MSDN for more options.

 

-- Updated Post --

Thanks to James Hancock for pointing this one out for me. This post is a little misleading in that the $select is currently not supported. Please see http://forums.asp.net/t/1771116.aspx/1?OData%20Support for more information on this. The other query string parameters listed above are supported.

Using RavenDb with Mvc WebApi

 

I’m starting this post with a disclaimer. I’m not a RavenDb expect, actually far from it, in fact I’ve only started working with it this evening!

I’m working on a pet project and getting the initial building blocks in place. I read about RavenDB in a recent edition of CODE magazine. The same magazine dealt with some other NoSql databases, e.g. Mongo Db, I’ve had a passing interest in NoSql in the last while so I wanted to get me a piece of the pie, and RavenDB jumped out at me for a few reasons.

  • Written in .NET
  • Scalability over RDBMS
  • RestAPI (although i won’t be using it, my app will have its own REST API using RavenDb managed api underneath)
  • .NET API with Linq querying
  • Automatic indexing
  • Scalability

    Create project

    Fire up visual studio and create an new MVC4 project

    Add the RavenDb package,

    Global.asax.cs

    Do the very same that is indicated on the Raven website, We need a single Document Store in our application.

     protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                            
                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
    
                BundleTable.Bundles.RegisterTemplateBundles();
    
                InitRaven();
            }
    
            private void InitRaven()
            {
                Store = new DocumentStore { ConnectionStringName = "RavenDB" };
                Store.Initialize();
    
                IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), Store);
    
            }
    
            public static DocumentStore Store;

    Create RavenController

    public abstract class RavenController : ApiController
        {
            public RavenController()
            {
                this.AutoSave = true;
                RavenSession = TickTockBaby.Mvc.WebApiApplication.Store.OpenSession();
            }
    
            public bool AutoSave { get; set; }
    
            public IDocumentSession RavenSession { get; protected set; }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (RavenSession != null)
                    {
                        using (RavenSession)
                        {
                            if (this.AutoSave)
                                RavenSession.SaveChanges();
                            RavenSession.Dispose();
                            RavenSession = null;
                        }
                    }
                }
    
                base.Dispose(disposing);
            } 
        }

    Let me explain what I’ve done here…

    I’ve initialized the session in the constructor, and cleaned it up in dispose, I also SaveChanges by default unless it gets switched off in a derived class.

     

    Derive from RavenController

    public class UsersController : RavenController
        {       
            // GET /api/values
            public IEnumerable<string> Get()
            {
                this.AutoSave = false;
                return RavenSession.Query<User>().Select(u => u.Name);            
            }        
        }

    That’s my initial attempt, hope it helps someone out a little.

    I’ll post my final solution possibly using Ninject DI after I’ve used RavenDb for a while and get a better feel for it.

    Raven Studio


    Check results in browser

    Vs11 Xml

     

    I’m working with an XML document all morning, and for the hell of it I decided to open in VS11.

    Guess what I found, some pretty cool xml/xsd/xslt support

     

    image

    but the biggest feature I found is the following…

    Paste XML as classes! BOOM!!

    image

    image

    Loving VS11…

    Linq DistinctBy

     

    Here is an extension method that I just had to share, TBH I’ve forgotten what I robbed the initial idea from, it wasn’t mine, but it’s something I found that I use over and over.

    The problem is I want to use the Distinct() extension method. However the objects I’m creating don’t override the default equality comparer, nor did I want to create a functor and supply to the overload just for this scenario.

    Lets have a look of what I’m dealing with.

    public class Source
    {
            
        public string Code { get; set; }    
        public string Name { get; set; }        
    }

    Here’s what one would initially try

    // Remove any duplicates
     c.DependingOnSources = c.DependingOnSources.Distinct();

    The problem here is that I don’t use the overload that allows me to specify an equality comparer, and the class itself doesn’t have the default equality comparer.

    So what’s the solution?

    var set = new HashSet<string>();
    c.DependingOnSources = c.DependingOnSources.Where(element => set.Add(element.Name));

     

    It’s a beauty it’s it, and quite simplistic, what I do is create a HashSet of the keys I want o compare, then I use use the Linq Where statement to select all the elements that I can add to the list. If you’re familiar with HashSet you’ll know that for first time we try add an element it will be not exist in the set and it gets added to the set and returns true, because the set.Add returns true.. we satisfy the Func in the Where clause and it gets added to the items that get returned.

     

    Simple ey.. yes true, but it gets better, we can make this a little more generic and leverage an extension method to do the lifting for us.

     

    internal static class LinqExtensions
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
                            this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));
        }
    }

     

    So now we can call our method like so

    // Remove any duplicates
    c.DependingOnSources = c.DependingOnSources.DistinctBy(k => k.Name);
     
    Neat ey! (another common method is to use GroupBy and Select.)

    Recent Tweets

    Note: For Customization and Configuration, CheckOut Recent Tweets Documentation

    Calendar

    <<  September 2017  >>
    MoTuWeThFrSaSu
    28293031123
    45678910
    11121314151617
    18192021222324
    2526272829301
    2345678

    View posts in large calendar

    Month List