ASP.NET 4.5 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Create Nested WebGrid in ASP.NET MVC6.

clock November 19, 2014 05:51 by author Mark

How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.

Introduction

In this post, I am explain How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.
Steps :

Step - 1 : Create New Project.

  • Go to File > New > Project > Select asp.net MVC6 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

  • Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

  • Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > OK.

In this example, I have used two tables as below

Step-4: Add Entity Data Model.

  • Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
  • A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
  • Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a class for create a view model.

  • 1st : Add a folder.
  • Go to Solution Explorer > Right Click on the project > add > new folder.
  • 2nd : Add a class on that folder
  • Go to Solution Explorer > Right Click on that folder > Add > Class... > Enter Class name > Add.

Write the following code in this class

using System.Collections.Generic;
namespace MVCNestedWebgrid.ViewModel
{
    public class OrderVM
    {
        public OrderMaster order { get; set; }
        public List<OrderDetail> orderDetails { get; set; }
    }
}

Step-6: Add a new Controller.

  • Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for show nested data in a webgrid.

Here I have added "List" Action into "Order" Controller. Please write this following code

public ActionResult List()
{
    List<OrderVM> allOrder = new List<OrderVM>();
 
    // here MyDatabaseEntities is our data context
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var o = dc.OrderMasters.OrderByDescending(a => a.OrderID);
        foreach (var i in o)
        {
            var od = dc.OrderDetails.Where(a => a.OrderID.Equals(i.OrderID)).ToList();
            allOrder.Add(new OrderVM { order= i, orderDetails = od });
        }
    }
    return View(allOrder);
}

Step-8: Add view for the Action & design.

  • Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

NOTE " Please Rebuild solution before add view

Html Code
@model IEnumerable<MVCNestedWebgrid.ViewModel.OrderVM>

@{
    ViewBag.Title = "Order List";
    WebGrid grid = new WebGrid(source: Model, canSort: false);
}
<div id="main" style="padding:25px; background-color:white;">
    @grid.GetHtml(
    htmlAttributes: new {id="gridT", width="700px" },
    columns:grid.Columns(
            grid.Column("order.OrderID","Order ID"),
            grid.Column(header:"Order Date",format:(item)=> string.Format("{0:dd-MM-yyyy}",item.order.OrderDate)),
            grid.Column("order.CustomerName","Customer Name"),
            grid.Column("order.CustomerAddress","Address"),
            grid.Column(format:(item)=>{
                WebGrid subGrid = new WebGrid(source: item.orderDetails);
                return subGrid.GetHtml(
                    htmlAttributes: new { id="subT" },
                    columns:subGrid.Columns(
                            subGrid.Column("Product","Product"),
                            subGrid.Column("Quantity", "Quantity"),
                            subGrid.Column("Rate", "Rate"),
                            subGrid.Column("Amount", "Amount")
                        )                   
                    );
            })
        )
    )
</div>
Css Code
<style>
th, td {
        padding:5px;
    }
    th
    {
        background-color:rgb(248, 248, 248);       
    }
    #gridT,  #gridT tr {
        border:1px solid #0D857B;
    }
    #subT,#subT tr {
        border:1px solid #f3f3f3;
    }
    #subT {
        margin:0px 0px 0px 10px;
        padding:5px;
        width:95%;
    }
    #subT th {
        font-size:12px;
    }
    .hoverEff {
        cursor:pointer;
    }
    .hoverEff:hover {
        background-color:rgb(248, 242, 242);
    }
    .expand {
        background-image: url(/Images/pm.png);
        background-position-x: -22px;
        background-repeat:no-repeat;
    }
    .collapse  {
        background-image: url(/Images/pm.png);
        background-position-x: -2px;
        background-repeat:no-repeat;
    }
</style>
Write the following Jquery code for make webgrid collapsible
<script>
    $(document).ready(function () {
        var size = $("#main #gridT > thead > tr >th").size(); // get total column
        $("#main #gridT > thead > tr >th").last().remove(); // remove last column
        $("#main #gridT > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
        $("#main #gridT > tbody > tr").each(function (i, el) {
            $(this).prepend(
                    $("<td></td>")
                    .addClass("expand")
                    .addClass("hoverEff")
                    .attr('title',"click for show/hide")
                );
            //Now get sub table from last column and add this to the next new added row
            var table = $("table", this).parent().html();
            //add new row with this subtable
            $(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
            $("table", this).parent().remove();
            // ADD CLICK EVENT FOR MAKE COLLAPSIBLE
            $(".hoverEff", this).live("click", function () {
                $(this).parent().closest("tr").next().slideToggle(100);
                $(this).toggleClass("expand collapse");
            });
        });
        //by default make all subgrid in collapse mode
        $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
            $(this).toggleClass("expand collapse");
            $(this).parent().closest("tr").next().slideToggle(100);
        });    
    });
</script>



ASP.NET 4.5 HOSTING - ASPHostPortal.com | How to Create Dynamic GridView Control in C#/ASP.Net

clock November 18, 2014 06:54 by author Dan

Introduction

In webapplications, one the most widely task is showing a table of information to clients. In Asp.net, we make utilization of the Datagrid, Datalist and Repeater controls. Every day, the need of showing the information will be diverse. Now, we will explain to you about "How to Create Dynamic GridView Control in C#/ASP.Net". Please read the steps carefully.

Implementing Dynamic GridView Control

Utilizing the gridview to show the articles will show the article a little in diverse layout when compared with Datalist. Appoint the below figure, Dynamic Gridview.

Constructing Dynamic GridView

Showing the articles in gridview will be different from showing in datalist. For that, i have made two Template classes :

  • DynamicGridViewTextTemplate
  • DynamicGridViewURLTemplate

Dynamicgridviewtexttemplate class is utilized to include a layout column with label while Dynamicgridviewurltemplate class is utilized to include URL of the article.

TemplateClass for GridView

public class DynamicGridViewTextTemplate : ITemplate
{
    string _ColName;
    DataControlRowType _rowType;
    int _Count;
    public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)
    {
        _ColName = ColName;
        _rowType = RowType;
    }
    public DynamicGridViewTextTemplate(DataControlRowType RowType, int ArticleCount)
    {
        _rowType = RowType;
        _Count = ArticleCount;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + _ColName + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:              
                 Label lbl = new Label();
                 lbl.DataBinding += new EventHandler(this.lbl_DataBind);
                 container.Controls.Add(lbl);              
                break;
            case DataControlRowType.Footer:
                Literal flc = new Literal();
                flc.Text = "<b>Total No of Articles:" + _Count + "</b>";
                container.Controls.Add(flc);
                break;
            default:
                break;
        }
    }
 
  
    private void lbl_DataBind(Object sender, EventArgs e)
    {
        Label lbl  = (Label)sender;
        GridViewRow row = (GridViewRow)lbl.NamingContainer;
        lbl.Text =DataBinder.Eval(row.DataItem, _ColName).ToString();
    }
 
}
public class DynamicGridViewURLTemplate : ITemplate
{
    string _ColNameText;
    string _ColNameURL;
    DataControlRowType _rowType;
 
    public DynamicGridViewURLTemplate(string ColNameText, string ColNameURL, DataControlRowType RowType)
    {
        _ColNameText = ColNameText;
        _rowType = RowType;
        _ColNameURL = ColNameURL;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + _ColNameURL + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                HyperLink hpl = new HyperLink();
                hpl.Target = "_blank";
                hpl.DataBinding += new EventHandler(this.hpl_DataBind);
                container.Controls.Add(hpl);
                break;
            default:
                break;
        }
    }
 
    private void hpl_DataBind(Object sender, EventArgs e)
    {
        HyperLink hpl = (HyperLink)sender;
        GridViewRow row = (GridViewRow)hpl.NamingContainer;
        hpl.NavigateUrl = DataBinder.Eval(row.DataItem, _ColNameURL).ToString();
        hpl.Text = "<div class=\"Post\"><div class=\"PostTitle\">" + DataBinder.Eval(row.DataItem, _ColNameText).ToString() + "</div></div>";
    }
}

Using the Template Class in GridView

Utilizing dynamic template in gridview is not the same as datalist i.e. we will make the dynamic gridview in column wise with header layout, item template and footer layout from the first column till the last.

Steps:

  1. Create a Gridview Object.
  2. Create an instance of TemplateField object.
  3. Instantiate the Dynamic template class with proper ListItemType and assign it to corresponding template property of TemplateField object and finally add this object to the column collection of GridView. Refer the below code for better understanding.

Templates of GridView

TemplateField tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count); 

In the event that you analyze the usage of Datalist, in Gridview we won't make dynamic template for the grid within we make it for the grid's column (Templatefield). Appoint the below code (Using Template class) for clear understanding.

Using Template class

for (int i = 0; i < ds.Tables.Count; i++)
        {
            if (ds.Tables[i].Rows.Count > 0)
            {
                GridView gvDynamicArticle = new GridView();
                gvDynamicArticle.Width = Unit.Pixel(700);
                gvDynamicArticle.BorderWidth = Unit.Pixel(0);
                gvDynamicArticle.Caption = "<div id=\"nifty\" class=\"PostCategory\"> + ds.Tables[i].Rows[0]["Category"].ToString() + " Articles</div>";
                gvDynamicArticle.AutoGenerateColumns = false;
                gvDynamicArticle.ShowFooter = true;
                TemplateField tf = null;
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count);               
              
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Author", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("CreatedBy", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
 
                gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(this.DynamicGrid_RowDataBound);
 
                gvDynamicArticle.DataSource = ds.Tables[i];
                gvDynamicArticle.DataBind();
                phDynamicGridHolder.Controls.Add(gvDynamicArticle);
            }
        }
In the above code (Using Template class), we can unmistakably comprehend that we are making the dynamic template for the gridview's column instead of Datalist where we made the template for the grid itself. To throw more light on this it implies that we are making the first column's header, item and footer and adding it to the gridview's column list through Templatefield article till the last column as I said before.


ASP.NET 4.5 HOSTING - ASPHostPortal :: How make Single Page CRUD Application (SPA) using ASP.NET Web API, MVC and Angular.js

clock November 17, 2014 07:41 by author Mark

How make Single Page CRUD Application (SPA) using ASP.NET Web API, MVC and Angular.js ??

A Single Page Application (SPA) is a web application that fits on a single web page. In this type of application, the server provides static HTML views, CSS and JavaScript and the application then loads data by making Ajax calls to the server. All subsequent views and navigation occurs without a postback to the server. This architecture provides a more fluid user experience just like a desktop application.
In this article, we will create a SPA using ASP.NET MVC, WEB API and Angular.js. Angular.js is a Model-View-* JavaScript based framework for developing SPA applications. Similarly ASP.NET Web API is a good fit for providing data for these type of applications.

  • First Download Hundreds of UI Controls for ASP.NET/MVC, WinForms - Free Trial
  • To create this application, you can use the free new Visual Studio Community 2013
  • Step 1: Open Visual Studio 2013 and create a new Empty MVC application. Name it as ‘MVC_Using_Angular’. In this MVC project,
  • Add a new Sql Server database with the name ‘Company.mdf’. In the database add a new EmployeeInfo table with the following script:

CREATE TABLE [dbo].[EmployeeInfo] (
    [EmpNo]       INT          IDENTITY (1, 1) NOT NULL,
    [EmpName]     VARCHAR (50) NOT NULL,
    [Salary]      DECIMAL (18) NOT NULL,
    [DeptName]    VARCHAR (50) NOT NULL,
    [Designation] VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([EmpNo] ASC)
);

  • Step 2: In the project, add Angular.js scripts using NuGet Package Manager. This will create a new ‘Scripts’ folder in the project, with Angular.js scripts in it.
  • Step 3: To create a model, right-click on the Models folder and add a new ADO.NET Entity Model with the name CompanyEDMX. Select the Database First approach. Select Company.mdf in the Wizard and then the EmployeeInfo table.
  • Step 4: In the Controllers folder, add a new WEB API 2 Controller with actions. Using Entity Framework, select the Model as EmployeeInfo and Context class as CompanyEntities. Name the API controller as EmployeeInfoAPIController. This will generate methods for performing GET, POST, PUT and DELETE operations.
  • Step 5: In the Controllers folder, add an empty MVC controller of the name EmployeeInfo Controller. This controller will have an ‘Index’ action method in it. To add a new Index View, right-click on the Index action method and add an Empty View without Model. In our SPA, we will use the Index.cshtml as a container for dynamically displaying all views. In the EmployeeInfo sub-folder of the Views folder, add an empty partial views for performing various operations. These views will have the following names:

ShowEmployees.cshtml - show all Employees.
AddEmployee.cshtml - allow to add new Employee.
EditEmployee.cshtml - allow to edit an Employee.
DeleteEmployee.cshtml - used to delete selected Employee.

  • Step 6: Open EmployeeInfo Controller and add the following Action Methods in it:

public ActionResult AddNewEmployee()
{
    return PartialView("AddEmployee");
}
public ActionResult ShowEmployees()
{
    return PartialView("ShowEmployees");
}
public ActionResult EditEmployee()
{
    return PartialView("EditEmployee");
}
public ActionResult DeleteEmployee()
{
    return PartialView("DeleteEmployee");
}

The above action methods returns Partial Views added in the Step 5.
Step 7: Now its’ time for us to add the necessary client-side logic for performing operations using WEB API. In the project, add a new folder of the name ‘MyScripts’. In this folder add a new JavaScript file of name ‘Module.js’.
var app = angular.module("ApplicationModule", ["ngRoute"]);


//The Factory used to define the value to
//Communicate and pass data across controllers
app.factory("ShareData", function () {
return { value: 0 }
});
//Defining Routing
app.config(['$routeProvider','$locationProvider', function ($routeProvider,$locationProvider) {
$routeProvider.when('/showemployees',
{
    templateUrl: 'EmployeeInfo/ShowEmployees',
    controller: 'ShowEmployeesController'
});
$routeProvider.when('/addemployee',
{
    templateUrl: 'EmployeeInfo/AddNewEmployee',
    controller: 'AddEmployeeController'
});
$routeProvider.when("/editemployee",
{
    templateUrl: 'EmployeeInfo/EditEmployee',
    controller: 'EditEmployeeController'
});
$routeProvider.when('/deleteemployee',
{
    templateUrl: 'EmployeeInfo/DeleteEmployee',
    controller: 'DeleteEmployeeController'
});
$routeProvider.otherwise(
{
    redirectTo: '/'
});
// $locationProvider.html5Mode(true);
$locationProvider.html5Mode(true).hashPrefix('!')
}]);

  • The above code defines module of name ‘ApplicationModule’. The module defines factory of name ‘ShareData’, which is used to communicate and pass data across controllers. The module also defines routing expressions using $routeProvider.
  • Step 8: In this step, we will add an Angular Service to encapsulate call to WEB API for performing CRUD operations. The code is as follows:

app.service("SinglePageCRUDService", function ($http) {
//Function to Read All Employees
this.getEmployees = function () {
    return $http.get("/api/EmployeeInfoAPI");
};
//Fundction to Read Employee based upon id
this.getEmployee = function (id) {
    return $http.get("/api/EmployeeInfoAPI/" + id);
};
//Function to create new Employee
this.post = function (Employee) {
    var request = $http({
        method: "post",
        url: "/api/EmployeeInfoAPI",
        data: Employee
    });
    return request;
};
//Function  to Edit Employee based upon id
this.put = function (id,Employee) {
    var request = $http({
        method: "put",
        url: "/api/EmployeeInfoAPI/" + id,
        data: Employee
    });
    return request;
};
//Function to Delete Employee based upon id
this.delete = function (id) {
    var request = $http({
        method: "delete",
        url: "/api/EmployeeInfoAPI/" + id
    });
    return request;
};
});

The service has an $http dependency to perform HTTP GET, POST, PUT and DELETE operations.

  • Step 9: Now its time for us to add Angular controllers used for performing CRUD operations. We will add controllers to make call to the Angular service which we created in the Step 8.

ShowEmployeesController.js
//The controller has dependency upon the Service and ShareData
app.controller('ShowEmployeesController', function ($scope, $location, SinglePageCRUDService, ShareData) {
loadRecords();
//Function to Load all Employees Records. 
function loadRecords()
{
    var promiseGetEmployees = SinglePageCRUDService.getEmployees();
    promiseGetEmployees.then(function (pl) { $scope.Employees = pl.data },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
}
//Method to route to the addemployee
$scope.addEmployee = function () {
    $location.path("/addemployee");
}
//Method to route to the editEmployee
//The EmpNo passed to this method is further set to the ShareData.
//This value can then be used to communicate across the Controllers
$scope.editEmployee = function (EmpNo) {
    ShareData.value = EmpNo;
    $location.path("/editemployee");
}
//Method to route to the deleteEmployee
//The EmpNo passed to this method is further set to the ShareData.
//This value can then be used to communicate across the Controllers
$scope.deleteEmployee = function (EmpNo) {
    ShareData.value = EmpNo;
    $location.path("/deleteemployee");
}
});

The above controller is used to make call to SinglePageCRUDService using ‘loadRecords()’ function. This function make use of Promise object to manage asynchronous call to the service. The retrieved data is then saved in the $scope.Employees object, which is this then passed to the View. Functions addEmployee, editEmployee and deleteEmployee are used to Create, Edit and Delete employee respectively. $location is used to load the corresponding view based upon the route defined in the Module.
AddEmpController.js
app.controller('AddEmployeeController', function ($scope, SinglePageCRUDService) {
$scope.EmpNo = 0;
//The Save scope method used to define the Employee object and
//post the Employee information to the server by making call to the Service
$scope.save = function () {
    var Employee = {
        EmpNo: $scope.EmpNo,
        EmpName: $scope.EmpName,
        Salary: $scope.Salary,
        DeptName: $scope.DeptName,
        Designation: $scope.Designation
    };
    var promisePost = SinglePageCRUDService.post(Employee);
    promisePost.then(function (pl) {
        $scope.EmpNo = pl.data.EmpNo;
        alert("EmpNo " + pl.data.EmpNo);
    },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
};
});
The above ‘AddEmployeeController’, is dependent on the ‘SinglePageCRUDService’. The function ‘save’ makes call to the post() function service to post Employee object.
EditEmployeeController.js
app.controller("EditEmployeeController", function ($scope, $location,ShareData,SinglePageCRUDService) {
getEmployee();
function getEmployee() {
var promiseGetEmployee = SinglePageCRUDService.getEmployee(ShareData.value);
promiseGetEmployee.then(function (pl)
{
    $scope.Employee = pl.data;
},
      function (errorPl) {
          $scope.error = 'failure loading Employee', errorPl;
      });
}
//The Save method used to make HTTP PUT call to the WEB API to update the record
$scope.save = function () {
var Employee = {
    EmpNo: $scope.Employee.EmpNo,
    EmpName: $scope.Employee.EmpName,
    Salary: $scope.Employee.Salary,
    DeptName: $scope.Employee.DeptName,
    Designation: $scope.Employee.Designation
};
var promisePutEmployee = SinglePageCRUDService.put($scope.Employee.EmpNo,Employee);
promisePutEmployee.then(function (pl)
{
    $location.path("/showemployee");
},
      function (errorPl) {
          $scope.error = 'failure loading Employee', errorPl;
      });
};
});

The above ‘EditEmployeeController’ is dependent on the ‘SinglePageCRUDService’ and ‘ShareData’ factory. The function getEmployee(), makes call to the getEmployee() function of the service and passes the ShareData.value to it. This is the EmpNo passed from the editEmployee() function from the ShowEmployeesController.
The function save() is used to make call to the put() function of the service by passing EmpNo and the Employee object to complete an edit operation. Both the save() and getEmployee() functions make use of promise object to manage asynchronous calls to angular service.
DeleteEmployeeController.js
app.controller("DeleteEmployeeController", function ($scope, $location, ShareData, SinglePageCRUDService) {
getEmployee();
function getEmployee() {
    var promiseGetEmployee = SinglePageCRUDService.getEmployee(ShareData.value);
    promiseGetEmployee.then(function (pl) {
        $scope.Employee = pl.data;
    },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
}

//The delete method used to make HTTP DELETE call to the WEB API to update the record
$scope.delete = function () {
    var promiseDeleteEmployee = SinglePageCRUDService.delete(ShareData.value);
    promiseDeleteEmployee.then(function (pl) {
        $location.path("/showemployee");
    },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
};
});

The above DeleteEmployeeController has a dependency on the SinglePageCRUDService and ShareData factory. The function getEmployee() makes a call to the getEmployee() function of the service and passes the ShareData.value to it. This is the EmpNo passed from the editEmployee() function from the ShowEmployeesController.
The function save() is used to make call to the delete() function of the service by passing EmpNo and Employee object to complete delete operation. Both the save() and getEmployee() functions make use of promise object to manage asynchronous calls to angular service.

  • Step 10: Now we need to manage our views for performing operations. We will design it as below:

Index.cshtml:
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<body ng-app="ApplicationModule">
    <div>
        <div>
            <div>
                <table>
                    <tr>
                        <td><a href="showemployees"> Show Employees </a></td>
                        <td><a href="addemployee"> Add Employee </a></td>
                    </tr>
                </table>
            </div>
            <div>
                <div ng-view></div>
            </div>
        </div>
    </div>
</body>
@section scripts{
  <script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script> 
  <script type="text/javascript" src="@Url.Content("~/Scripts/angular-route.min.js")"></script> 
  <script type="text/javascript" src="@Url.Content("~/MyScripts/Module.js")"></script>
<script src="~/MyScripts/Services.js"></script>
  <script type="text/javascript" src="@Url.Content("~/MyScripts/ShowEmployeesController.js")"></script>
  <script type="text/javascript" src="@Url.Content("~/MyScripts/AddEmpController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/EditEmployeeController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/DeleteEmployeeController.js")"></script> 
 }
In the above markup, <body> is bound with the ApplicationModule using ‘ng-app’ directive. The ‘ng-view’ will be used to show views which we will be loading dynamically. The Hyperlink elements define links for ‘showemployees’ and ‘addemployee’ route expressions to load corresponding views.
AddEmployee.cshtml
@{
    ViewBag.Title = "AddEmployee";
}
<h2>Add New Employee</h2>
<table>
    <tr>
        <td>EmpNo</td>
        <td><input type="text" ng-model="EmpNo" />  </td>
    </tr>
    <tr>
        <td>EmpName</td>
        <td><input type="text" ng-model="EmpName" />  </td>
    </tr>
    <tr>
        <td>Salary</td>
        <td><input type="text" ng-model="Salary" />  </td>
    </tr>
    <tr>
        <td>DeptName</td>
        <td><input type="text" ng-model="DeptName" />  </td>
    </tr>
    <tr>
        <td>Designation</td>
        <td><input type="text" ng-model="Designation" />  </td>
    </tr>
</table>
<input type="button" value="Save" ng-click="save()" />

The above view uses ‘ng-model’ directive to bind Employee properties with the <input> elements. This view will be loaded with the /addemployee route expression. This is defined in the Module.js. This expression in the URL loads the AddEmployeeController. This controller contains method to post employee details to save in the database.
EditEmployee.cshtml
@{
    ViewBag.Title = "EditEmployee";
}
<h2>EditEmployee</h2>
<table>
    <tr>
        <td>EmpNo</td>
        <td><input type="text" ng-model="Employee.EmpNo" />  </td>
    </tr>
    <tr>
        <td>EmpName</td>
        <td><input type="text" ng-model="Employee.EmpName" />  </td>
    </tr>
    <tr>
        <td>Salary</td>
        <td><input type="text" ng-model="Employee.Salary" />  </td>
    </tr>
    <tr>
        <td>DeptName</td>
        <td><input type="text" ng-model="Employee.DeptName" />  </td>
    </tr>
    <tr>
        <td>Designation</td>
        <td><input type="text" ng-model="Employee.Designation" />  </td>
    </tr>
</table>
<input type="button" value="Save" ng-click="save()" />
<div>{{error}}</div>

The above view is loaded for the /editemployee url. This is defined in the Module.js in the routing configuration and loads EditEmployeeController, which contains a method to fetch employees to be edited and update its values.
DeleteEmployee.cshtml
@{
    ViewBag.Title = "DeleteEmployee";
}
<h2>DeleteEmployee</h2>
<table>
    <tr>
        <td>EmpNo</td>
        <td>{{Employee.EmpNo}}</td>
    </tr>
    <tr>
        <td>EmpName</td>
        <td>{{Employee.EmpName}}</td>
    </tr>
    <tr>
        <td>Salary</td>
        <td>{{Employee.Salary}}</td>
    </tr>
    <tr>
        <td>DeptName</td>
        <td>{{Employee.DeptName}}</td>
    </tr>
    <tr>
        <td>Designation</td>
        <td>{{Employee.Designation}}</td>
    </tr>
</table>
<input type="button" value="Delete" ng-click="delete()" />

The above view is loaded for the /deleteemployee url. This is defined in the Module.js in the  routing configuration. This loads DeleteEmployeeController, which contains a method to fetch employee to be deleted and perform delete operations.

Running Application

Run the application the following View gets displayed

  • Click on ‘Show Employees’. The following result will be displayed with Employee details:
  • The URL used is http://Server/shoewmployees
  • Similarly click on the ‘Add Employee’ link and the following View will be displayed:
  • The URL is http://server/addemployee. Add the Employee details and click on the Save button, the EmpNo will be generated as follows:
  • Click on the ‘Show Employees’ link and the result will be as follows:
  • Click on the ‘Edit’ link of any row and the Edit View will be displayed:
  • The url will be http://Server/editemployee. Here we can update Employee details and click on save. After clicking on the Save we will be back to the first result (exactly the same when we ran the application) where the updated values can be verified. In a similar way, the delete functionality can also be tested.

Conclusion: SPA is the requirement of this new generation of web applications. It provides an easy interaction with WEB interfaces for users looking for a Desktop like experience on the Web. A mashup of client-server technologies like Angular.js and ASP.NET Web API helps you create enterprise ready SPA applications.
Download the entire source code of this article (Github)



ASP.NET 4.5 HOSTING - ASPHostPortal.com :: A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

clock November 14, 2014 06:41 by author Mark

Introduction

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

  • PM> Install-Package jQuery
  • PM> Install-Package angularjs -Version 1.2.26
  • PM> Install-Package Newtonsoft.Json
  • PM> Install-Package MvcScaffolding

Step 3: Create Connection String

Create connection string and name DB name as SPADB
    <connectionStrings>
  <add name="SPAContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=SPADB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 4: Create model

Create Trainer model
    public class Trainer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Venue { get; set; }
}

Step 5: Create Repository

Create repository for Trainer model.

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.
The overall folder structure looks like following. 
SPAContext.cs
    public class SPAContext : DbContext
{
    public SPAContext()
        : base("SPAContext")
    {
    }
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    //
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<SPA.Models.SPAContext>());
    public DbSet<SPA.Models.Trainer> Trainers { get; set; }
    public DbSet<SPA.Models.Training> Trainings { get; set; }
}

TrainerRepository.cs
    public class TrainerRepository : ITrainerRepository
{
    SPAContext context = new SPAContext();
    public TrainerRepository()
        : this(new SPAContext())
    {
    }
    public TrainerRepository(SPAContext context)
    {
        this.context = context;
    }
    public IQueryable<Trainer> All
    {
        get { return context.Trainers; }
    }
    public IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties)
    {
        IQueryable<Trainer> query = context.Trainers;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }
    public Trainer Find(long id)
    {
        return context.Trainers.Find(id);
    }
    public void InsertOrUpdate(Trainer trainer)
    {
        if (trainer.Id == default(long))
        {
            // New entity
            context.Trainers.Add(trainer);
        }
        else
        {
            // Existing entity
            context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
        }
    }
    public void Delete(long id)
    {
        var trainer = context.Trainers.Find(id);
        context.Trainers.Remove(trainer);
    }
    public void Save()
    {
        context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
public interface ITrainerRepository : IDisposable
{
    IQueryable<Trainer> All { get; }
    IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties);
    Trainer Find(long id);
    void InsertOrUpdate(Trainer trainer);
    void Delete(long id);
    void Save();
}

UnitOfWork.cs
public class UnitOfWork : IDisposable
{
    private SPAContext context;
    public UnitOfWork()
    {
        context = new SPAContext();
    }
    public UnitOfWork(SPAContext _context)
    {
        this.context = _context;
    }
    private TrainingRepository _trainingRepository;
 
    public TrainingRepository TrainingRepository
    {
        get
        {
            if (this._trainingRepository == null)
            {
                this._trainingRepository = new TrainingRepository(context);
            }
            return _trainingRepository;
        }
    }
    private TrainerRepository _trainerRepository;
    public TrainerRepository TrainerRepository
    {
        get
        {
            if (this._trainerRepository == null)
            {
                this._trainerRepository = new TrainerRepository(context);
            }
            return _trainerRepository;
        }
    }
    public void Dispose()
    {
        context.Dispose();
        GC.SuppressFinalize(this);
    }
}

Step 6: Add migration

  • Run the following command to add migration
  • PM> Enable-Migrations
  • PM> Add-Migration initialmigration
  • PM> Update-Database –Verbose

Step 7: Create API Controllers

Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.
    public class TrainersController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    public IEnumerable<Trainer> Get()
    {
        List<Trainer> lstTrainer = new List<Trainer>();
        lstTrainer = unitOfWork.TrainerRepository.All.ToList();
        return lstTrainer;
    }
    //// GET api/trainers/5
    public Trainer Get(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        return objTrainer;
    }
    public HttpResponseMessage Post(Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    private IEnumerable<string> GetErrorMessages()
    {
        return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
    }
    // PUT api/trainers/5
    public HttpResponseMessage Put(int Id, Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        else
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    // DELETE api/trainers/5
    public HttpResponseMessage Delete(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        if (objTrainer == null)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
        unitOfWork.TrainerRepository.Delete(id);
        unitOfWork.TrainerRepository.Save();
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Step 9: Create Layout and Home Controller

Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home
Home Controller
    public class HomeController : Controller
{
    //
    // GET: /Home/
 
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Index.cshtml
    @{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Home</h2>
<div>
    <ul>     
        <li><a href="/Registration/Trainers">Trainer Details</a></li>
        <li><a href="/Registration/Trainers/add">Add New Trainer</a></li>
    </ul>
</div>
<div ng-view></div>

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.
    var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });
        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });
        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.
    'use strict';
//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {
    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },
        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },
        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },
        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },
        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };
});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers
    'use strict';
//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});
//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);
    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});
//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates

Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.
All.html
    <div>
    <div>
        <h2>Trainers Details</h2>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <th>Name </th>
                <th>Email </th>
                <th>Venue </th>
                <th>Action</th>
            </tr>
            <tr ng-repeat="trainer in trainers">
                <td>{{trainer.name}}</td>
                <td>{{trainer.email}}</td>
                <td>{{trainer.venue}}</td>
                <td>
                    <a title="Delete" ng-href="/Registration/Trainers/delete/{{trainer.id}}">Delete</a>
                    |<a title="Edit" ng-href="/Registration/Trainers/{{trainer.id}}">Edit</a>
                </td>
            </tr>
        </table>
    </div>
</div>

Add.html
    <form name="trainerForm" novalidate ng-submit="save(trainer)">
    <table>
        <tbody>
            <tr>
                <td>Trainer Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" required ng-minlength="5" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <input name="venue" type="text" ng-model="trainer.venue" />
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <input type="submit" value="Save" ng-disabled="trainerForm.$invalid" />
                    <a href="/Registration/Trainers" class="btn btn-inverse">Cancel</a>
                </td>
            </tr>
        </tbody>
    </table>
</form>
Edit.html
    <form name="trainerFrom" novalidate abide>
    <table>
        <tbody>
            <tr>
                <td>
                    <input name="id" type="hidden" ng-model="trainer.id"/>
                </td>
            </tr>
            <tr>
                <td>Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <textarea name="venue" ng-model="trainer.venue"></textarea>
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <button type="submit" class="btn btn-primary" ng-click="update(trainer)" ng-disabled="trainerFrom.$invalid">Update</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Step 14: Add references to the Layout

Modify the _Layout.cshtml to add references
_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-resource.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/Application/registrationModule.js"></script>
    <script src="~/Scripts/Application/Repository/trainerRepository.js"></script>
    <script src="~/Scripts/Application/Controllers/trainersController.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>

Now run you application and add, delete, modify and get all trainer information. Thanks for your patient! Laughing



ASP.NET 4.5 HOSTING - ASPHostPortal :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



ASP.NET 4.5 Hosting - ASPHostPortal :: Integrate Stripe .Net Payment Processing Library With your ASP.Net 4.5 C# Application

clock November 11, 2014 06:05 by author Ben

The advantages of Stripe

Accepting payment cards on-line has not been less difficult than it's now. Businesses like Stripe have created it simple for builders like ourselves to include sophisticated payment methods into our internet programs without having to bother with the safety compliance and audits which are typically associated with payment card info storage.

 


Stripe lets you preserve customers’ details securely, create custom made payment structures, and also develop customized payment programs for multiple or one customers.

Stripe.Net

Stripe.Net is definitely an open resource library to the Microsoft .NET Framework that permits straightforward integration into your .NET tasks. Today we are going to only be masking the integration of Stripe.Net into an ASP.NET undertaking, however you can study the documentation and find out more regarding how to use the Stripe.Net library on the Stripe.Net Github repository.

Our Project

For your goal of the tutorial, we are going to be producing a brand new ASP.Net internet application. Should you already have an application that you simply want to combine Stripe.Web with, which is amazing! If not, or for those who have by no means developed an ASP.Net application, follow these initial step to obtain up and running.

Very first, we'd like to create the venture. We will do that by opening up Microsoft Visual Studio, and picking Visual C# > Web > ASP.Net Web Forms Application. Notice that we have been utilizing the .NET 4.5 Framework on the best from the window, really feel totally free to change the framework model in your liking. Push OK.

Referencing the Stripe.Net Library

When you have your software open up in Visual Studio, you’re likely to require to put in the Stripe.Net library to use it is classes and methods inside your program. By reading the Stripe.Net Github page, we have discovered the library is obtainable like a NuGet package in Visual Studio, which is the optimal way to integrate the library, so that is how we’re going to do it. Within your solution explorer locate the References listing and proper click on it. You will see a choice labelled “Manage NuGet Packages…”, click that alternative within the dropdown menu.

You'll be prompted with the Control NuGet Packages window. Navigate down the remaining menu and click on Online. Now you'll be able to kind Stripe.Net to the lookup bar in the top left corner in the window, and (if you are related to the world wide web) you will note the Stripe.Net library seem within the center of the window. Set up the package and you'll notice that it installs the json.NET and Stripe.NET package inside the references listing. The explanation this occurs, would be that the Stripe.Net library relies on the json.NET library, so that you must include it into your references directory to ensure that Stripe.Net to operate.

Authentication

The last step of integration in this process, is verifying your account with Stripe. The designated authentication method that Stripe has provided for us is their developer API Key. This key is unique to each Stripe user and verifies your account so Stripe knows which user account all of your transactions belong to.

We only need to place this API Key into our application once by opening up the Web.config file and placing the following code before the </configuration> tag.

<appSettings>
  <add key="StripeApiKey" value="[your API Key]"/>
</appSettings>

Now you’re all set to use the Stripe.NET library in your application! Just remember to reference the json.NET and Stripe.NET libraries in any files you are using Stripe.NET functionality.

 



ASP.NET 4.5.2 Hosting - ASPHostPortal.com to Launch New Data Center in Paris

clock November 10, 2014 10:44 by author Kenny

ASPHostPortal.com to Launch New Data Center in Paris, France on November 2014

ASPHostPortal is known for credible and unswerving web hosting solutions. Apart from the reliability of the ASPHostPortal Uptime, which features 99.9 per cent average uptime, ASPHostPortal also offers outstanding data center which reflects ASPHostPortal high speed and high performance hosting package.  Recently, ASPHostPortal.com launch its new data center in Paris, France on 9th November 2014 with room for more than 10,000 physical servers, and allowing customers’ to meet their France data residency requirements.

The new facility will provide customers and their end users with ASPHostPortal.com services that meet in-country data residency requirements. It will also complement the existing ASPHostPortal.com Amsterdam data center and London data center, to provide European customers redundancy options within the region. The Paris data center will offer the full range of ASPHostPortal.com web hosting infrastructure services, including bare metal servers, virtual servers, storage and networking.

ASPHostPortal offers the perfect combination of affordability and reliability.  They have an excellent uptime history with several months this year boasting more than 99.9% average uptime.  Their hosting package reflects speed and performance.  Their data center can take much of the credit for such superb services. The new data center will allow customers to replicate or integrate data between Paris, London and Amsterdam data centers with high transfer speeds and unmetered bandwidth (at no charge) between facilities.

“With ASPHostPortal, choosing the data center location is a free feature and option to all customers. The customer simply chooses US, Europe, Asia or Australia. It's simple, intuitive and convenient. The option is free, and there will never be any other cost to the user associated with this option,” said Dean Thomas, Manager at ASPHostPortal.co

Clients who have any questions about the feature and the option that is most suitable for their purposes should feel free to contact ASPHostPortal through their 24/7/365 customer support team. ASPHostPortal will help you choose the right option that will best suit your needs.

For more information about new data center in France, please visit http://asphostportal.com/Hosting-Data-Center-France.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and SharePoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET 4.5 Hosting - ASPHostPortal :: WebSockets Utilizing .NET 4.5 With the Asynchronous HTTP Handler and System.Web.WebSockets

clock November 7, 2014 07:32 by author Mark

What is WebSockets?

WebSockets is really a new normal way for net apps to have a persistent relationship in between consumer and server. It allows bidirectional (“full-duplex”) communication between an online browser as well as the web server.

Preparing Windows to support WebSockets

To be able to have Windows 8 (or Windows 2012 for instance) assistance for WebSocket, we initial need to add some features towards the Windows operation system. This may be carried out making use of the “Turn Windows features on or off” control panel product. The features we’d like are :
.NET Framework 4.5 Advanced Services → WCF Services → HTTP Activation

and also: Internet Information Services → World Wide Web Services → Application Development Features → WebSocket Protocol

Creating a generic asynchronous HTTP Handler
Let’s start of with creating a new item of type ASP.NET Handler.

Visual Studio generates a class that implements the IHttpHandler interface. We’ll change that to derive from your abstract base course HttpTaskAsyncHandler. Also, as opposed to employing an interface, we’ll override the IsReusable house and ProcessRequest approach. Every thing is run asynchronously, so we seriously depend upon the async/await keywords and phrases as well as the task class. We’ll retailer the incoming WebSocket instance within a personal house, thus permitting us to get in touch with it’s techniques from inside of our class. The code must search such as this:

using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Web;
namespace StockTickerDemo
{
    public abstract class WebSocketAsyncHandler : HttpTaskAsyncHandler
    {
        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private WebSocket Socket { get; set; }
        public override async Task ProcessRequestAsync(HttpContext httpContext)
        {
            await Task.Run(() =>
            {
                if (httpContext.IsWebSocketRequest)
                {
                }
            });
        }
    }
}


Notice that we’re producing a generic class implementation. Though this class will not outline summary methods, it’s going to only find it is usefulness whenever a specialised class derives from it. Therefore the WebSocketAsyncHandler class is marked summary. Also note that the code we apply is wrapped inside a Task occasion.

Defining the WebSocket concept handlers

When the HTTP ask for is in reality a WebSockets ask for, the WebSocket occasion is saved inside the corresponding home. Then we should also examine the State home of that occasion. Dependent on it’s price, we get in touch with the corresponding virtual approach. The following code illustrates this:


if (httpContext.IsWebSocketRequest)
{
    httpContext.AcceptWebSocketRequest(async delegate(AspNetWebSocketContext context)
    {
        this.Socket = context.WebSocket;
        while ( this.Socket != null || this.Socket.State != WebSocketState.Closed)
        {
            ArraySegment< byte> buffer = new ArraySegment< byte>( new byte[1024]);
            WebSocketReceiveResult receiveResult = await this.Socket.ReceiveAsync(buffer, CancellationToken.None);
            try
            {
                switch (receiveResult.MessageType)
                {
                    case WebSocketMessageType.Text:
                        string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
                        this.OnMessageReceived(message);
                        break;
                    case WebSocketMessageType.Binary:
                        this.OnMessageReceived(buffer.Array);
                        break;
                    case WebSocketMessageType.Close:
                        this.OnClosing( true, receiveResult.CloseStatusDescription);
                        break;
                }
                switch ( this.Socket.State)
                {
                    case WebSocketState.Connecting:
                        this.OnConnecting();
                        break;
                    case WebSocketState.Open:
                        this.OnOpen();
                        break;
                    case WebSocketState.CloseSent:
                        this.OnClosing( false, string.Empty);
                        break;
                    case WebSocketState.CloseReceived:
                        this.OnClosing( true, string.Empty);
                        break;
                    case WebSocketState.Closed:
                        this.OnClosed();
                        break;
                }
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }
        }
    });
}


 And of course the virtual methods:


protected virtual void OnConnecting()
{
}
protected virtual void OnOpen()
{
}
protected virtual void OnMessageReceived(string message)
{
}
protected virtual void OnMessageReceived(byte[] bytes)
{
}
protected virtual void OnClosing(bool isClientRequest, string message)
{
}
protected virtual void OnClosed()
{
}
protected virtual void OnError(Exception ex)
{
}


This is all the code we need to allows us to respond to messages from the client. Now we need to implement the code to send messages to the client. WebSockets allow us to send/receive binary or text messages (asynchronously!). This implementation is as such:


protected async Task SendMessageAsync(byte[] message)
{
    await this.SendMessageAsync(message, WebSocketMessageType.Binary);
}
protected async Task SendMessageAsync(string message)
{
    await this.SendMessageAsync( Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text);
}
private async Task SendMessageAsync(byte[] message, WebSocketMessageType messageType)
{
    await this.Socket.SendAsync(
        new ArraySegment(message),
        messageType,
        true,
        CancellationToken.None);
}


This generic class can be used in any ASP.NET project to implement your own custom WebSockets handler. All you need to do i s derive your class from it and implement the virtual methods.
Deriving a specialized class and implementing the specifics.
Now that we have written the generic class. we can implement the specifics.


namespace StockTickerDemo
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Threading.Tasks;
        public class StockTickerWebSocketAsyncHandler : WebSocketAsyncHandler
    {
        private static double[] FacebookQuotes
        {
            get
            {
                return new double[] { 28.38, 28.45, 27.53, 29.11, 29.23 };
            }
        }
        private static double[] GoogleQuotes
        {
            get
            {
                return new double[] { 758, 760, 764, 765, 769 };
            }
        }
        private double[] ActiveQuote { get; set; }
        protected override void OnMessageReceived( string message)
        {
            // Assignment prevents warning "Because this call is not awaited...Consider applying the 'await' operator
            // This is intentional => fire and forget
            Task task;
            if ( string.Equals(message, "STOP" ))
            {
                IndexTicker .DefaultInstance.Update -= this .IndexTicker_Update;
                this.ActiveQuote = null;
                task = this.SendMessageAsync( "Stopped" );
            }
            else
            {
                if ( this.ActiveQuote == null)
                {
                    IndexTicker .DefaultInstance.Update += this .IndexTicker_Update;
                }
                if ( string.Equals(message, "FB" ))
                {
                    this.ActiveQuote = FacebookQuotes;
                }
                else
                {
                    this.ActiveQuote = GoogleQuotes;
                }
                task = this.SendMessageAsync( "Started" );
            }
        }
        protected override void OnError( Exception ex)
        {
            // Assignment prevents warning "Because this call is not awaited...Consider applying the 'await' operator
            // This is intentional => fire and forget
            var task = this.SendMessageAsync( string.Format( "Something exceptional happened: {0}", ex.Message));
        }
        private void IndexTicker_Update( object sender, IndexTickerEventArgs e)
        {
            // Assignment prevents warning "Because this call is not awaited...Consider applying the 'await' operator
            // This is intentional => fire and forget
            var task = this .SendMessageAsync(this .ActiveQuote[e.QuoteIndex].ToString());
        }
    }


The IndexTicket is a single instance of a class that implements a basic Timer and fire’s an event every 5 seconds. Each time giving a random number between 0 and 4. This number corresponds to n index of the array with quote values. This timer is started and stopped in the Global.asax handlers for the web application. This simulates the stock quote ticker. All that the HTTP Handler does at start/stop is assign a event handler to the timer or remove it. When it handles the timer event it send a text message back to the browser client.

Registering the handler

Now that the handler code is ready, we should tell IIS to use this handler. This is done by registering the handler in the web.config:


<configuration>
  <system.webServer>
    <handlers>
      <add name="StockTickerWebSocketAsyncHandler" verb="*" path="StockTicker"
               type="StockTickerDemo.StockTickerWebSocketAsyncHandler, StockTickerDemo"
               resourceType="Unspecified" />
    </handlers>
  </system.webServer>
</configuration>


The web socket service is reachable through ws://<domain>/<site:ports>/StockTicker. The type attribute tells IIS where it can find the handler.
This concludes the server-side part of the demo.

The client HTML page.

Almost done. Now all we have to do is implement the client-side JavaScript and HTML. The HTML page is simple and straight forward. It has a script reference to jQuery and to the JavaScript files, which we will create further on in this article.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Stock Ticker using Web Sockets!</title>
    <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Scripts/StockTicker.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <input id="stockQuoteFB" type="radio" name="stockQuote" checked="checked"/><label for="stockQuoteFB">Facebook</label>
        <input id="stockQuoteGOOG" type="radio" name="stockQuote" /><label for="stockQuoteGOOG">Google</label>
    </div>
    <div>
        <button id="startButton" value="Start">Start</button>&nbsp;
        <button id="stopButton" value="Stop" disabled="disabled">Stop</button>
    </div>
    <div id="stockQuoteInfo">
    </div>
</body>
</html>


Returned message texts will appear within the stockQuoteInfo div element.

JavaScript

In the JavaScript file we first create a client instance of a WebSocket class and hook up the event handlers so we can we process the messages send from the server :
var stockTickerService;
$(document).ready(function () {
    stockTickerService = new WebSocket( "ws://localhost:55555/StockTicker" );
    stockTickerService.onopen = function () {
        $( "#stockQuoteInfo").append("Connection opened
" );
    }
    stockTickerService.onmessage = function (message) {
        $( "#stockQuoteInfo").append(message.data + "
" );
    }
    stockTickerService.onclose = function () {
        $( "#stockQuoteInfo").append("Connection closed" + "
" );
    }
    stockTickerService.onerror = function (error) {
        $( "#stockQuoteInfo").append(error.data + "
" );
    }


 In the WebSocket constructor we pass the “ws:” url to the WebSocket service as it’s registered in the web.config. Also, we have a little custom JavaScript object to easily communicate the stock quote identifiers:
var NASDAQ = {
    'FACEBOOK' : 'FB',
    'GOOGLE': 'GOOG'
}

Now we only have to wire up the button click handlers to start and stop receiving messages. That is also done in the $(document).ready function:
$("#startButton").click( function () {
    if( $("#stockQuoteFB")[0].checked){
        stockTickerService.send(NASDAQ.FACEBOOK);
    } else {
        stockTickerService.send(NASDAQ.GOOGLE);
    }
    setUIState(true);
});
$("#stopButton").click( function () {
    stockTickerService.send( "STOP");
    setUIState(false);
});

 Now we can run our little web application. Pressing Start will initiate sending the stock numbers to the client:

Pressing the Stop button will send a message to the server, which causes the HTTP Handler to unhook the event. As a result the web server will stop sending messages to the client.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Rangevalidator control in ASP.NET 4.5

clock November 7, 2014 06:26 by author Mark

If you want to understand how RangeValidator  control work in ASP.NET 4.5 Now, we will discuss about How to Use Rangevalidator control in ASP.NET 4.5. Rangevalidator control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age between 1 until 100.

In the codesnippet below, TextBox txtAge get age of the person. If User fill with any number that isn’t between 1 – 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, Age is an integer, the Type is specified as integer. Write the code below:

&lt;asp:TextBox ID="txtAge" runat="server"&gt;&lt;/asp:TextBox&gt;
&lt;asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 &amp; 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" &gt;
&lt;/asp:RangeValidator&gt;

Properties for Rangevalidator control:

Type – Specifies the data type of the value to check. Data types supported include Currency, Date, Double, Integer and String.

MinimumValue – Minimum value that allowed

MaximumValue – Max value allowed in that field

The Rangevalidator only checks if the data is within the allowed range. If you wanna check for a required field, use RequiredFieldValidator. In the Age field, I am using both RequiredFieldValidator & RangeValidator. In this example I am using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Then the error message will always occupy the gap on the screen even if the validation passes.

<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

This pushes “Age is Required” error message to the correct. To correct this we’ve got set Display=”Dynamic”. This renders the error message with style display:none. If a tag has this style, it’ll not occupy space when not visible.
Code-Behind page code
:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls

None – Error message not rendered and displayed next to the control. used to show the error message only within the ValidationSummary control

Static – The error message is displayed next to the control if validation fails. space is reserved on the page for the message although validation succeeds. The span tag is rendered with style visibility:hidden

Dynamic – The error message is displayed next to the control if validation fails. space isn’t reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

 

 

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to enable Multicore JIT in an .NET 4.5 application

clock November 6, 2014 11:20 by author Mark

Multicore Just-in-Time (JIT)

In the .NET framework 4.5, Microsoft has introduced an enhancement of the pervious JIT compiler by making it a Multicore JIT compiler, that runs on the two cores and supports parallelism in the compilation process in order to improve the launch performance during application startup.

From the developer point of view the Multicore JIT is a very cool runtime feature in .NET Framework 4.5 to improve their productivity and speed up the overall performance of an application. Now the developer can benefit from multicore processors to speed up the application compilation process.

The Multicore JIT compiler works in parallel with two cores. Because of the two cores, Multicore JIT can make your application start the process faster at startup. Multicore JIT provides significant improvements to Web based applications as well as Desktop Windows Presentation Foundation (WPF) applications.

Now let's start, how does Multicore JIT work?

Working of Multicore JIT

Nowadays, every PC has at least two cores, so the JIT compiler is built to make the investment worthwhile. Using the Multicore JIT, methods are compiled on two CPUs so that the application is able to reach the end of its startup execution quickly.

The compilation process is done in two cores that run in parallel executing the Multicore JIT compiler. The more effective Multicore JIT will reduce the startup time of an .NET application.

Multicore JIT uses the two modes of operation.

Recording mode: It is the first mode, when JIT compiles the entire program and creates a JIT profile using a profile optimization class and saves the profile that was executed to a given folder to disk.

Playback mode: This mode is used when the application is launched subsequently. Playback mode is used to load the profile that was saved during the Recording mode from the disk using the background JIT thread in order to support the main thread.

 

The feature works by the JIT compiling the methods likely to be executed based on profiles created during previous compilations, that will runs on a separate processor core taking care of the JIT Compilation while the main execution thread runs on a different core.

In the ideal case, the second core quickly gets ahead of the mainline execution of the application, so whenever a method is required it is already compiled. As a result, the main thread doesn't need to do as much compilation, and your application launches faster.

In order to know which methods to compile, the feature generates profile data in the Recording mode that keeps track of the methods that are executed. Then the next time the application runs the call will look for that profile and when it finds it then it plays back; that means it starts compiling all the methods that was saved for that profile.

Note: MultiCore JIT requires a multicore machine to take advantage of its algorithms otherwise the CLR will ignore it on single core machines.

How to enable Multicore JIT in an .NET 4.5 application.

You can use this feature of the runtime to significantly improve the startup times of both client applications and Web sites in .NET framework 4.5
Since ASP.NET applications run in a hosted environment, this feature is turned on for these applications automatically. Therefore JIT compiling using multiple cores is enabled by default in ASP.NET 4.5 and Silverlight 5.

But, if you want to disable this feature

in your ASP.NET 4.5 applications then write the following code in the web.config file.

<system.web>
  <compilation profileGuidedOptimizations="None" />
</system.web>

But in a Windows based application, you will need to enable Multicore JIT feature explicitly.

Let's see how.

It is simple to use Multicore JIT, there is a class in the .NET Framework named "System.Runtime.ProfileOptimization" that you can use to start profiling at the entry point of your application.

Optimization Profilers

The ProfileOptimization is a new type introduced in .Net 4.5 to improve the startup performance of application domains in applications that require the just-in-time (JIT) compiler by performing background compilation of methods that are likely to be executed, based on profiles created during previous compilations.

See the MSDN documentation for more information.

http://msdn.microsoft.com/en-IN/library/system.runtime.profileoptimization.aspx

The two methods that you can call at the entry point of your application.
SetProfileRoot: This method is used to specify the root path, where to save the JIT profile compiled information for optimization.

StartProfile: This method is used to start Multcore just in-time compilation.

You must write the following code in your application constructor in order to enable Multicore JIT.

public App()
{

 ProfileOptimization.SetProfileRoot(@"C:\MyAppFolder");
 ProfileOptimization.StartProfile("Startup.Profile");

}

Now that's all to enable the Multicore feature in your application; the rest of the work will be handled by the CLR automatically.

Conclusion

This is definitely a great feature for improving application launch performance. Applications now startup 50% faster than before. If you are developing an web application, you will no need to do something and if you are developing a Desktop application then you can turn on this amazing feature with only a few lines of code.

 



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in