Monday, August 11, 2014

C# Design Patterns


Please find the presentation and the sample code I presented on Sri Lanka .Net forum on August 2014 Meet up.

August 2014

Tuesday, July 15, 2014

Cannot read property 'fnSetData' of undefined


I have a Jquery Datatable in one of my MVC view. When I tried to load the Datatable I got the following error.

Cannot read property 'fnSetData' of undefined

Problem in my case was my table header and the table body content was not matching.


 <table cellpadding="0" cellspacing="0" border="0" class="display" id="TBL_WorkAreaManagementSearchResults" style="width: 100%">
@foreach (var workArea in Model)
<td style="cursor: pointer;">
<a href="javascript:new RegionWorkAreaManagement().OurworkplaceManagement(@workArea.Id, @((int)WorkplaceConfigurationType.WorkArea))">Workplace</a>


Here as you can see I have defibed 3 columns in the header and have 4 columns in the table body. Because of this mismatch jquery datatble was giving the error above. When the table header and body has similar number of columns issue got solved.

Hope this will help.

Happy Coding !!!!!!

Wednesday, July 9, 2014

Editable List box in HTML


I have recently came across a requirement where  a list of objects need to be added and edited. That object has only two fields which is name & id. So there is no point of using a editable data table as well. Following is the solution I came across.

  1. Create a List box
  2. Add a text box and a button which will add new items to the list box.
  3. On click on list box item load a pop up which allows user to edit the items.


Code for generating Listbox at the View

  1. <div>

  2.                       <selectsize="10" id="workAreas" multiple>

  3.                         @foreach (var item in Model.WorkAreas)

  4.                         {


  6.                             <option id="option_@item.Id" value="@item.Id" onclick="new RegionManagement().OnWorkAreaEdit(@item.Id);" class="TextBoxLarge">

  7.                                 @item.Name

  8.                             </option>


  10.                         }

  11.                       </select>

  12.                 </div>

Code for Input text box and button

  1. <div>

  2.                     <input type="text" id="txtWorkArea" />

  3.                     <button id="btAddWorkArea" class="btn btn-success" onclick="new RegionManagement().AddNewWorkArea();">+</button>

  4.                 </div>

Code for pop up

  1. div id="DIV_EditWorkArea" style="display: none;">

  2.     <div id="DIV_EditWorkAreaSubForm" class="InnerEntrySubForm" style="display: none; height:200px; margin-top:-175px;">

  3.         <div class="InneEntryData" id="DIV_EditWorkAreaEditInner">

  4.                 <input type="hidden"id="txtWorkAreaId" />

  5.     <input type="text" id="txtEditWorkArea" />

  6.     <span id="btEditWorkAreaOK" class="btn btn-success" onclick="new RegionManagement().SaveWorkAreavalue();">OK</span>

  7.     <span id="btEditWorkAreaCancel" class="btn btn-warning " onclick="new RegionManagement().HideEditWorkArea();">X</span>

  8.         </div>

  9.     </div>

  10. </div>



  2. this.OnWorkAreaEdit = function(id) {

  3.     var txt = $('#option_' + id).text().trim();

  4.     $('#txtEditWorkArea').val(txt);

  5.     $('#txtWorkAreaId').val(id);


  7.     $("#DIV_EditWorkArea").css('display', 'block');

  8.     show("DIV_EditWorkAreaSubForm");

  9. };

  10. this.SaveWorkAreavalue = function() {

  11.     var id = $('#txtWorkAreaId').val();

  12.     var text = $('#txtEditWorkArea').val();

  13.     $('#option_' + id).text(text);

  14.     this.HideEditWorkArea();

  15. };



  18. this.AddNewWorkArea = function() {

  19.     var uniqueId =;

  20.     var text = $('#txtWorkArea').val();

  21.     if (text != '') {

  22.         $('#workAreas')

  23.             .append('<option value="0" id="option_' + uniqueId + '"onclick="new RegionManagement().OnWorkAreaEdit(' + uniqueId + ');">' + text + '</option>');

  24.         $('#txtWorkArea').val('');

  25.     }

  26. };

Hope this helps.

Happy Coding !!!!!!

Tuesday, June 17, 2014

Azure Exception after scaling

System.Security.Cryptography.CryptographicException: Key not valid for use in specified state.

I have recently scaled my application deployed in Azure for 2 instances. After scaling that I got the above exception when loading the application. After searching for hours I came across the solution for it.

What you have to do is add the following code snippet in your configuration.

  1. <system.identityModel>
  2.   <identityConfiguration>
  3.     <securityTokenHandlers>
  4.       <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,  
  5.              System.IdentityModel.Services, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  6.       <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
  7.              System.IdentityModel, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  8.     </securityTokenHandlers>
  9.   </identityConfiguration>
  10. </system.identityModel>

For more information visit here.

Happy Coding !!!!!!

Tuesday, June 10, 2014

Retrieve Sql Out parameter in c#

Recently I got an requirement of developing a Stored procedure which searches some data in our database including paging also it should return the total number of records as well. Following is the solution I came up.

1. Create a SP which returns the results set and have an output parameter in it which returns the total records count.

when deciding how to get total records from the SP which has paging as well , came across with following solutions.

  • Use COUNT(*) OVER in the select statement which will add a new column to your results set which has the total number of records as the value for each record.
  • Create a temp table with the select statement without paging, return the results set applying paging to that results set, and out the Total count taking the total count in the temp table
  • Use an out parameter for total ,rather creating a temp table run two separate queries and get the result set and count.

after reading few articles found out 3rd option is best as it has best performance. Check the following link for More Information.

So following is the stored procedure I came up with

  1. GO
  4. GO
  6. GO
  8. IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID('SP_SearchWorkOrders') AND OBJECTPROPERTY(id, 'IsProcedure') = 1)
  9.     DROP PROCEDURE SP_SearchWorkOrders
  10. GO
  12. CREATE PROCEDURE [dbo].[SP_SearchWorkOrders]
  13. (
  14. @FromRecord int = null,
  15. @RecordCount int = null,
  16. @TotalRecordsCount int out
  17. )
  18. AS
  19. BEGIN
  21. SELECT @TotalRecordsCount= COUNT(*)
  22. FROM [WorkOrders]
  23.   WHERE[WorkOrders].Archived = 0
  27. SELECT [WorkOrders].Id AS [ID]
  28. ,[WorkOrders].[DateLastModified] AS [Timestamp]
  29. ,[WorkOrders].[WorkOrderNo] as [WorkOrderNo]
  30. FROM [WorkOrders]
  31.   WHERE[WorkOrders].Archived = 0
  32. ORDER BY [WorkOrders].[CreatedOn] DESC
  33. OFFSET IsNull(@FromRecord, 0) ROWS
  34. FETCH NEXT IsNull(@RecordCount, 100000000) ROWS ONLY
  36. END
  38. GO

2. Create a c# method which returns the results set and the total count.

  1. public IList<WorkOrder> Search(SearchQuery searchQuery, out int totalRecordsCount)
  2.         {
  3.             Database database = GetDatabase();
  4.             IList<WorkOrder> valueObjectList = new List<WorkOrder>();
  5.             WorkOrderSearchQuery workOrderSearchQuery = searchQuery as WorkOrderSearchQuery;
  6.             using (DbCommand command = database.GetStoredProcCommand("SP_SearchWorkOrders"))
  7.             {
  8.                 database = AddSearchParameters(searchQuery, database, command, workOrderSearchQuery);
  9.                 //set the out parameter for the command                
  10.                 database.AddOutParameter(command, "TotalRecordsCount", DbType.Int32, 4);
  11.                 using (IDataReader reader = database.ExecuteReader(command))
  12.                 {
  13.                     while (reader.Read())
  14.                     {
  15.                         valueObjectList.Add(MapWorkOrder(reader));
  16.                     }
  17.                     // must close the reader to get the out put parameter                     
  18.                     reader.Close(); //read the out parameter value                    
  19.                     totalRecordsCount = (int) command.Parameters["@TotalRecordsCount"].Value;
  20.                 }
  21.             }
  22.             return valueObjectList;
  23.         }

Hope this helps.

Happy Coding !!!!

Friday, June 6, 2014

Asynchronous Programming Using Delegates

Delegated allow you to call any synchronous method asynchronously. In this post I will discuss way of doing this.

BeginInvoke() :

When a delegate is called using BeginInvoke it has same parameters as the method that you want to execute and two other parameters.

  1. AsyncCallback :delegate that references a method to be called when the asynchronous call completes
  2. Sender Object: a user-defined object that passes information into the callback method

lets see how this could be done step by step.

Step 1: Define delegate & call it asynchronously

As the first step you can do the followings.

  1. Define a delegate with same signature as the method to be called asynchronously
  2. Assign the method to be called asynchronously to the delegate
  3. Invoke the delegate asynchronously

See the sample code here:

  1. //Define a delegate with same signature as the method to be called asynchronously
  2.   private delegate void UpdateWorkLogHandler(int hours, string workType);
  3.   static void Main(string[] args)
  4.   {
  5.       DoWork(10, "Development");
  6.   }
  8.   public static void DoWork(int hours, string workType)
  9.   {
  10.       //Assign the method to be called asynchronously to the delegate
  11.       UpdateWorkLogHandler updateWorkLogHandler = UpdateWorkLog;
  13.       //Invoke the delegate asynchronously
  14.       updateWorkLogHandler.BeginInvoke(hours, workType, null, null);
  15.       Console.WriteLine("Work Completed!. Log updating in progress");
  16.       Console.ReadLine();
  17.   }
  19.   public static void UpdateWorkLog(int hours, string workType)
  20.   {
  21.       System.Threading.Thread.Sleep(1000);
  23.       Console.WriteLine("Work log updated!");
  24.       Console.ReadLine();
  25.   }

Output Window :


You can see here before completion of UpdateWorkLog method, programs has printed the “Work Completed!. Log updating in progress”. It is because as UpdateWorkLog  is called asynchronously rest of the code in DoWork method is been executed. If you have invoked the delegate without BeginInvoke output will be the following.


Step 2: With Callback

In case if you want to know whether that method is executed and call back to a method which you define & then execute some other logic you can assign a callback method on BeginInvoke as below.

  1. //Define a delegate with same signature as the method to be called asynchronously
  2.         private delegate void UpdateWorkLogHandler(int hours, string workType);
  4.         static void Main(string[] args)
  5.         {
  6.             DoWork(10, "Development");
  7.         }
  9.         public static void DoWork(int hours, string workType)
  10.         {
  11.             //Assign the method to be called asynchronously to the delegate
  12.             UpdateWorkLogHandler updateWorkLogHandler = UpdateWorkLog;
  14.             //Invoke the delegate asynchronously
  15.             updateWorkLogHandler.BeginInvoke(hours, workType, UpdateWorkLogCompleted, null);
  16.             Console.WriteLine("Work Completed!. Log updating in progress");
  17.             Console.ReadLine();
  18.         }
  20.         //Callback Method
  21.         public static void UpdateWorkLogCompleted(IAsyncResult ar)
  22.         {
  23.             Console.WriteLine("Work log updated Callback called");
  24.             Console.ReadLine();
  25.         }
  26.         public static void UpdateWorkLog(int hours, string workType)
  27.         {
  28.             System.Threading.Thread.Sleep(1000);
  29.             Console.WriteLine("Work log updated");
  31.         }

Output Window:


Step 3: With EndInvoke

In case if you need a return value from the asynchronously called method you can use EndInvoke.

The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes.

See the sample code below. It take the return value and then do the rest of the execution.

  //Define a delegate with same signature as the method to be called asynchronously
  private delegate bool UpdateWorkLogHandler(int hours, string workType);

  static void Main(string[] args)
      DoWork(10, "Development");

  public static void DoWork(int hours, string workType)
      //Assign the method to be called asynchronously to the delegate
      UpdateWorkLogHandler updateWorkLogHandler = UpdateWorkLog;
      //Invoke the delegate asynchronously
     IAsyncResult result= updateWorkLogHandler.BeginInvoke(hours, workType,null,null);
      Console.WriteLine("Work Completed!. Log updating in progress");

      // Call EndInvoke and get the returned value
      bool returnedValue = updateWorkLogHandler.EndInvoke(result);

      Console.WriteLine("Do Work Completed");

  //Callback Method
  public static void UpdateWorkLogCompleted(bool result)
      Console.WriteLine("Work log updated Callback called Result:"+ result);
  public static bool UpdateWorkLog(int hours, string workType)
      Console.WriteLine("Work log updated");
      return true;


Output Window :


So can see here it has received the return value. Also the it did not execute the rest of the code until after EndInvoke until it received the returned value.

Hope this helps you.

Happy Coding !!!!!

.net Forum June Meet up – c# events and Delegates


Hi All,

Please find the .net Forum June Meet up presentation and the code samples in the below link.

Happy Coding Smile