Tuesday, March 18, 2014

Load MVC view to jquery color box

 

You can use the following set of code to load a MVC view to a jquery color box.

You can get more details on jquery colobox here.

HTML code

  1. <table cellpadding="0" cellspacing="0" border="0" class="display" id="ClientConfigurationList" style="width: 100%" >
  2.         <thead>
  3.             <tr>
  4.                              
  5.                 <th>Work Order No</th>
  6.                 <th>Work Order Status</th>
  7.                 <th>Created On</th>
  8.                 <th>Completed On</th>
  9.                 <th>Asset Description</th>
  10.             </tr>
  11.         </thead>
  12.         <tbody>
  13.             @foreach (var item in Model)
  14.             {
  15.                 <tr class="leftAlign">
  16.                                     
  17.                     <td>
  18.                            <a href="#DIV_WorkOrderDetailsContent"  onclick="new WorkOrderManagement().ViewWorkOrderDetails(@item.Id)" class="colorbox">@Html.DisplayFor(modelItem => item.WorkOrderNo)</a>
  19.                     </td>
  20.                     <td class="leftAlign">
  21.                         @Html.DisplayFor(modelItem => item.WorkOrderStatus)
  22.                     </td>
  23.                     <td>
  24.                         @Html.DisplayFor(modelItem => item.CreatedOn)
  25.                     </td>
  26.                     <td>
  27.                         @Html.DisplayFor(modelItem => item.CompletedOn)
  28.                     </td>
  29.                     <td>
  30.                         @Html.DisplayFor(modelItem => item.AssetDescription)
  31.                     </td>
  32.                 </tr>
  33.             }
  34.         </tbody>
  35.     </table>

 

Javascript Code

  1. this.ViewWorkOrderDetails = function (workOrderId) {
  2.     debugger;
  3.     $('#DIV_WorkOrderDetailsContent').html($("#DIV_WorkOrderDetailsLoadingMessage").html());
  4.     $('#DIV_WorkOrderDetailsContent').load("/Workorder/WorkOrderDetails?workOrderId=" + workOrderId, new function () { });
  5.  
  6.     $('.colorbox').colorbox({ inline: true, height: "80%", width: "50%" });
  7.  
  8. };

Happy Coding !!!!!!!!

Wednesday, March 12, 2014

Dynamically Load External JS , CSS file paths in webconfig

 

If you want to load JavaScript paths or CSS paths saved in web config app settings you can use the following solution.

Step 1:

Create a API controller method which will return the appsettings

  1. public class ConfigurationController : ApiController
  2.  {
  3.   
  4.      [HttpGet]
  5.       public string LoadSettings(Domain.Entities.Configuration model)
  6.  {
  7.      string value = ConfigurationManager.AppSettings.Get(model.Key);
  8.      return value;
  9.  }
  10.  }

 

Step 2:

Create a javascript function which will load javascript or css paths dynamically.

  1. function loadjscssfile(filename, filetype) {
  2.       if (filetype == "js") { //if filename is a external JavaScript file
  3.           var fileref = document.createElement('script');
  4.           fileref.setAttribute("type", "text/javascript");
  5.           fileref.setAttribute("src", filename);
  6.       }
  7.       else if (filetype == "css") { //if filename is an external CSS file
  8.           var fileref = document.createElement("link");
  9.           fileref.setAttribute("rel", "stylesheet");
  10.           fileref.setAttribute("type", "text/css");
  11.           fileref.setAttribute("href", filename);
  12.       }
  13.       if (typeof fileref != "undefined")
  14.           document.getElementsByTagName("head")[0].appendChild(fileref);
  15.   }

 

Step 3:

Create javascript function to call that Api method and call that function on page load.

  1. function loadFiles() {
  2.     debugger;
  3.     var configuration = {
  4.         Key: "IdentityProviderScriptPath"
  5.  
  6.     };
  7.  
  8.  
  9.     $.ajax({
  10.  
  11.         url: "../Api/Configuration/LoadSettings" + productName,
  12.         //data: { name: productName },
  13.         type: "GET",
  14.         dataType: "jsonp",
  15.         error: function (request, status, error) {
  16.             alert(request.responseText);
  17.         },
  18.         success: function (path) {
  19.             loadjscssfile(path, "js");
  20.         }
  21.     });
  22.  
  23.     
  24.  
  25. }

 

  1. <body onload="loadScriptFiles();">

Happy Coding

Validating Username, password and timestamp in WCF

 

Recently I have got an requirement which is to validate username, password and timestamp set in the message header in each call made to WCF.

Following is the solution I came Up with.

 

Validating Username and Password

 

Step 1:

Create a wshttpbinding and add the following configuration.

  1. <wsHttpBinding>
  2.     <binding name="wsHttpBinding" closeTimeout="00:00:10" openTimeout="00:00:10" receiveTimeout="00:00:10" sendTimeout="00:00:10">
  3.       <security mode="Message">
  4.         <message clientCredentialType="UserName" />
  5.       </security>
  6.     </binding>
  7.   </wsHttpBinding>

 

Step 2:

Create a custom username and password validator as below

  1. public class UserValidator : UserNamePasswordValidator
  2.   {
  3.       public override void Validate(string userName, string password)
  4.       {
  5.           if (null == userName || null == password)
  6.           {
  7.               throw new ArgumentNullException();
  8.           }
  9.  
  10.  
  11.           // your validation logic comes under here
  12.          if(!ValidateUser(userName,password))
  13.              throw new FaultException("Invalid username or password");
  14.  
  15.       }
  16.  
  17.      
  18.   }

 

Step 3

Add the following configuration section.

  1. <behaviors>
  2.   <serviceBehaviors>
  3.     <behavior name="ServiceBehavior">
  4.       <serviceMetadata httpGetEnabled="true" />
  5.       <serviceDebug includeExceptionDetailInFaults="false" />
  6.       <serviceCredentials>
  7.         <serviceCertificate findValue="0789B7C8F0018E869EA9DB95B208BFB0C3449A3D"
  8.           x509FindType="FindByThumbprint" />
  9.         <userNameAuthentication userNamePasswordValidationMode="Custom"
  10.           customUserNamePasswordValidatorType="WcfService.MobilityIntegrationService.UserValidator, WcfService.MobilityIntegrationService" />
  11.       </serviceCredentials>
  12.     </behavior>
  13.   </serviceBehaviors>
  14. </behaviors>

 

Validating Timestamp

  1. public class TimeStampValidator
  2.   {
  3.       public void ValidateTimeStamp()
  4.       {
  5.  
  6.           string ns = HybridConfig.GetAppSetting("MessageNamespace");
  7.           int timespanExpiry =-Convert.ToInt32( HybridConfig.GetAppSetting("TimestampExpiry"));
  8.           int i = OperationContext.Current.IncomingMessageHeaders.FindHeader("Timestamp", ns);
  9.  
  10.           //If timestamp is not set in the header
  11.           if(i==-1)
  12.                 throw new FaultException("Invalid Request.Timestamp is not set");
  13.           
  14.           string timestamp = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(i);
  15.  
  16.           //if timestamp header doesnot contain any data
  17.           if (string.IsNullOrEmpty(timestamp))
  18.               throw new FaultException("Invalid Request.Timestamp is not set");
  19.  
  20.           DateTime timeStampValue = Convert.ToDateTime(timestamp);
  21.  
  22.           if (DateTime.UtcNow.AddSeconds(timespanExpiry) > timeStampValue)
  23.                 throw new FaultException("Invalid Request.Timestamp is expired");
  24.  
  25.  
  26.          
  27.       }
  28.  
  29.       
  30.   }

 

Hope this would help.

Happy Coding !!!

Tuesday, March 4, 2014

OData in WebApi 2

 

Web API 2 comes with OData query support. It supports the following query options for webAPI client applications to customize the result set returned by the API based on there requirement.

Option Description
$expand Expands related entities inline.
$value Gets the raw value of a property.
$filter Filters the results, based on a Boolean condition.
$inlinecount Tells the server to include the total count of matching entities in the response. (Useful for server-side paging.)
$orderby Sorts the results.
$select Selects which properties to include in the response.
$skip Skips the first n results.
$top Returns only the first n the results.

 

To use OData queries you need to enable it globally, controller or specific action level.

Enable Globally

1. In you MVC project go to App_Start folder

2. There you can find the WebApiConfig.Cs

3. In there add the following code.

  1. public static void Register(HttpConfiguration config)
  2.    {
  3.        config.EnableQuerySupport();
  4.    }

 

Enable Controller Level

  1.  
  2. [Queryable]
  3. public class EmployeeController : ApiController
  4. {

 

Enable Action Level

  1. [Queryable]
  2.         public IEnumerable<string> Get()
  3.         {
  4.             return new string[] { "value1", "value2" };
  5.         }

lets see examples of each option one by one. We will consider the following model for explaining the queries.

  1. public class Employee
  2.     {
  3.         [Key]
  4.         public int Id { get; set; }
  5.         public string Name { get; set; }
  6.         public int Age { get; set; }
  7.         public string Gender { get; set; }
  8.         public string Address { get; set; }
  9.         public string Mobile { get; set; }
  10.         public virtual ICollection<Leave> Leaves { get; set; }
  11.  
  12.     }
  13.     public class Leave
  14.     {
  15.         [Key]
  16.         public int Id { get; set; }
  17.         public string Reason { get; set; }
  18.         [ForeignKey("LeaveType")]
  19.         public int LeaveTypeId { get; set; }
  20.         public LeaveType Leavetype { get; set; }
  21.     }
  22.  
  23.     public class LeaveType
  24.     {
  25.         [Key]
  26.         public int Id { get; set; }
  27.         public string Name { get; set; }
  28.  
  29.     }

 

$expand

Suppose you want to get employee details with all the leave records for each employee then you can use expand query as below.

http://localhost/odata/Employees?$expand=Leaves

In case if you want to get the Leave type details you can add the the related entities you want to expand comma separated in the query as below.

http://localhost/odata/Employees?$expand=Leaves,LeaveType

By default Web API support expansion to 2 levels. You can override it as below.

  1. [Queryable(MaxExpansionDepth = 4)]
  2.      public IQueryable<Employee> GetEmployees()
  3.      {
  4.          return db.Employees;
  5.      }

 

$select

If you need to select only the Name and Age of the employee or a subset of properties of an entity you can use $select for that as below.

http://localhost/odata/Employees?$select=Name,Age

You can also use this to select properties of an expanded entity as below. This selects name and age from Employee and Name from leaves

http://localhost/odata/Employees?$expand=Leaves&$select=Name,Age,Leaves/Name

$value

This will return raw value of property without JSON

http://localhost/odata/Employees(1)/Name/$value

$filter

You can use Boolean expressions to filter your API results using this query type.

Return all employees with gender equal to “Male”. http://localhost/Employees?$filter=Gender eq 'Male'
Return all employees who’s age is below 30. http://localhost/Employees?$filter=Age lt 30
Logical operators: employees who’s age is between 20-30 http://localhost/Employees?$filter=Age ge 20 and Age le 20
String functions: Return all employees with name “john” http://localhost/Employees?$filter=substringof('john',Name)

 

 

$orderby

This is used to sort the result set.

Sort by Age. http://localhost/Employees?$orderby=Age
Sort by Age in descending order (highest to lowest). http://localhost/Employees?$orderby=Age desc

 

$skip & $top

This is used when you have millions of records in your database and when you need paging in client side.

http://localhost/Employees?$top=10&$skip=20

The $top option gives the maximum number of entries to return, and the $skip option gives the number of entries to skip. The previous example fetches entries 21 through 30.

Hope this helps you.

 

Happy Coding !!!!!