Sunday, May 17, 2015

Thursday, May 14, 2015

Prevent automatic hyperlinks in Email notifications in your code

Sometimes you want to send an email notification from your web application or any system that has a website address to be displayed as plain text when you view it on an email client such as Outlook, G-mail, etc. But nowadays, the email clients are so intelligent that even if you send a website address, email address, etc as plain text, they will be converted to links.

Therefore, in order to avoid email clients automatically making hyperlinks, you have to change the pattern but display the same.

I came across some findings to include a white-space character in the link text but not displayed to the user using the html code ​ to include white-space as follows.

www.google.com has to be written as www.google.&#8203com so that the email client will not identify this as a link, still there will not be difference when displaying it.

<p>Check out at www.google.&#8203com</p>

will be displayed as;
Check out at www.google.​com

Define Display Labels as attributes in BE class in C#

Assume that in your BE class you have certain properties to match with table fields. I want to expose descriptive name for each of these properties. for example to show it as column header in grid.
For example, there is a property called FirstName. I want to expose it's descriptive name as First Name
in BE define this.
[DisplayName("First Name"), Description("First Name of the Member")]
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value; }
}
You can read these details of each property as below;
PropertyDescriptorCollection propertiesCol = TypeDescriptor.GetProperties(objectBE);

PropertyDescriptor property;

for (int i = 0; i < propertiesCol.Count; i++)
{
    property = TypeDescriptor.GetProperties(objectBE)[i];

    /*
    // Access the Property Name, Display Name and Description as follows
    property.Name          // Returns "FirstName"
    property.DisplayName   // Returns "First Name"
    property.Description   // Returns "First Name of the Member"
    */
}
* where objectBE is the object instance of BE class.

WCF GET URL Length Limit Issue: Bad Request - Invalid URL

I tried to access a WCF Service through jQuery AJAX call with GET method. So, sometimes the URL is lengthy with parameters.
When the parameters becomes so lengthy, jQuery AJAX Call fails, and returns nothing. So I put a break point and took the URL out to test. When I try the same URL in the browser (I tried FireFox and Chrome), it returns the following when the URL length is too long.
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
I checked the length limitation as well. When the number of characters in the URL (in encoded format) exceeds 1011 characters (including http://) only I get the error.
I tried POST method, but I don't know I could not make it work. Because it needs some web.config changes.
My Parameters are set of Json Objects. I don't think any of the characters cause the problem, because, if I just reduce few alpha numeric characters to less than the limit, it works.
I'm running my application in Visual Studio 2012 Premium in Windows 8 Professional, so it's .NET 4.5 and IIS Express Came with it.
Further Research
When I try to investigate this further, this is not the limitation I have already mentioned which is the length of full url. But, there is a limitation of length in each parameter which is 260 characters.
So, I'm not sure about URL total length, but each parameter (seperated by "/") has the limit. The problem with the above URL which I have posted is Email Address JSON parameter is 261 characters long, given below.
SOLUTION
I Found a solution which worked for me, when I research further on this.
There is an IIS Setting
The problem is because, the default character limit of each parameter in REST url is 260 which is defined in the registry.
So, you have to update the registry to increase this size limit where the IIS Server / IIS Express is running.
Following is the location of Registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters
And the value name is UrlSegmentMaxLength. If it is not there, create one with Type of REG_DWORD. And specify a higher value for value data such as 1000 in hexadecimal or 4096 in decimal.
This is a http.sys setting. More about http.sys settings : http://support.microsoft.com/kb/820129
Make sure, you restart the server/machine to apply the registry changes. And that's it.

Basic Auditing in MySQL

Introduction

Keeping track of a record about the time it was created and the time it was last updated, may be important when you want that information.
This document explains how to implement this in any of the given table.

Implementation

There are two ways of implementing this in the database table. First method is to use ALTER TABLE and TRIGGER. The other method is to define in the ALTER TABLE itself. The second method will only work in MySQL 5.6.5 and later versions.
Before following the steps below, make sure you are selected the correct database and make sure the column names you use for created time and modified time do not already exists in the table.

Method 1

ALTER TABLE tblname
ADD COLUMN modifiedtime TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
ADD COLUMN createdtime DATETIME;

DELIMITER //
DROP TRIGGER IF EXISTS tblname_insert_trigger//
CREATE TRIGGER tblname_insert_trigger
BEFORE INSERT ON tblname
FOR EACH ROW
BEGIN
IF NEW.CreatedTime = '0000-00-00 00:00:00' THEN
SET NEW.CreatedTime = NOW();
END IF;
END;//
DELIMITER ;

Method 2

This method will only work in MySQL 5.6.5 and later versions.
ALTER TABLE tblname
ADD COLUMN modifiedtime TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
ADD COLUMN createdtime DATETIME NULL DEFAULT CURRENT_TIMESTAMP;

Update Existing Records

If you want to keep existing records’ audit fields as null to differentiate that those records were created and modified before implementing audit fields, execute the following statements just after the above steps.
SET SQL_SAFE_UPDATES = 0;  -- bypass the workbench safe mode, if you need
UPDATE tblname SET modifiedtime = null, createdtime = null;

References

1.       Automatic Create and Modified timestamps in MySQL
https://www.marcus-povey.co.uk/2013/03/11/automatic-create-and-modified-timestamps-in-mysql
2.       Having both a Created and Last Updated timestamp columns in MySQL 4.0
http://stackoverflow.com/a/267675/1931848

Wednesday, May 13, 2015

jQuery Datatables server-side pagination in ASP.NET MVC with Entity Framework

In order to capture datatable events we need to create a class as follows;

   /// <summary>  
   /// Class that encapsulates most common parameters sent by DataTables plugin  
   /// </summary>  
   public class jQueryDataTableParams  
   {  
     /// <summary>  
     /// Request sequence number sent by DataTable,  
     /// same value must be returned in response  
     /// </summary>      
     public string sEcho { get; set; }  
     /// <summary>  
     /// Text used for filtering  
     /// </summary>  
     public string sSearch { get; set; }  
     /// <summary>  
     /// Number of records that should be shown in table  
     /// </summary>  
     public int iDisplayLength { get; set; }  
     /// <summary>  
     /// First record that should be shown(used for paging)  
     /// </summary>  
     public int iDisplayStart { get; set; }  
     /// <summary>  
     /// Number of columns in table  
     /// </summary>  
     public int iColumns { get; set; }  
     /// <summary>  
     /// Number of columns that are used in sorting  
     /// </summary>  
     public int iSortingCols { get; set; }  
     /// <summary>  
     /// Comma separated list of column names  
     /// </summary>  
     public string sColumns { get; set; }  

Following is the method to load data for datatable. Assuming that we are going to show firstname, lastname, company and jobtitle from member table.
 public ActionResult GetDataForDatatable(jQueryDataTableParams param)  
 {  
    IQueryable<Member> memberCol = myDbContext.Member  
                      .Select(m => m.FirstName,  
                          m.LastName,  
                          m.Company,  
                          m.JobTitle)  
                      .AsQueryable();  
    int totalCount = memberCol.Count();  
    IEnumerable<Member> filteredMembers = memberCol;  
    if (!string.IsNullOrEmpty(param.sSearch))  
    {  
      filteredMembers = memberCol  
              .Where(m => m.FirstName.Contains(param.sSearch) ||  
                 m.LastName.Contains(param.sSearch) ||  
                 m.Company.Contains(param.sSearch) ||  
                 m.JobTitle.Contains(param.sSearch));  
    }  
    var sortIdx = Convert.ToInt32(Request["iSortCol_0"]);  
    Func<Member,string> orderingFunction = (m => sortIdx == 0 ? m.FirstName :  
                         sortIdx == 1 ? m.LastName :  
                         sortIdx == 2 ? m.Company :  
                         m.JobTitle);  
    var sortDirection = Request["sSortDir_0"]; // asc or desc  
    if (sortDirection == "asc")  
      filteredMembers = filteredMembers.OrderBy(orderingFunction);  
    else  
      filteredMembers = filteredMembers.OrderByDescending(orderingFunction);  
    var displayedMembers = filteredMembers  
             .Skip(param.iDisplayStart)  
             .Take(param.iDisplayLength);  
    var result = from a in displayedMembers  
           select new[] { a.FirstName, a.LastName, a.Company,   
                  a.JobTitle, a.ID.ToString() };  
    return Json(new  
       {  
         sEcho = param.sEcho,  
         iTotalRecords = totalCount,  
         iTotalDisplayRecords = filteredMembers.Count(),  
         aaData = result  
       },  
       JsonRequestBehavior.AllowGet);  
 }  

Following is how we initialize our datatable and design the HTML.

-> Reference to jQuery js, jQuery Datatable js, jQuery Datatable css

 <table id="tblMember" class="table" style="width: 100%">  
   <thead>  
     <tr>  
       <th>First Name</th>  
       <th>Last Name</th>  
       <th>Company</th>  
       <th>Job Title</th>  
       <th>Actions</th>  
     </tr>  
   </thead>  
   <tbody>  
   </tbody>  
 </table>  
 <script>  
   $(document).ready(function () {  
     // destroy existing datatable before, initiating  
     if (oTable != undefined) {  
       oTable.fnDestroy();  
     };  
     oTable = $('#tblMember').dataTable({  
       "bServerSide": true,  
       "sAjaxSource": '@Url.Action("GetDataForDatatable","Member")',  
       "bProcessing": true,  
       "aoColumns": [  
               { "sName": "FirstName" },  
               { "sName": "LastName" },  
               { "sName": "Company" },  
               { "sName": "JobTitle" },  
               {  
                 "sName": "ID",  
                 "bSearchable": false,  
                 "bSortable": false,  
                 'mRender': function (data, type, row) {  
                   return '<a href="@Url.Action("Edit", "Member")/' + row[4] + '" class="btn btn-warning btn-xs" role="button">@labels.btn_edit</a>' + '&nbsp;' +  
                       '<button onclick="confirmDelete(' + row[4] + ');" class="btn btn-danger btn-xs">@labels.btn_delete</button>';  
                 }  
               },  
       ]  
     });  
   }  
 </script>