Category Archives: Asp.Net

Asp.Net

How to host a window service using installUtil.exe.

Steps to host window service using installUtil.exe

  1. Go to installUtil.exe path C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe
  2. Build Application in Release mode.
  3. Open VS2012 x86/64 Native Tool Command with Run as Administrator
  4. cd (Copy+Paste InstallUtil.exe path) Enter
  5. Application Path Enter

How to fetch html from a URL in c#.

Fetching a html from an URL is easy. Class System.Net.HttpWebRequest provides an HTTP – specific implementation of the System.Net.WebRequest class.

using System.IO;
using System.Net;
public void FetchHtml()
{
    string result = string.Empty;
    string url = "http://codesolution.org";
    var request = HttpWebRequest.Create(url);
    using (var response = request.GetResponse())
    {
        result = new StreamReader(response.GetResponseStream()).ReadToEnd();
    }
    div1.InnerHtml = result;
}

IIS Integrated vs Classic Mode

Integrated mode and Classic mode are parts of IIS Pipeline mode. IIS Pipeline mode refers to how a web server processes client requests.

Integrated Mode

  • It works as a part of IIS 7. It is only available in IIS 7 and above.
  • It handles all requests through a unified pipeline because of the integration of ASP.NET’s runtime with the Web server.
  • it uses new and improved services of IIS 7 and above.

Classic Mode

  • It works as an external plugin with IIS 7. It was the only mode available in IIS 6 and below.
  • It uses two pipeline modes to handles client requests. One for native code and other for managed code.
  • It does not use new and improved services of IIS 7 and above.

 

What are Hashtable and Dictionary in C#?

Hashtable

//Create Hashtable
Hashtable objHash = new Hashtable();
objHash.Add("Hitesh", "1");
objHash.Add("Dev", "2");

//Get Value from Hashtable
int value1 = Convert.ToInt32(objHash["Hitesh1"]);
int value2 = Convert.ToInt32(objHash["Dev"]);
Console.WriteLine("{0},{1}", value1, value2);

  • it is not generic type because key and value are not declared with datatypes.
  • It is slower because it needs to convert value while getting data from hashtable.
  • Return null when requesting value does not exists.

Dictionary

//Create Dictionary
Dictionary<string, int >; objDic = new Dictionary < string, int > ()
{
    {"Hitesh",1},
    {"Dev",2}
};
//Get Value from dictionary
foreach (var d in objDic)
{
    Console.WriteLine("{0},{1}", d.Key, d.Value);
}

  • it is generic type because key and value are declared with datatypes.
  • It is fast because no need to convert value or no need for boxing and unboxing.
  • Return exception when requesting value does not exists.

What is yield in C#.

yield keyword is used for customized iteration in a collection. It is used inside an iterator block which return iterator type. It can not be used directly inside Main method which is void type.

Uses of yield keyword :

  • No need to create temporary list. As it returns value back to caller for every match found.
  • It keeps track of last iterated value. So it does not need to iterate the same value again.

Now lets have an example. We have a list with 20 numbers. But i want to display only even numbers. we can also get even number without using yield keyword. But in this case an extra temp collection need to be created. but with the help of yield keyword we can directly get the even numbers.

static List<int> numbers = new List<int>();
static void NumberList()
{
    for (int i = 1; i<= 20; i++)
    {
        numbers.Add(i);
    }
}

static IEnumerable<int> EvenNumber()
{
    foreach (int i in numbers)
    {
        if (i % 2 == 0) yield return i;
    }
}

static void Main(string[] args)
{
    NumberList();
    IEnumerable<int> EvenNumberList = EvenNumber();
    foreach (int i in EvenNumberList)
    {
        Console.WriteLine(i);
    }
    Console.ReadKey();
}


Output: 2 4 6 8 10 12 14 16 18 20

What is an Obsolete in C#.

Obsolete is an attribute which is used to mark a member of class or class that is no longer in use. You can pass a custom message to this attribute which will be shown when calling these members or class.

[Obsolete("This method is no longer in use! instead use isNumericNew")]
public int isNumeric()
{
    //Code here
}
public int isNumericNew()
{
    //Code here
}


When you will call isNumeric() method. It will show you custom warning as “This method is no longer in use! instead use isNumericNew”.
Note: In Obsolete keyword “O” should be in capital letter.

Security in ASP.NET Web API.

Security can be provide in ASP.Net Web API using Authentication and Authorization.
Authentication means user identity to the system. user is able to login to a website. Example Google Account.
Authentication is provided using HTTP Module and HTTP Message Handler.

HTTP Module- You can configure your project to IIS to use built in authentication i.e; HTTP Module. It uses IPrincipal object for security under which your project is running. You can get the user identity in Thread.CurrentPrincipal. If Identity.IsAuthenticated is true then user is authenticated else user is not authenticated. It is only available to web-hosting.

HTTP Message Handler- This is more flexible as compared to HTTP Module. It can be used with both self-hosting and web-hosting. It filters all the request and pass only request that are requesting to web API route. we can provide different message handlers to different routes. we can get the identity in Thread.CurrentPrincipal.

Authorization means user rights. user is able to read and not allowed to write. Authorization is provided using Authorization Filters. We can provide filters at different level. Filters are called before any controller action.

At Global Level-  We can set filter in global file WebApiConfig.cs. This filter will authorize all the Controllers.

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}


At Controller Level-  We can specify filters to specific Controllers. This filter will authorize all the Controller actions.

[Authorize]
public class EmployeeController : ApiController
{
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}


At Action Level-  We can specify filters at action level. This filter will authorize specific action.

public class EmployeeController : ApiController
{
    [Authorize]
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}


Inside Action Method-  We can customize action return result based on conditions.

public class EmployeeController : ApiController
{    
    public List<Employee> Get()
    {
       if (User.IsInRole("Manager"))
        {
          return EmployeeDAL.GetAllEmployees();
        }      
       else
        {
          //return different result
        }
    }      

    [Authorize(Users="Hitesh,Dev")] //This Action will be available for these users.
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}

CRUD Operations using ASP.NET Web API.

This Tutorial will explain how to implement crud operations using ASP.NET Web API.

Open Visual Studio 2012. Go to create new project tab. Select “Asp.Net MVC 4 Web Application.” Then select Web API from Project Template.

using ASP.NET Web API Crud operation are performed by

GET – To Get data from database
POST – To Insert data into database
PUT – To Update data into database
DELETE – To delete data in database

Create an Employee class in Model folder. And write the below code in the file.

public class Employee
{
    [Display(Name = "Employee ID")]
    public string EmployeeID { get; set; }
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date of Birth")]
    public string DOB { get; set; }

    public string Gender { get; set; }
    public string Nationality { get; set; }
    public string Language { get; set; }
    public string Address { get; set; }
}


Create an EmployeeController Controller file in Controller folder. And write the below code in the file.

public class EmployeeController : ApiController
{
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }
    public void Post(Employee Employee)
    {
        EmployeeDAL.AddEmployee(Employee);
    }
    public void Put(Employee Employee, string id)
    {
        EmployeeDAL.UpdateEmployee(Employee, id);
    }
    public void Delete(string id)
    {
        EmployeeDAL.RemoveEmployee(id);
    }
}


Create a EmployeeDAL file in Model folder for DataBase Operations.

 public class EmployeeDAL
    {
        private static List<Employee> employees;

        public static List<Employee> GetAllEmployees()
        {            
            try
            {
               // Code to fetch data from database
               // create employee list and return
               // return employees;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        public static Employee GetEmployee(string employeeID)
        {           
            try
            {
                // Code to fetch data from database based on employeeID
                // create list and return                           
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void RemoveEmployee(string employeeID)
        {           
            try
            {
                // Code to delete record from database based on employeeID                              
            }
            catch (SqlException ex)
            {
                throw ex;
            }           
        }
        public static void AddEmployee(Employee employee)
        {            
            try
            {    
                 // Code to Insert employee data into database         
            }
            catch (SqlException ex)
            {
                throw ex;
            }            
        }
        public static void UpdateEmployee(Employee employee, string id)
        {           
            try
            {
                 // Code to update employee data into database             
            }
            catch (SqlException ex)
            {
                throw ex;
            }            
        }
    }


Open Index.cshtml file in View folder. And replace body code with the code below.

<div id="body">
    <section class="featured">
        <div class="content-wrapper">
        </div>
        <div class="content-wrapper main-content clear-fix">
            <h2>Search</h2>
            @model WebApiPart1.Models.Employee
            @using (Html.BeginForm())
            {
                @Html.ValidationSummary(true)
                <fieldset>
                    <legend>Employee Search</legend>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmployeeID)
                    </div>
                    <div class="editor-field">
                        @Html.TextBox("SearchEmployee")
                        @Html.ValidationMessageFor(model => model.EmployeeID)
                    </div>
                    <p>
                        <input type="submit" value="Search" onclick="SearchEmployeeById(); return false;" />
                        <input type="submit" value="Get ALL" onclick="GelAllEmployees(); return false;" />
                    </p>
                </fieldset>
                <h2>Employee List</h2>
                <table border="1" id="employees">
                    <thead>
                        <tr>
                            <th><b>Employee ID</b></th>
                            <th><b>First Name</b></th>
                            <th><b>Last Name</b></th>
                            <th><b>DOB</b></th>
                            <th><b>Gender</b></th>
                            <th><b>Nationality</b></th>
                            <th><b>Language</b></th>
                            <th><b>Address</b></th>
                            <th><b>Edit</b></th>
                            <th><b>Delete</b></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <h2>Create</h2>
                <fieldset>
                    <legend>Employee</legend>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmployeeID)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.EmployeeID)
                        @Html.ValidationMessageFor(model => model.EmployeeID)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.FirstName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.FirstName)
                        @Html.ValidationMessageFor(model => model.FirstName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.LastName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.DOB)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.DOB)
                        @Html.ValidationMessageFor(model => model.DOB)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Gender)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Gender)
                        @Html.ValidationMessageFor(model => model.Gender)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Nationality)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Nationality)
                        @Html.ValidationMessageFor(model => model.Nationality)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Language)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Language)
                        @Html.ValidationMessageFor(model => model.Language)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Address)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address)
                        @Html.ValidationMessageFor(model => model.Address)
                    </div>
                    <p>
                        <input type="submit" id="AddUpdate" name="AddUpdate" value="Create" onclick="ADDUpdate(); return false;" />
                        <input type="submit" id="Clear" name="Clear" value="Clear" onclick="ClearForm(); return false;" />
                    </p>
                </fieldset>
            }
        </div>
    </section>
</div>

Asp.Net Web API

Asp.Net Web API

Get ALL Employee List using GET method.

 function GelAllEmployees() {
 $.ajax({
 type: "GET",
 url: "api/Employee",
 contentType: "json",
 dataType: "json",
 success: function (data) {
 $('#employees tbody tr').empty();
 $.each(data, function (key, value) {
 //stringify
 var jsonData = JSON.stringify(value);
 //Parse JSON
 var objData = $.parseJSON(jsonData);
 var id = objData.EmployeeID;
 var fname = objData.FirstName;
 var lname = objData.LastName;
 var dob = objData.DOB;
 var Gender = objData.Gender;
 var Nationality = objData.Nationality;
 var Language = objData.Language;
 var Address = objData.Address;
 $('
<tr>
<td>' + id + '</td>
<td>' + fname +
 '</td>
<td>' + lname + '</td>
<td>' + dob + '</td>
<td>' + Gender + '</td>
<td>' + Nationality + '</td>
<td>' + Language +
 '</td>
<td>' + Address + '</td>
<td><a onclick="GetEmployeeById(id); return false;" id="' + id + '" >Edit</a></td>
<td><a onclick="DeleteEmployee(id);" id="' + id + '" >Delete</a></td>
</tr>

').appendTo('#employees tbody');
 });
 },
 error: function (xhr) {
 alert(xhr.responseText);
 }
 });
 };


Get Employee by ID

 function GetEmployeeById(EmployeeID) {
    var employeeData = {
        "EmployeeID": EmployeeID
    };
    $.ajax({
        type: "GET",
        url: "api/Employee/" + employeeData.EmployeeID,
        contentType: "json",
        dataType: "json",
        success: function (data) {
            //stringify
            var jsonData = JSON.stringify(data);
            //Parse JSON
            var objData = $.parseJSON(jsonData);
            if (objData == null) {
                return;
            }
            $('#AddUpdate').val("Update");            
            $('#EmployeeID').val(objData.EmployeeID);
            $('#FirstName').val(objData.FirstName);
            $('#LastName').val(objData.LastName);
            $('#DOB').val(objData.DOB);
            $('#Gender').val(objData.Gender);
            $('#Nationality').val(objData.Nationality);
            $('#Language').val(objData.Language);
            $('#Address').val(objData.Address);
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
}       


Search Employee by Employee ID

 function SearchEmployeeById() {
            var employeeData = {
                "EmployeeID": $('#SearchEmployee').val()
            };
            if (employeeData.EmployeeID == "") {
                return false;
            }
            $.ajax({
                type: "GET",
                url: "api/Employee/" + employeeData.EmployeeID,
                contentType: "json",
                dataType: "json",
                success: function (data) {
                    //stringify
                    $('#employees tbody tr').empty();
                    var jsonData = JSON.stringify(data);
                    //Parse JSON
                    var objData = $.parseJSON(jsonData);
                    if (objData == null) {
                        return;
                    }
                    var id = objData.EmployeeID;
                    var fname = objData.FirstName;
                    var lname = objData.LastName;
                    var dob = objData.DOB;
                    var Gender = objData.Gender;
                    var Nationality = objData.Nationality;
                    var Language = objData.Language;
                    var Address = objData.Address;
                    $('
<tr>
<td>' + id + '</td>
<td>' + fname +
                    '</td>
<td>' + lname + '</td>
<td>' + dob + '</td>
<td>' + Gender + '</td>
<td>' + Nationality + '</td>
<td>' + Language +
                    '</td>
<td>' + Address + '</td>
<td><a onclick="GetEmployeeById(id); return false;" id="' + id + '" >Edit</a></td>
<td><a onclick="DeleteEmployee(id); return false;" id="' + id + '" >Delete</a></td>
</tr>

').appendTo('#employees tbody');

                },
                error: function (xhr) {
                    alert(xhr.responseText);

                }
            });
        }


Add New Employee

 function AddNewEmployee() {
            var employeeData = {
                "EmployeeID": $('#EmployeeID').val(),
                "FirstName": $('#FirstName').val(),
                "LastName": $('#LastName').val(),
                "DOB": $('#DOB').val(),
                "Gender": $('#Gender').val(),
                "Nationality": $('#Nationality').val(),
                "Language": $('#Language').val(),
                "Address": $('#Address').val()
            };

            $.ajax({
                type: "POST",
                url: "api/Employee",
                data: JSON.stringify(employeeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                    alert("Successsfully added…. " + employeeData.EmployeeID);
                    GelAllEmployees();
                    ClearForm();
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }


Update Employee

function UpdateEmployee() {
            var employeeData = {
                "EmployeeID": $('#EmployeeID').val(),
                "FirstName": $('#FirstName').val(),
                "LastName": $('#LastName').val(),
                "DOB": $('#DOB').val(),
                "Gender": $('#Gender').val(),
                "Nationality": $('#Nationality').val(),
                "Language": $('#Language').val(),
                "Address": $('#Address').val()
            };
            $.ajax({
                type: "PUT",
                url: "api/Employee/" + employeeData.EmployeeID,
                data: JSON.stringify(employeeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                    alert("Successfully updated…" + employeeData.EmployeeID);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }


Delete Employee

function DeleteEmployee(EmployeeID) {
            var txt;
            var r = confirm("Are you sure you want to delete this recored?");
            if (r == true) {
                $.ajax({
                    type: "DELETE",
                    url: "api/Employee/" + EmployeeID,
                    contentType: "json",
                    dataType: "json",
                    success: function (data) {
                        alert("Successsfully deleted…. " + EmployeeID);
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });
                GelAllEmployees();
            } else {
            }
        }


Clear form

  function ClearForm() {
            $('#EmployeeID').val("");
            $('#FirstName').val("");
            $('#LastName').val("");
            $('#DOB').val("");
            $('#Gender').val("");
            $('#Nationality').val("");
            $('#Language').val("");
            $('#Address').val("");
            $('#AddUpdate').val("Create");
        }


Create or Update decider function

  function ADDUpdate() {
            var btn = $('#AddUpdate').val();
            if (btn == "Create") {
                AddNewEmployee();
            }
            if (btn == "Update") {
                UpdateEmployee();
            }
        }


Add this script to get reference of JQuery.

 <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

SQL Helper Class in Asp.Net

SQL Helper class is used in Data access layer which interact with data base with the help of connection string provided. It contains ExecuteNonQuery, ExecuteDataset, ExecuteReader, ExecuteScalar, ExecuteDataTable, ExecuteDataSet and more methods which helps in performing CRUD operations.

Link to download SQL Helper class
SQL Helper Class

Highlight parent menu when child menu is selected in Asp.net.

To highlight the parent menu we need to first find out the selected menu item and then find the top most parent of the selected item. Make the top most parent of the selected menu item selected and apply the selected css. Below is the code implementation.

<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal"  
    BorderStyle="None" 
    StaticEnableDefaultPopOutImage="False"   
    StaticHoverStyle-BackColor="#FFFFFF" 
    StaticHoverStyle-ForeColor="#CC0000" 
    StaticHoverStyle-Font-Names="Arial"
    StaticHoverStyle-Height="16px"
    StaticPopOutImageUrl="~/app_themes/Images/seperator.jpg"
    
    StaticMenuItemStyle-BackColor="#008080"
    StaticMenuItemStyle-ForeColor="#FFFFFF"
    StaticMenuItemStyle-Font-Names="Arial"    
    StaticMenuItemStyle-Font-size="13px" 
    StaticMenuItemStyle-Font-Bold="true"
    StaticMenuItemStyle-HorizontalPadding="20px" 
    StaticMenuItemStyle-VerticalPadding="5px"
    StaticMenuItemStyle-Height="11px"  
  
    DynamicMenuItemStyle-DisappearAfter="6"
    DynamicMenuItemStyle-Font-size="12px" 
    DynamicMenuItemStyle-Font-Bold="true"
    DynamicMenuItemStyle-HorizontalPadding="19px"
    DynamicMenuItemStyle-VerticalPadding="5px"
    DynamicMenuItemStyle-BackColor="#CC0000"
    DynamicMenuItemStyle-Font-Names="Arial" 
    DynamicMenuItemStyle-ForeColor="#FFFFFF" 
    DynamicMenuItemStyle-Height="18.5px" 
    DynamicMenuItemStyle-Width="185px"
    DynamicHoverStyle-BackColor="#AE0000"></asp:Menu>


Add CSS part to your page

<style>
.popout {
    background-color: #008080;
    Color: #FFFFFF;
    font-family: Arial;
    Font-size: 13px;
    font-weight: bold;
    padding-left: 20px;
    padding-top: 5px;
    Height: 11px;
}

.level1 {
    background-color: #008080;
    Color: #FFFFFF;
    font-family: Arial;
    Font-size: 13px;
    font-weight: bold;
    padding-left: 20px;
    padding-top: 5px;
    Height: 11px;
}

.selected {
    background-color: #FFFFFF !important;
    Color: #CC0000 !important;
    font-family: Arial !important;
    Height: 16px !important;
}
</style>


Write the below line of code after binding the Menu Control in Asp.net.
In this code current page url will match with Menu url. “APPLICATION_NAME” is the name of your Application.

foreach (MenuItem MenuItem in Menu1.Items)
{
    if (MenuItem.NavigateUrl.ToUpper() == Request.Url.PathAndQuery.ToUpper().Replace("/APPLICATION_NAME", "~"))
    {
        MenuItem.Selectable = true;
        MenuItem.Selected = true;
        break;
    }
    else
    {
        if (FindRecursiveChild(MenuItem) == true)
        {
            break;
        }
    }
}


If the menu has multilevel items. FindRecursiveChild method is used to find child item. FindRecursiveParent method is used to find top most parent of the selected menuitem.

public bool FindRecursiveChild(MenuItem ChildMenuitem)
{
    bool flag = false;
    foreach (MenuItem MenuItem1 in ChildMenuitem.ChildItems)
    {
        if (MenuItem1.NavigateUrl.ToUpper() == Request.Url.PathAndQuery.ToUpper().Replace("/APPLICATION_NAME", "~"))
        {
            FindRecursiveParent(MenuItem1);
            flag = true;
            break;
        }
        else
        {
            foreach (MenuItem ChildItem in MenuItem1.ChildItems)
            {
                FindRecursiveChild(ChildItem);
            }
            flag = false;
        }
    }
    return flag;
}

public void FindRecursiveParent(MenuItem ChildMenuitem)
{
    if (ChildMenuitem.Parent == null)
    {
        ChildMenuitem.Selectable = true;
        ChildMenuitem.Selected = true;
    }
    else
    {
        FindRecursiveParent(ChildMenuitem.Parent);
    }
}