Monday, December 15, 2014

Injecting a service into a view in MVC 6 MVC 6 supports injecting service to view using a class.

Example :- When country combo box value get changed , region com

Only restriction is that class should be

  • Public
  • Non-nested
  • Non-Abstract

1. Create a Asp.Net Project in Visual Studio 2015





2. Create a folder name services and add a service class.

  1. using System;
  2. using System.Threading.Tasks;
  4. namespace ViewInjection.Services
  5. {
  6.     public class EmployeeService
  7.     {
  8.         public async Task<int> GetEmployeesOnLeaveCount()
  9.         {
  10.             return await Task.FromResult(5);
  11.         }
  13.         public async Task<int> GetEmployeesOnSiteCount()
  14.         {
  15.             return await Task.FromResult(
  16.                 10);
  17.         }
  19.         public async Task<int> GetEmployeesOnWorkCount()
  20.         {
  21.             return await Task.FromResult(97);
  22.         }
  23.     }
  24. }


2. Create a View to show Employee statistics and add the inject statement to the top of the file.

  1. @inject ViewInjection.Services.EmployeeService EmployeeService
  2. @{
  3.      ViewBag.Title = "Employee Page";
  4. }

3. Call the service as below

  2. @inject ViewInjection.Services.EmployeeService EmployeeService
  3. @{
  4.      ViewBag.Title = "Employee Page";
  5. }
  7. <h3>Employee Stats</h3>
  8. <ul>
  9.     <li>On Leave: @await EmployeeService.GetEmployeesOnLeaveCount()</li>
  10.     <li>On Site:@await EmployeeService.GetEmployeesOnSiteCount()</li>
  11.     <li>On Work:@await EmployeeService.GetEmployeesOnWorkCount()</li>
  12. </ul>

4. Register the EmployeeService class in the Startup.cs file.

  1. public void ConfigureServices(IServiceCollection services)
  2.       {
  3.           // Add EF services to the services container.
  4.           services.AddEntityFramework(Configuration)
  5.               .AddSqlServer()
  6.               .AddDbContext<ApplicationDbContext>();
  8.           // Add Identity services to the services container.
  9.           services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
  11.           // Add MVC services to the services container.
  12.           services.AddMvc();
  14.           services.AddTransient<ViewInjection.Services.EmployeeService>();
  16.       }

5. Add a action method in HomeController.cs

  2. public IActionResult EmployeeStaticstics()
  3. {
  4.     return View();
  5. }

6.Run your code you will see the output as below.


Happy Coding !!

Thursday, October 2, 2014

Visual Studio 2014–New features


Visual studio 2014 CTP is now available for download. You can download it from here.

With the new release there are some new language & IDE features introduced. I will discuss some of IDE improvements in this post.

IDE Improvements

1. Colored quick info

when you hover over on something in your code now the quick info window has information with colors.


also if you collapse your code & hover over to see the code inside so you can see the code with all colored formatting in the tool tip.


2. Hint with un-used references

When we create a class there are few references which are automatically added. Also there are some cases we add some piece of code which need some other references & sometime back we remove that code but we don’t remove the reference.

Now Visual studio grey out those references & give option to remove those.


3. Hint with redundant qualifiers

In your code if you have already added the reference in your code & have used the namespace when when initializing objects of the classes in that namespace those are also highlighted & options are given to remove those. And it will show how the code will looks like when the fix is applied.


4. Show Refactoring options

Now visual studio provides some hints to refactor. Also it shows how code will look like when the refactoring is applied. Also in gives some windows which improved options for refactoring.

Will take the following code as an example.

  1. class Program
  2.   {
  3.       static void Main(string[] args)
  4.       {
  5.           User user = new User().GetUser();
  7.           string result=  string.Format("Age is {0}, Retirement in {1} years",
  8.                             user.age, (65 - user.age));
  9.           Console.WriteLine(result);
  10.           Console.ReadLine();
  11.       }
  12.   }
  15.   public class User
  16.   {
  17.       public int age { get; set; }
  19.       public User GetUser()
  20.       {
  21.           User user = new User();
  22.           user.age = 26;
  24.           return user;
  25.       }
  26.   }

so there you can see when taking the result string there is a duplicate code when taking user age. so if u highlight that code & click “ALT”+”.” it will show you the refactoring options.


there we can introduce a new local variable for that. When local variable is introduced it gives option to rename the variable also it highlights & shows it get renamed in every place.








also when you rename if that name conflicts with any existing variable it will show that as well.

ex: if we rename age as args


also it gives options to extract methods and some other refactoring options with many other improved options.


so if you are familiar with Re-sharper you might have used this options before. Now these are shipped with visual studio so you don’t need to buy licenses of another third party tool Smile.

Lets see some language improvements in the next post.

Until that……

Happy Coding Laughing out loud

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