Thursday, April 10, 2014

Get Controls by ID

 

I have recently come across a requirement in one of the webform asp.net project where we wanted to get the controls by ID rather accessing the control object it self. Following is the solution we came up with.

I wrote a generic method which will search and return the control.

 

  1. private T GetControl<T>(string controlName, int tabIndex ,Control parentControl)
  2.              where T : Control
  3.  
  4.         {
  5.             string name = controlName + "_TabPanel" + tabIndex.ToString();
  6.             Control control = parentControl == null ? FindControl(name) : parentControl.FindControl(name);
  7.  
  8.  
  9.             return (T)control;
  10.         }

Following is the code where we use the method.

  1. GetControl<TextBox>("tbNewForecast", selectedTabIndex, ForecastTab.ActiveTab).Text = "";

 

Hope this helps you.

Happy Coding !!!!

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 !!!!!

Friday, February 28, 2014

Enum Support in MVC 5.1

 

Enum support for MVC views is a new feature introduced in Asp.net MVC 5.1. If you have Enum in your model view will create a dropdown list or radio button list in the view for you.

See the example below.

Model
  1. public class MyData
  2.     {
  3.         public int Id { get; set; }
  4.  
  5.         public MyEnum Enum1 { get; set; }
  6.  
  7.         public MyEnum? Enum2 { get; set; }
  8.  
  9.         public FlagsEnum FlagsEnum { get; set; }
  10.     }

 

Enum as Dropdown List

 

  1. <div class="form-group">
  2.          @Html.LabelFor(model => model.Enum1, new { @class = "control-label col-md-2" })
  3.          <div class="col-md-10">
  4.              @Html.EditorFor(model => model.Enum1)
  5.              @Html.ValidationMessageFor(model => model.Enum1)
  6.          </div>
  7.      </div>
  8.  
  9.      <div class="form-group">
  10.          @Html.LabelFor(model => model.Enum2, new { @class = "control-label col-md-2" })
  11.          <div class="col-md-10">
  12.              @Html.EditorFor(model => model.Enum2)
  13.              @Html.ValidationMessageFor(model => model.Enum2)
  14.          </div>
  15.      </div>

Following shows the how view renders. As you can see as Enum2 member is nullable it does not have any value selected by default.

image

Enum as Radio button List

 

  1. <div class="form-group">
  2.           @Html.LabelFor(model => model.Enum1, new { @class = "control-label col-md-2" })
  3.           <div class="col-md-10">
  4.               @Html.EditorFor(model => model.Enum1, templateName: "Enum-radio")
  5.               @Html.ValidationMessageFor(model => model.Enum1)
  6.           </div>
  7.       </div>
  8.  
  9.       <div class="form-group">
  10.           @Html.LabelFor(model => model.Enum2, new { @class = "control-label col-md-2" })
  11.           <div class="col-md-10">
  12.               @Html.EditorFor(model => model.Enum2, templateName: "Enum-radio")
  13.               @Html.ValidationMessageFor(model => model.Enum2)
  14.           </div>
  15.       </div>
 

image

Happy Coding !!!!!!!!!!

Thursday, February 27, 2014

TestCase Attribute (NUnit 2.5)


Have you ever thought how easy would it be if we could pass parameters and expected result to a Unit Test method we have rather writing multiple test methods.
It is possible now with NUnit 2.5 “TestCase” Attribute.

Suppose you have a method to test whether a year is a leap year or not which you want to test by passing different values here is the solution.
 
        [TestCase(2000, Result = true)]
        [TestCase(1996, Result = true)]
        [TestCase(2013, Result = false)]
        public bool IsLeapYearTest(int year)
        {
            return DateTime.IsLeapYear(year);
        }
and if you want to pass multiple parameters just add them comma seperated as below example.
   
        [TestCase(12, 3, Result = 4)]
        [TestCase(12, 2, Result = 6)]
        [TestCase(12, 4, Result = 3)]
        public int DivideTest(int n, int d)
        {
            return (n / d);
        }

This helps us to provide test methods with parameters as well as providing inline date to be used when invoking that method.

Happy Coding