Search in Help for developer site.

Sunday 15 January 2017

Difference between Const, Readonly and Static Keywords in C#


Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.


Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
  1. void Calculate(int Z)
  2. {
  3. const int X = 10, X1 = 50;
  4. const int Y = X + X1; //no error, since its evaluated a compile time
  5. const int Y1 = X + Z; //gives error, since its evaluated at run time
  6. }
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
  1. const MyClass obj1 = null;//no error, since its evaluated a compile time
  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
  1. class MyClass
  2. {
  3. readonly int X = 10; // initialized at the time of declaration
  4. readonly int X1;
  5.  
  6. public MyClass(int x1)
  7. {
  8. X1 = x1; // initialized at run time
  9. }
  10. }

  11. Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
    Use the readonly modifier when you want to make a field constant at run time.

Static

The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
  1. class MyClass
  2. {
  3. static int X = 10;
  4. int Y = 20;
  5. public static void Show()
  6. {
  7. Console.WriteLine(X);
  8. Console.WriteLine(Y); //error, since you can access only static members
  9. }
  10. }

Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can't be parameterized. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.
What do you think?
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.


Friday 6 January 2017

The Perfect Real Time Example of Interface in OOPS

 The Perfect Real Time Example of Interface in OOPS

Suppose your parents gives you a list of items to purchase,
that list is an Interface that you will implement at the time of purchasing.....
Means Before implementing any thing , you list out what you have to do that will be an interface......


Now Lets implement it in programming way:-



//Here Parent gives list of Items to purchase.So we listed out the Items
        interface IPurchaseItem
        {
            void PurchaseBook();
        }

        //Implementation while Purchasing.
        class Person1Purchasing:IPurchaseItem
        {
            public void PurchaseBook()
            {
                Console.WriteLine("Hey! I purchased C Sharp Book");
            }
            //other code here
        }
        class Person2Purchasing : IPurchaseItem
        {
            //Different Implementation
            public void PurchaseBook()
            {
                Console.WriteLine("Hey! I purchased Java Programming Book");
            }
            //other code here
        }



Description:-
Here we have one interface having PurchaseBook() method so now it depends on classes how they implement it. So here Person1 purchased C Sharp book and Person2 purchased Java Programming book.



I hope now you have a clear vision about Interface.

Note:-Its my own understanding on Interface.So Please correct me if i am wrong. Write your comments into the Comments section below.


LAG and LEAD Analytical Functions in Sql Server with Real Time Examples

LAG and LEAD Analytical Functions in Sql Server with Real Time Examples
Hello folks, Today I am going to share LAG and LEAD Analytical Functions in Sql Server. After reading this article you will be able to Understand and work with both the Analytical Functions.

1.   LAG Function:-

In SQL Server (Transact-SQL), the LAG function is an analytic function that lets you query more than one row in a table at a time without having to join the table to itself. It returns values from a previous row in the table. 

Syntax

LAG( expression [, offset [, default] ]) 
OVER ( [query_partition_clause ] order_by_clause )

Arguments Description:-
expression
 An expression that can contain other built-in functions, but can not contain any analytic functions.

offset
Optional. It is the physical offset from the current row in the table. If this parameter is omitted, the default is 1.

default 
Optional. It is the value that is returned if the offset goes out of the bounds of the table. If this parameter is omitted, the default is null.

query_partition_clause 
Optional. It is used to partition the results into groups based on one or more expressions.

order_by_clause 
Optional. It is used to order the data within each partition.

Applies To
The LAG function can be used in the following versions of SQL Server (Transact-SQL):
SQL Server 2014, SQL Server 2012

Example:-

Lets take an Example we have following Student data.


And we want to know the previous mark like this.

Another Example would be like we have Customer data with their order date so we want to know the Order Date along with Previous Order date so we would know what was the Previous Order date.


So now to achieve this data we will use LAG function as follow.


SELECT studentName, Mark,
LAG(Mark) OVER( ORDER BY Mark) AS PrevMark
FROM Exam order by Mark

So now it would return above result.

In this example, the LAG function will sort in ascending order all of the Mark values in the Student table.

2.   LEAD Function:-

Accesses data from a subsequent row in the same result set without the use of a self-join in SQL Server 2016. LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Syntax

LEAD ( scalar_expression [ ,offset ] , [ default ] )  
    OVER ( [ partition_by_clause ] order_by_clause ) 

Arguments Description:-

scalar_expression
The value to be returned based on the specified offset. It is an expression of any type that returns a single (scalar) value. scalar_expression cannot be an analytic function.

offset
The number of rows forward from the current row from which to obtain a value. If not specified, the default is 1. offset can be a column, subquery, or other expression that evaluates to a positive integer or can be implicitly converted to bigint. offset cannot be a negative value or an analytic function.

default
The value to return when scalar_expression at offset is NULL. If a default value is not specified, NULL is returned. default can be a column, subquery, or other expression, but it cannot be an analytic function. default must be type-compatible with scalar_expression.

OVER ( [ partition_by_clause ] order_by_clause)
partition_by_clause divides the result set produced by the FROM clause into partitions to which the function is applied. If not specified, the function treats all rows of the query result set as a single group. order_by_clause determines the order of the data before the function is applied. When partition_by_clause is specified, it determines the order of the data in each partition. The order_by_clause is required.

Examples:-

Compare values between years
The query uses the LEAD function to return the difference in sales quotas for a specific employee over subsequent years. Notice that because there is no lead value available for the last row, the default of zero (0) is returned.



Conclusion
In this article I discussed how you can use LAG and LEAD analytical function to access or query data from previous or subsequent rows without writing  self-join query. Write your queries into the comments section.


Wednesday 4 January 2017

what are the access modifiers

what are the access modifiers in c#


Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, member function, member variables etc. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components, It defines the accessibility of the specific type (e.g class, struct), data member etc.
In c# there are five type of access modifiers -
  • Public
  • Private
  • Protected
  • Internal
  • Protected Internal

Accessibility of access modifies in c#

Access Modifiers
Inside Assembly
Outside Assembly
With Inheritance
With Type
With Inheritance
With Type
Public
ü
ü
ü
ü
Private
X
X
X
X
Protected
ü
X
ü
X
Internal
ü
ü
X
X
Protected Internal
ü
ü
ü
X

Explanation of Public, Protected, Private, Internal And Protected Internal Access Modifiers In C#

Public: - Public members are accessible anywhere, inside the type (e.g. - class), outside the type, inside the assembly, outside the assembly, through the inheritance or with the type (e.g. instance of class, with type of class in case of static).

Private: - Private members are only accessible within the own type (Own class).

Protected: - Protected members are accessible only with its derived types whether it is inside the assembly or outside the assembly.

Internal: - Internal members are accessible only within the assembly by inheritance (its derived type) or by instance of class.

Protected Internal: - Protected internal is type of access modifier contains protected member properties as well as internal member properties, means protected internal member accessible inside the assembly in its derived class or with the instance of the class and accessible outside the class only in its derived class.

Monday 2 January 2017

The Various Ways of Binding MVC DropDownList

To Bind a DropDownListFor or DropDown in asp.net MVC from database, from enum or from hard coded values, most people suggest to add a property in the model with IEnumarable or IList. We can use it but not very helpful because after every postback we will need to fill the list again otherwise it will be null. So using ViewBag is not a bad idea, we will use it in our article.


    What we will see in this discussion:
    1. Bind DropDown with hard coded values
    2. Bind DropDown with records from database
    3. Bind DropDown with Enum
    4. Bind DropDown on change of other DropDown's value

    1. Bind DropDown with hard coded values

    We will try to write both controller code and view in every case, so let's see our first example by using hard coded value
    1.     public ActionResult Index()
    2.     {      
    3.         ViewBag.Active = new List<SelectListItem> {                  
    4.                  new SelectListItem { Text = "Yes", Value = "1"},                  
    5.                  new SelectListItem { Text = "No", Value = "0"}
    6.              };
    7.         var model = new ProductModel();
    8.         return View(model);
    9.     }
    In the view, I am not going to show all the label and other model detail. Here IsActie is the model value which will come from database for existing records otherwise null or default value from the model, I used the class name from bootstrap.
    1. @Html.DropDownListFor(model => model.IsActive,
    2.    new SelectList(ViewBag.Active, "Value", "Text"),
    3.    "Select status",
    4.     new { @class = "form-control" })
    If it is hard coded values and is a big list then we can create a separate method to create the list otherwise directly we can declare it in view rather than passing from controller view as we did in our above example, see how
    1. @Html.DropDownListFor(model => model.Category,
    2.     new SelectList(new List<SelectListItem> {                  
    3.              new SelectListItem { Text = "Yes", Value = "1"},                  
    4.              new SelectListItem { Text = "No", Value = "0"}
    5.          }, "Value", "Text"),
    6.     "Select status",
    7.      new { @class = "form-control" })
    It doesn't looks good but good thing is that we don't need to create the list again and again on postback, which we will see latter.

    2. Bind DropDown with records from database

    If you will explore a little bit, you will found most of the people suggest to convert the record into SelectList in controller or in model before passing to view. Is that really required or is a good practice? I cannot say about others but for me, it is really frustrating to convert my table into SelectList every time. If not then is there any way to directly bind the dropdown from a table records, yes, we will see it in this example:
    I have a table category which we will use in this example, here is the table structure:
    1. public partial class Category
    2. {
    3.     public int CategoryId { get; set; }
    4.     public string CategoryName { get; set; }
    5.     public bool IsActive { get; set; }
    6. }
    Controller code:
    1. // GET: Products
    2. public ActionResult Create()
    3. {
    4.     var db = new MyDBEntities();
    5.     ViewBag.Categories = db.Categories.Where(x => x.IsActive);
    6.     var model = new ProductModel();
    7.     return View(model);
    8. }  
    9. // POST: Create Product
    10. public ActionResult Create(ProductModel model)
    11. {
    12.     var db = new MyDBEntities();
    13.     if (ModelState.IsValid)
    14.     {
    15.         // code to save record  and redirect to listing page
    16.     }
    17.     // If model is not valid then reload categories from database
    18.     ViewBag.Categories = db.Categories.Where(x => x.IsActive);
    19.     return View(model);
    20. }
    In our GET action we are fetching all active categories from database and passing to view by using ViewBag. In POST action we try to validate the posted data by using ModelState.IsValid method, if valid, save data and redirect user to your desired page otherwise, re-populate the the categories before returning the user to page to fix the issue. Now we will see our view html
    1. @Html.DropDownListFor(model => model.Category,
    2.     new SelectList(ViewBag.Categories, "CategoryID", "CategoryName"),
    3.     "Select Category",
    4.     new { @class = "form-control" })
    As you noticed, we directly pass the table records to view after fetching from database without converting to Select List and converted into Select List directly into the view, which is easy and save time. If we will do the same in controller then we need to convert the list in both GET as well as POST action.

    3. Bind DropDown with Enum

    There are two ways to bind and save the records, and it's all depends on requirement, whether we want to save the number or text value of the enum, we will try both. Let's first create an enum say Language, I am adding those language which I read write and speak
    1. public enum Language
    2. {
    3.     Arabic,
    4.     English,
    5.     Hindi,
    6.     Spanish,
    7.     Urdu
    8. }
    If we need to save the text or say bind with text then
    1. // In controller
    2. ViewBag.Languages = Enum.GetValues(typeof(Language)).Cast<Language>();
    3. // In View
    4. @Html.DropDownListFor(model => model.Language,
    5.         new SelectList(ViewBag.Languages),
    6.         "Select language",
    7.         new { @class = "form-control" })
    As in most cases we want to use value and text, so we need to create a structure or class and create the list of it from enum which we will use in this example:
    We will create a structure which we can use for entire application
    1. public struct DDL
    2. {
    3.     public int Value { get; set; }
    4.     public String Text { get; set; }
    5. }
    Now create the list of DLL by using Language enum foreach, and assign to ViewBag.Languages
    1. var languages = new List<DDL>();
    2. foreach (Language lang in Enum.GetValues(typeof(Language)))
    3.     languages.Add(new DDL { Value = (int)lang, Text= lang.ToString() });
    4. ViewBag.Languages = languages;
    In view, binding is same as earlier:
    1. @Html.DropDownListFor(model => model.Language,
    2.       new SelectList(ViewBag.Languages, "Value", "Text"),
    3.       "Select status",
    4.       new { @class = "form-control" })
    Now when we will post the page, it will post the language Id not the text.

    4. Bind DropDown on change of other DropDown's value

    we will try to bind child Dropdown on selection change of parent Dropdown, say Country to State or Sate to City, by using jQuery which will call an action in controller and return JSON for selected id, and with the help of jQuery append values to child Dropdown. We will try to create page to add new employee and state and city will be used as parent and child Dropdown.

    Let's see the tables we are going to use:
    1. public partial class State
    2. {
    3.     public int StateId { get; set; }
    4.     public string StateName { get; set; }
    5.     public string Abbr { get; set; }
    6. }
    7. public partial class City
    8. {
    9.     public int CityId { get; set; }
    10.     public string CityName { get; set; }
    11.     public int StateId { get; set; }
    12. }
    Employee Model:
    1. public class Employees
    2. {
    3.     [Key]
    4.     public int EmployeeId { get; set; }
    5.     [Required, Display(Name="Employee Name")]
    6.     public string EmployeeName { get; set; }
    7.     [Required, Display(Name = "Address")]
    8.     public String Address { get; set; }
    9.     [Required, Display(Name = "State")]
    10.     public int State { get; set; }
    11.     [Required, Display(Name = "City")]
    12.     public int City { get; set; }
    13.     [Display(Name = "Zip Code")]
    14.     public String ZipCode { get; set; }
    15.     [Required, Display(Name = "Phone #")]
    16.     public String Phone { get; set; }
    17. }
    As you can see, I have not added anything in our model for list of states or cities because we are using Code first, which will create the database tables, we will try to get data from database and pass to view by using ViewBag, here is our HttpGet and HttpPost action method:
    1. [HttpGet]
    2. public ActionResult Create()
    3. {
    4.     ViewBag.StateList = db.States;
    5.     var model = new Employees();
    6.     return View(model);
    7. }
    8. [HttpPost]
    9. public ActionResult Create(Employees model)
    10. {
    11.     if (ModelState.IsValid)
    12.     {
    13.         // code to save record  and redirect to listing page
    14.     }
    15.     ViewBag.StateList = db.States;
    16.     return View(model);
    17. }
    HTML code for both state and city dropdown:
    1. <div class="form-group">
    2.     @Html.LabelFor(m => m.State,  new { @class = "control-label col-md-2" })
    3.     <div class="col-md-10">
    4.         @Html.DropDownListFor(m => m.State,
    5.               new SelectList(ViewBag.StateList, "StateId", "StateName"),
    6.               "Select state",
    7.               new { @class = "form-control", @onchange="FillCity()" })
    8.         @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
    9.     </div>
    10. </div>
    11. <div class="form-group">
    12.     @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
    13.     <div class="col-md-10">
    14.         @Html.DropDownListFor(m => m.City,
    15.        new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
    16.               "Select city",
    17.               new { @class = "form-control" })
    18.         @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
    19.     </div>
    20. </div>
    As you can notice we used @onchange="FillCity()" in our State dropdown so we need a JavaScript function which will be call on change of state. If you are from asp.net background then forgot about the postback, in mvc there is no postback concept so we don't need viewstate of controls so the pages are light weight. Here is our FillCity function:
    1. @section Scripts {
    2. <script>
    3.   function FillCity() {
    4.     var stateId = $('#State').val();
    5.     $.ajax({
    6.         url: '/Employees/FillCity',
    7.         type: "GET",
    8.         dataType: "JSON",
    9.         data: { State: stateId},
    10.         success: function (cities) {                    
    11.             $("#City").html(""); // clear before appending new list
    12.             $.each(cities, function (i, city) {
    13.                 $("#City").append(
    14.                     $('<option></option>').val(city.CityId).html(city.CityName));
    15.             });
    16.         }
    17.     });
    18.   }
    19. </script>
    20. }
    Here we used $.each to loop the items and add item by item to city dropdown. We used to call FillCity action method in our Employees controller.We need a separate action method which can return cities on the basis of selection change and return JSON string.
    1. public ActionResult FillCity(int state)
    2. {
    3.     var cities = db.Cities.Where(c => c.StateId == state);
    4.     return Json(cities, JsonRequestBehavior.AllowGet);
    5. }
    See how we can return json from any action method in our controller. If you want to see the complete html of the page then it is here.
    1. @model MyApp.Models.Employees
    2. @{
    3.     ViewBag.Title = "Index";
    4.     Layout = "~/Views/Shared/_Layout.cshtml";
    5. }
    6. <h2>Index</h2>
    7. @using (Html.BeginForm())
    8. {
    9. @Html.AntiForgeryToken()
    10. <div class="form-horizontal">
    11.     <h4>New Employee</h4>      
    12.     <div class="form-group">
    13.         @Html.LabelFor(m => m.EmployeeName, new { @class = "control-label col-md-2" })
    14.         <div class="col-md-10">
    15.             @Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control" })
    16.             @Html.ValidationMessageFor(m => m.EmployeeName, "", new { @class = "text-danger" })
    17.         </div>
    18.     </div>
    19.     <div class="form-group">
    20.         @Html.LabelFor(m => m.Address, new { @class = "control-label col-md-2" })
    21.         <div class="col-md-10">
    22.             @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
    23.             @Html.ValidationMessageFor(m => m.Address, "", new { @class = "text-danger" })
    24.         </div>
    25.     </div>
    26.     <div class="form-group">
    27.         @Html.LabelFor(m => m.State,  new { @class = "control-label col-md-2" })
    28.         <div class="col-md-10">
    29.             @Html.DropDownListFor(m => m.State,
    30.                   new SelectList(ViewBag.StateList, "StateId", "StateName"),
    31.                   "Select state",
    32.                   new { @class = "form-control", @onchange="FillCity()" })
    33.             @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
    34.         </div>
    35.     </div>
    36.     <div class="form-group">
    37.         @Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
    38.         <div class="col-md-10">
    39.             @Html.DropDownListFor(m => m.City,
    40.            new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
    41.                   "Select city",
    42.                   new { @class = "form-control" })
    43.             @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
    44.         </div>
    45.     </div>
    46.     <div class="form-group">
    47.         @Html.LabelFor(m => m.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
    48.         <div class="col-md-10">
    49.             @Html.TextBoxFor(m => m.ZipCode,  new { @class = "form-control" })
    50.             @Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })
    51.         </div>
    52.     </div>
    53.     <div class="form-group">
    54.         @Html.LabelFor(m => m.Phone, new { @class = "control-label col-md-2" })
    55.         <div class="col-md-10">
    56.             @Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })
    57.             @Html.ValidationMessageFor(m => m.Phone, "", new { @class = "text-danger" })
    58.         </div>
    59.     </div>
    60.     <div class="form-group">
    61.         <div class="col-md-offset-2 col-md-10">
    62.             <input type="submit" value="Create" class="btn btn-success" />
    63.             <a href="/Employees" class="btn btn-warning" >Cancel</a>
    64.         </div>
    65.     </div>
    66. </div>
    67. }
    If you want to add more column value into dropdown text you can concatenate them easily, say we want to show both Id and text in city drop down then we simmply show it like this:
    $('<option></option>').
       val(city.CityId).html(city.CityId + " - " + city.CityName)); 
    Whatever we see here is not complete to maintain the selected value if we found the model invalid in our post method and return back to the view then current selected state's cities will be lost same will happen when we need to fill and select the value in city dropdown for a saved records. We need to add one more JavaScript method to check on document.ready if there is any value already selected in state dropdown then call the FillCity method and fill our city dropdown and selected the city value which we get from the model.
    I am leaving it for you so you can do a little bit practice, hope you will easily complete it, best of luck.