Sunday, January 4, 2015

Primary Constructor in C# 6.0

 

In my previous post I explain about Auto Property Initializer in C# 6.0. Now lets see another new feature in C# 6.0 which is Primary constructor.

First we will see the following code.

  1. public class Country
  2. {
  3.     public string Name { get; private set; }
  4.  
  5.     public Country(string name)
  6.         {
  7.         Name = name;
  8.         }
  9.  
  10. }

here we have a class which has a property with a private setter and assigning the value for the name property inside the constructor.

Now in C# 6.0 you can write the above code in a more simplified manner as follows.

  1. public class Country(string name)
  2.     {
  3.         public string Name { get;}=name;
  4.  
  5.  
  6.     }

This is what is called primary constructor in C# 6.0 . Notice the parameters added just right of the class definition. This tells the compiler to add a constructor to the Country class with one parameters: name. So we don’t need to create separate constructor with parameters and then assign the values to the property , compiler do all those for us.

For one class only one primary constructor is allowed. If you want to have constructors with some more parameters you can create new constructor and also call the primary constructor inside it. See the following example.

  1. public class Country(string name)
  2.     {
  3.         public string Name { get; } = name;
  4.     public List<string> Regions { get; private set; }
  5.     public Country(List<string> regions, string name):this(name)
  6.     {
  7.         Regions = regions;
  8.     }
  9. }

Here when you call the constructor with two parameters it will assign the value to the property “Regions” and it has call the primary constructor it will set the value to the property “Name”. Hope you understand the concept behind this.

Hope this is helpful.

Happy Coding !!!!!!

Friday, January 2, 2015

Auto Property Initializer

 

Anyone who have worked with properties in a class must have experienced that it was little annoying that we have to have private fields and assigned if we want to have default values for properties.

See the following example which we used to do when we have collection property.

  1. public class Country
  2.     {
  3.         private List<string> _regions = new List<string>();
  4.         public List<string> Regions { get { return _regions} set { value = _regions; } }
  5.  
  6.     }

but this is no more needed. We can simply write it as below.

  1. public class Country
  2.     {
  3.         public List<string> Regions { get; set; }=new List<string>();
  4.  
  5.     }

Also this is useful when you want to assign default values for read only fields.

Before C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }
  4.       public Country()
  5.       {
  6.           this.Name = "Sri Lanka";
  7.       }
  8.  
  9.   }

In C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }="Sri Lanka";
  4.  
  5.   }

 

This is syntactic sugar added in c# 6.0. hope this is helpful.

 

Happy Coding !!!!!!

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