Monday, February 8, 2016

Pattern for Consuming REST Services (ASP.NET Web API) from a .NET Client (Using HttpClient)

Pattern for Consuming REST Services (ASP.NET Web API) from a .NET Client (Using HttpClient)


RESTful Service Server-Side is the most common feature in Micro-services software architecture. It would be best to design a pattern to consume data so that we can use this for any RESTful Service. 

For Simplicity, In this article  I have used .Net client application which is consume movie data from OMDB API http://www.omdbapi.com/


BaseClient Class 

First, We need to define the base client class which provides a generic interface to deserialize the data from given API URL. Notice that the Main Extarcting data function as an async method named ExtractDataFromAPI and then await until it completes. Many of the HttpClient methods are async, because they perform network I/O.

  
 public class BaseClient  
   {  
     protected readonly UriBuilder _uriBuilder;  
     protected readonly string _endpoint;  
     public BaseClient(string endpoint)  
     {  
       _endpoint = endpoint;  
       _uriBuilder = new UriBuilder(_endpoint);  
     }  
     protected async Task<T> ExtractDataFromAPI<T>(string queryString)  
     {  
       using (var httpClient = new HttpClient())  
       {  
         _uriBuilder.Query = queryString;  
         HttpResponseMessage response = await httpClient.GetAsync(_uriBuilder.ToString());  
         using (HttpContent content = response.Content)  
         {  
           string result = await content.ReadAsStringAsync();  
           return JsonConvert.DeserializeObject<T>(result);  
         }  
       }  
     }  
   }  


Implement Omdb Client

So, Lets Implement all the client services which inherits from Base Client. To implement base client we need to pass constructor parameter called endpoint as API Base URL here. Also to retrieve data from ExtractDataFromAPI, need to pass query string.

For example http://www.omdbapi.com/?s=bat&r=json
end point -  http://www.omdbapi.com/  
query string - ?s=bat&r=json


  public class OmdbRequestService : BaseClient, IOmdbRequestService  
   {  
     // Also we can keep this api string web config App setting   
     public const string omdbUrl = "http://www.omdbapi.com/?";  
     public OmdbRequestService()  
       : base(omdbUrl)  
     {  
     }  
     // Omdb Request goes here  
     // Created some request like SearchMovie, GetMovieByIMDBId, GetMovieByTitle  
     // We can create more in future Example - GetMovieByIMDBIdAndYear, GetMovieByTitleAndPlot, etc  
     public Task<MovieSearchList> SearchMovie(string search)  
     {  
       // async method, client can use await  
       // query string builded from OmdbQueryBuilder  
       return ExtractDataFromAPI<MovieSearchList>(OmdbQueryBuilder.QueryBySearchDataTypeJson(search));  
     }  
     public Task<Movie> GetMovieByIMDBId(string imdbID)  
     {  
       return ExtractDataFromAPI<Movie>(OmdbQueryBuilder.QueryByImdbIdDataTypeJson(imdbID));  
     }  
     public Task<Movie> GetMovieByTitle(string title)  
     {  
       return ExtractDataFromAPI<Movie>(OmdbQueryBuilder.QueryByTitleDataTypeJson(title));  
     }  
   }  

Here, I created a small OmdbQueryBuilder static class to build query strings. It is simple


 // Build QueryString for Url  
   // Future - Refactor this with NameValueCollection  
   public static class OmdbQueryBuilder  
   {  
     private const string SEARCH= "s";  
     private const string TITLE = "t";  
     private const string IMDB_ID = "i";  
     private const string DATA_TYPE= "r";  
     private const string JSON= "json";  
     private const string XML = "xml";  
     public static string QueryBySearchDataTypeJson(string search)  
     {  
       return SEARCH + "=" + search + "&" + DATA_TYPE + "=" + JSON;  
     }  
     public static string QueryByImdbIdDataTypeJson(string imdbId)  
     {  
       return IMDB_ID + "=" + imdbId + "&" + DATA_TYPE + "=" + JSON;  
     }  
     public static string QueryByTitleDataTypeJson(string title)  
     {  
       return TITLE + "=" + title + "&" + DATA_TYPE + "=" + JSON;  
     }  
   }  

Complete Code Example

Here is the GitHub Link (https://github.com/jayakaran1987/Consuming-RESTful-Service-HttpClient) for complete code for this article. It is an implemented web application that makes use of http://www.omdbapi.com/ API that performs the following:

  1. Allow the user to search for any movie(s) they want.
  2. Search results are presented in a grid/table format
I have used the following Technology Stack

  - C# and .NET MVC for a web application
  - AngularJS
  - Telerik/Kendo Controls
  - HTML 5 , Javascript & Jquery
  - Bootstrap

Wednesday, December 17, 2014

Progress bar for long running server calls in ASP.Net MVC

Progress bar for long running server calls in ASP.Net MVC


Last I faced to fix an issue to create client side progress bar for long running server side call. so the way I thought to fix this issue as Producer Consumer Approach. Normally Producer updates the results and Consumer will poll the results and display in a J query progress bar. Then I found the Microsoft SignalR library is the most easiest way to fix this issue. Normally we can use this library to chat applications also.

First need to download SignalR using nuget,
https://www.nuget.org/packages/Microsoft.AspNet.SignalR/2.1.2


Second Step, 

Create folder named as hubs in your project directory. 

Create two classes inside hubs folder, 

Startup.cs
using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}
ProgressHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace RealTimeProgressBar
{
    public class ProgressHub : Hub
    {

        public static void SendMessage(string msg , int count)
        {
            var message = "Process completed for " + msg;
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
            hubContext.Clients.All.sendMessage(string.Format(message), count);
        }
    }
}

Now in long running controller action, we need to update / send the progress to client action.

In controller,
// assembly
using Microsoft.AspNet.SignalR;
using RealTimeProgressBar;   
//call this method inside your working action
ProgressHub.SendMessage("initializing and preparing",  2);

// View, establishing the connection to server and updating the view
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.--> 

function StartInvoicing()
{
    var progressNotifier = $.connection.progressHub;

    // client-side sendMessage function that will be called from the server-side
    progressNotifier.client.sendMessage = function (message, count) {
        // update progress
        UpdateProgress(message, count);
        //alert(message);
    };

    // establish the connection to the server and start server-side operation
    $.connection.hub.start().done(function () {
        // call the method CallLongOperation defined in the Hub
        progressNotifier.server.getCountAndMessage();
    });
}

// Using kendo progress bar to update view

 function UpdateProgress(message, count) {
        var result = $("#result");
        result.html(message);
        $("#progressBar").data("kendoProgressBar").value(count);
    }

Instead of kendo progress bar you can use some jquery progress bars to update this percentage.








Saturday, May 24, 2014

Handling complex view models in Razor in Asp.Net MVC

Sometimes we all face some difficulties while handling some complex view models in mvc. Most of them are happens while passing view model back to controller form razor view. Following example describes some clear information regarding complex model binding

Here is my complex model,

namespace FEWO.Web.Models
{
    public class PriceModel
    {
        public Guid Id { get; set; }
        public Guid SeasonTimesId { get; set; }
        public Guid CategoryId { get; set; }
        public Guid PercentageId { get; set; }
        public Guid PriceTypeId { get; set; }
        public decimal Value { get; set; }

        public virtual Category Category { get; set; }
        public virtual Percentage Percentage { get; set; }
        public virtual Price_Type Price_Type { get; set; }
        public virtual SeasonTime SeasonTime { get; set; }
    }

    public class GroupedPriceModelBySeasonTime
    {
        public string GroupName { get; set; }
        public List<PriceModel> PriceModelList { get; set; }
    }

      public class HolidayComplexPriceModel
    {
        public Guid HolidayComplexId { get; set; }
        public string Year { get; set; }
        public List<GroupedModelBySeasonTime> SeasonTimeGroupedModel { get; set; }
    }
}


Here I want to pass the HolidayComplexPriceModel to the view from action method. In action method i will bind this view model a follows

List<PriceModel> priceViewModel  = _repo.GetPriceModelList();
List<GroupedModelBySeasonTime> gmodel = new List<GroupedModelBySeasonTime>();
foreach (var item in priceViewModel.GroupBy(con => con.SeasonTimesId).ToList())
   {
        GroupedModelBySeasonTime  m = new GroupedModelBySeasonTime();
         m.GroupName = item.ElementAt(0).SeasonTime.Season_Shortcut
         List<PriceModel> pmodel = new List<PriceModel>();
                foreach (var items in item.OrderBy(con => con.Category.Category_Name))
                 {
                    pmodel.Add(items);
                  }
          m.PriceModelList = pmodel;
          gmodel.Add(m);
    }

return new HolidayComplexPriceModel(){ SeasonTimeGroupedModel  = gmodel }

Following are the important tips, what are the usual mistakes we might do in razor,

1. Dont use any foreach loop to bind the view model, use for loop

    Ex -
 @using (Html.BeginForm("Index", "Price", FormMethod.Post, new { enctype = "multipart/form-data",
  id = "SavePrice" }))
   {
    foreach(var item in Model.SeasonTimeGroupedModel) {}
   // if you use foreach then you might bind element like  item.Id, then razor viewmodel didnot realize the  model    property. So need to bind like this, Model.SeasonTimeGroupedModel[0].Id

    Use simple for loop like below,
  for (int i = 0; i < Model.SeasonTimeGroupedModel.Count; i++) {}
  }

2. Dont do any grouping in view, do the gruoping in controller action. If grouping happens in view,
    ex- var groupList = Model.ExampleList.Group(x => x.Id);  then you need to bind elements like below
    @Html.TextBoxFor(model => groupList.Name) then Razor didnot realize the model property.

3. Using nested for loops,
     @for (int i = 0; i < Model.SeasonTimeGroupedModel.Count; i++)
        {
                  Model.SeasonTimeGroupedModel[i].GroupName
                  for (int e = 0; e < Model.SeasonTimeGroupedModel[i].PriceModelList.Count; e++)
                   {
                    Html.TextBoxFor(model => Model.SeasonTimeGroupedModel[i].PriceModelList[e].Value)
                   }
        }

4. Dont use any action link to post complex view model. It is clear that action link wont post complex      model. if you want to use multiple post in single view then use multiple submits
 Example
  <input type="submit"  name="submitbutton1" value="submit1" />
  <input type="submit"  name="submitbutton2" value="submit2" />

   In controller action differentiate both by
   if (Request.Form["submitbutton1"] != null)
    {
     // Submit button 1 function goes in here
    }
    if (Request.Form["submitbutton2"] != null)
    {
     // Submit button 2 function goes in here
    }

Cool. Those are some few tips from me to keep coding happily, Enjoy :)

Monday, March 4, 2013

14 hive directory structure in SharePoint 2010

In this post I will list down some important directories or folders used with SharePoint 2010 server. The 14 hive is located under "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14". If you explore the 14 hive you would see below folder structure.























Lets Start with some directories which are related to SharePoint 2010 installation,Configration and its files,
  • C:\Inetpub\wwwroot\wss - Directory for default location of IIS SharePoint websites
  • C:\ProgramFiles\Microsoft Office Servers\14.0 - default installation directory for SharePoint 2010 binaries and data.
Frequent usable 14 Hive directory folders are as follow,

ADMISAPI
Contains the soap services for Sharepoint 2010 Central Administration
CONFIG
Contains files used to extend IIS Web sites with SharePoint Server
Help
Contains Html Help file used by configuration wizard
ISAPI
Contains all the standard Web Services for SharePoint and some additional DLL’s, resources and configuration files that the web services use
LOGS
Contains all SharePoint related logs will see. This is important when any problem or error occur in SharePoint you have to trace the logs files in this folder to get the error message
TEMPLATE
Contains the core web site functionality like the features, templates, configurations, resources of a web site
WebServices
Contains where the SharePoint back-end Web services are hosted, for example, Excel and Search


Following files are undergo with appropriate directories listed down,

ascx in web part/user controls 
14\TEMPLATE\CONTROLTEMPLATES\ProjectNamespace\usercontrols.nameUserControl

aspx in master pages - 14\TEMPLATE\LAYOUTS. 
Identical copies in  14\TEMPLATE\GLOBAL

      css in master page - 14\TEMPLATE\LAYOUTS\1033\STYLES\     OR 14\TEMPLATE\LAYOUTS\1033\STYLES\Themable

         js in master page  - 14\TEMPLATE\LAYOUTS\1033

      css in webpart styling - 14\TEMPLATE\LAYOUTS\STYLES

            js in webpart scripting  - 14\TEMPLATE\LAYOUTS\

        feature.xml in a feature - 14\TEMPLATE\FEATURES\FeatureName\ 
     
      dll in custom assembly -14\BIN\
     
      xslt in ItemStyle14\TEMPLATE\LAYOUTS\XSL


Enjoy !


Thursday, January 31, 2013

Connecting Visual Web Parts programmatically  

Visual web parts allow developers to easily design the user interface as they are doing in conventional ASP.Net applications. The main advantage of connected Web Parts is to exchange data between web parts at run time. Here we are going to use two visual web parts one is called Tags as provider web part and other one is called Items as  consumer web part.

Tags web part retrieve all the items from tag list. Tags list have two columns which are tag and connection which is shown below


Items web part which is act as filtering web part to retrieve filtering items from Items List. Item List is shown below.
Now,  When we click tag from item web part, particular connection for the selected tag should pass to the items web part and filtered from Item A and Item B. For this first I m going to create tags web part to get all tags and connection properties from Tags List. (Note - Bind all the tags in link button and pass connections as command argument of this link button in Grid View ). Tags Webpart is shown below

Interface 
Now lets set the connection provider attribute to Tags web part. First define the Interface that will specify the data we wanted pass or exchange from one web part to another web part.

    public interface ITagString
    {
        string TagString { get; set; }
    }

Tag web part - Provider web part
Now in the Tag web part class, you need to implement the TagString property which is a string as you defined in the Interface. Actually the webpart will load the user control to its control collection in the CreateChildControls. 

1- Implement the ItagString Interface
2- Implement the get and set methods of the TagString property of ITagString Interface
3- ConnectionProvider property after the CreateChildControls subroutine. which will expose the interfacing  data to the Consumer web part.

Here you can pass the connection string using Link button command events

Items web part - Consumer web part
In the Item web part , create an object for Interface “ITagString”. The purpose of this variable is to receive/consume data from the other web part. So you can create a web part variable in user control and a user control variable in the web part code and inside CreateChildControls method, assign the web part variable 

1. User control variable to pass the value to ItemsUserControl class
2. Method will get the Interface ref and returns the value passed by provider web part

Now filter the Item list based on this parameter.
1- Reference from Items web part class
2- Label to print passed parameter
3- Filter the Items list based on parameter

Configure the web parts to enable connection (After deployed)
Following steps are shown how to enable the connection from tag web part and items web part.
When you are done, you will end up with 2 web parts on a web parts page that will communicate with each other as you make click on tags.
Enjoy!


Friday, January 4, 2013


SharePoint Application Development Life Cycle

SharePoint Application Development Life Cycle is the basic concept for every share Point developer. The SharePoint Application development has some additional important methodologies when compared with the usual software project life cycle.

SharePoint Development Life Cycle Process

  •  Capture Business Requirements
  • Solution Architecture
  • Development and Build
  • Testing
  • Quality Assurance
  • Deployment


Capturing  Business Requirements in SharePoint Projects
The SharePoint Business Analyst will work directly with business users to document requirements, analyze business problems and implement solutions. This requirement capturing process mainly covers, requirements elicitation, analyzing requirements, validating requirements,documenting requirements.

How does it happen ?
  • Conduct an analysis of the existing SharePoint systems to ensure all functional requirements are understood and captured
  • Using wireframes and UI mockups for describing business processes and expected functional modules
  • Verifying all SharePoint procedures and limitations
  • Educate stakeholders in SharePoint
  • Document validated requirements, improvements and issues

Solution Architecture
The Solution architect is the most important role in the SharePoint Project Life cycle because he defines the structure of the ‘Solution Design ’of the Project. In this phase reference Architecture, reference implementations and tools for faster development of prototypes are defined

How does it happen ?
  • Information Artifacts – (define data flow, use cases and managing artifacts)
  • Information Architecture
o   How to organize the information in SharePoint Projects
o   Governance (Ownership, Retrieval and Security)
o   Contents and content types
o   Navigation and meta data
o   Users
o   Look and feel / SharePoint branding/Search
  • Logical Architecture
o   Which features will be used and for what
o   Logical design of proposed solution
o   Service levels and administrative policies
  • Capacity planning and physical architecture (network Requirements and storage managements)


Approaches in Development and Build
The term “SharePoint Development” always brings up some difficult discussions when combined  with “Developers” who use Visual Studio, write managed code (C#/VB.NET) and “Developers” who use SharePoint Designer and write client side code (HTML/JavaScript/XSLT) to build their applications. Essentially these are both forms of SharePoint Development.

How does it happen ?
  • Analysis, design, development, and deployment in SharePoint
  • Conformance to the coding guidelines
  • Team development
  • Standalone development environment
  • Shared development SharePoint Server
  • Team Foundation Server

Approaches to Testing and Quality Assurance
Since SharePoint is a collaborative platform due to the wide range of rich features, configuration options and the functionalities it provides, it becomes obligatory to test and track applications with systematic understanding in terms of functionality, usability, security, performance and various platform layers.

How does it happen ?
  • Build Test Environment
  • Use Test Tools and Automated Testing
  • Use Mocking Frameworks
  • Unit Tests and UI Tests
  • User Experience
  • Quality testing in each phases
Deployment
Deployment is the final step of the entire SharePoint Project Life cycle.
  • Standardize deployment
  • Deployment using Power shells