Monday, December 15, 2014

Injecting a service into a view in MVC 6

 

Asp.net 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

image

 

image

 

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

  1. using System;
  2. using System.Threading.Tasks;
  3.  
  4. namespace ViewInjection.Services
  5. {
  6.     public class EmployeeService
  7.     {
  8.         public async Task<int> GetEmployeesOnLeaveCount()
  9.         {
  10.             return await Task.FromResult(5);
  11.         }
  12.  
  13.         public async Task<int> GetEmployeesOnSiteCount()
  14.         {
  15.             return await Task.FromResult(
  16.                 10);
  17.         }
  18.  
  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

  1.  
  2. @inject ViewInjection.Services.EmployeeService EmployeeService
  3. @{
  4.      ViewBag.Title = "Employee Page";
  5. }
  6.  
  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>();
  7.  
  8.           // Add Identity services to the services container.
  9.           services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
  10.  
  11.           // Add MVC services to the services container.
  12.           services.AddMvc();
  13.           
  14.           services.AddTransient<ViewInjection.Services.EmployeeService>();
  15.  
  16.       }

5. Add a action method in HomeController.cs

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

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

image

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.

image

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.

image

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.

image

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.

image

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();
  6.  
  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.   }
  13.  
  14.  
  15.   public class User
  16.   {
  17.       public int age { get; set; }
  18.  
  19.       public User GetUser()
  20.       {
  21.           User user = new User();
  22.           user.age = 26;
  23.  
  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.

image

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.

image

image

 

 

 

 

 

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

image

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

image

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.

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