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.

ex:

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

<td>
@workArea.Name
</td>
<td>
@workArea.Region.Name
</td>
<td>
@workArea.Code
</td>
</tr>
}
</tbody>
</table>



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.                         {

  5.               

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

  7.                                 @item.Name

  8.                             </option>

  9.            

  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>





Javascript






  1.  

  2. this.OnWorkAreaEdit = function(id) {

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

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

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

  6.  

  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. };

  16.  

  17.  

  18. this.AddNewWorkArea = function() {

  19.     var uniqueId = Date.now();

  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=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  6.       <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
  7.              System.IdentityModel, Version=4.0.0.0, 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
  2.  
  3. SET ANSI_NULLS ON
  4. GO
  5. SET QUOTED_IDENTIFIER ON
  6. GO
  7.  
  8. IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID('SP_SearchWorkOrders') AND OBJECTPROPERTY(id, 'IsProcedure') = 1)
  9.     DROP PROCEDURE SP_SearchWorkOrders
  10. GO
  11.  
  12. CREATE PROCEDURE [dbo].[SP_SearchWorkOrders]
  13. (
  14. @FromRecord int = null,
  15. @RecordCount int = null,
  16. @TotalRecordsCount int out
  17. )
  18. AS
  19. BEGIN
  20.  
  21. SELECT @TotalRecordsCount= COUNT(*)
  22. FROM [WorkOrders]
  23.   WHERE[WorkOrders].Archived = 0
  24.  
  25.  
  26.  
  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
  35.  
  36. END
  37.  
  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.   }
  7.  
  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;
  12.    
  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.   }
  18.  
  19.   public static void UpdateWorkLog(int hours, string workType)
  20.   {
  21.       System.Threading.Thread.Sleep(1000);
  22.  
  23.       Console.WriteLine("Work log updated!");
  24.       Console.ReadLine();
  25.   }

Output Window :

image

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.

image

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);
  3.       
  4.         static void Main(string[] args)
  5.         {
  6.             DoWork(10, "Development");
  7.         }
  8.  
  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;
  13.           
  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.         }
  19.  
  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");
  30.            
  31.         }

Output Window:

image

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);
      UpdateWorkLogCompleted(returnedValue);

      Console.WriteLine("Do Work Completed");
      Console.ReadLine();
  }

  //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)
  {
      System.Threading.Thread.Sleep(1000);
      Console.WriteLine("Work log updated");
      return true;

  }

Output Window :

image

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.

https://onedrive.live.com/?cid=80EDE0125C9CA03A&id=80EDE0125C9CA03A%21110

Happy Coding Smile

Wednesday, May 7, 2014

Azure Cache (Preview) Step by Step

 

Windows Azure Cache is a distributed, in-memory, scalable solution that enables you to build highly scalable and responsive applications by providing super-fast access to data. Cache increases performance by temporarily storing information from other backend sources. High performance is achieved by maintaining this cache in-memory in a distributed environment.

There are mainly 3 types

  1. Cache Service (Preview)
  2. In-Role Cache
  3. Shared Cache

In this post I will explain step by step on how to develop Cache Service (Preview) with in an ASP.net application.

Step 1 : Create Cache

Create a cache for Windows azure cache service.

You can find step by step on how to create here.

Step 2 : Configure Cache

1. Create a ASP.net web project

2. Include Cache Service (Preview) NuGet package in to you project.

for that

  • Right click on the project References
  • Select “Manage NuGet packages

image

  • Search “Windows Azure Cache”. Then select and install the package highlighted in the following image.

image

3. You can  see following two sections added to your Web config.

  • dataCacheClients
  • cacheDiagnostics
  1. <configSections>
  2.   <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  3.   <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  4.   <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
  5.   <section name="cacheDiagnostics" type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon" allowLocation="true" allowDefinition="Everywhere" />
  6. </configSections>

 

4. Edit the dataCacheClients section in webconfig and add you service endpoint url which you got when creating the cache in to the web configuration file.

  1. <dataCacheClients>
  2.   <dataCacheClient name="default">
  3.     <!--To use the in-role flavor of Windows Azure Cache, set identifier to be the cache cluster role name -->
  4.     <!--To use the Windows Azure Cache Service, set identifier to be the endpoint of the cache cluster -->
  5.     <autoDiscover isEnabled="true" identifier="[Cache role name or Service Endpoint]" />
  6.     <!--<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />-->
  7.     <!--Use this section to specify security settings for connecting to your cache. This section is not required if your cache is hosted on a role that is a part of your cloud service. -->
  8.     <!--<securityProperties mode="Message" sslEnabled="false">
  9.       <messageSecurity authorizationInfo="[Authentication Key]" />
  10.     </securityProperties>-->
  11.   </dataCacheClient>
  12. </dataCacheClients>

 

5. Uncoment the securityProperties section under the dataCacheClients section in webconfig and add you Authentication Key which you got when creating the cache in to the web configuration file.

  1. <securityProperties mode="Message" sslEnabled="false">
  2.         <messageSecurity authorizationInfo="[Authentication Key]" />
  3.       </securityProperties>

 

now you are ready to develop cache for your application

Step 3 : Use Cache

The Cache Service (Preview) programming model is designed for the cache-aside programming pattern. If your data is not present in the cache, your application, and not the distributed cache, must reload data into the cache from the original data source.

1. Create a class which has generic methods for accessing the cache.

  1.   public staticclass AzureCache
  2.   {
  3.  
  4.       public static T Get<T>(string key)
  5.       {
  6.           DataCache defaultCache = GetDataCache();
  7.           T value = default(T);
  8.           var cacheValue = defaultCache.Get(key);
  9.  
  10.           if (cacheValue != null)
  11.           {
  12.               try
  13.               {
  14.                   value = (T)defaultCache.Get(key);
  15.               }
  16.  
  17.               catch
  18.               {
  19.                   value = default(T);
  20.               }
  21.           }
  22.           return value;
  23.  
  24.       }
  25.  
  26.       public static void Put(string key, object value)
  27.       {
  28.           DataCache defaultCache = GetDataCache();
  29.           defaultCache.Put(key, value);
  30.       }
  31.  
  32.       public static void Remove(string key)
  33.       {
  34.           DataCache defaultCache = GetDataCache();
  35.           defaultCache.Remove(key);
  36.       }
  37.  
  38.       private static DataCache GetDataCache()
  39.       {
  40.           DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration("default");
  41.           config.ChannelOpenTimeout = new TimeSpan(0, 10, 0);
  42.           config.TransportProperties.ReceiveTimeout = new TimeSpan(0, 0, 50);
  43.           DataCacheFactory cacheFactory = new DataCacheFactory(config);
  44.           DataCache defaultCache = cacheFactory.GetDefaultCache();
  45.  
  46.           return defaultCache;
  47.       }
  48.   }

2. Add Items to cache as below

  1. AzureCache.Put("test",9900);

3. Get Items from cache as below.

  1. var value = AzureCache.Get<int>("test");

 

Happy Coding !!!!!