All posts by Thiyagu

Creating simple WCF Service

What is Windows Communication Foundation

From msdn,Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

An endpoint can be a client of a service that requests data from a service endpoint.

Creating Service

Here i am creating WCF service out side of the application(ie., To  be host in IIS, to use  service by other end)

Step 1:

Open File -> New -> Project (choose WCF Workflow Service Application) like shown below image

Creating WCF 1

Step 2:

After successful creation of project, project hierarchy will shown like below

Step 3:

Let we write the operationcontract in the IService1.cs to consume in the other end point

[OperationContract]
string DisplayUserName(string name);

and then define this contract in the Service1.svc.cs

public string DisplayUserName(string cusName)
{
return “Welcome” + cusName +”to our site!!!”;
}

Output :

After code level completion, check whether its running correctly or not by open the Service1.svc.cs and the press F5 like below, then it will list out the service methods.

Lazy Loading vs Eager Loading

 

What is  Lazy Loding?

As name implies, if we need to load parent data , it will load parent data without loading the related child  data.This is know as lazy loading

Otherwise, data is loaded only on demand (if required)

When to use ?

If we do not want to load the related entity at the same time as when the main entity is loaded/fetched, in this scenario we can use Lazy Loading.

Example :

Here we will see an example for lazy loading with the entity. Let we discuss with two tables, Here we having one table named as  customers which contain customerid,cusotmerName,CusomerMobileNo,customerdetailId ( it refer the primary key of Customerdetails table). then table Customerdetails which contain customerdetailId,customerAddress,Customercity….

var customerList = context.customers.Take(100);

foreach (var Customer in customerList)
{
// Login here
foreach (var CustomerDetail in customerList.Customerdetails)
{
// Login here
}
}

First line of code shows its is working as lazy, because it load only customers table without customerdetails table ( ie., without relations data).

Note :

From the above code, SQL hit will be high ( it will take 100 hits for fetching the customerdetails). Because every time the related data fetch will be happen inside the loop.


What is Eager Loading?

It Load all the related data with the loading object.

When to use ?

If we  want to load the related entity at the same time as when the main entity is loaded/fetched, in this scenario we can use Eager Loading.

Let we see the example for Eager Loading with the entity

var customerList = context.customers.Include(“Customerdetails”).Take(100);

foreach (var Customer in customerList)
{
// Login here
foreach (var CustomerDetail in customerList.Customerdetails)
{
// Login here
}
}

First line show it will fetch all the related entity for the customers table

Note :

Here SQL hit will be only one time , because it will fetch related entity using include keyword (first itself).

Removing unused View Engines in MVC

In this post, we will discuss how to remove View Engines which is not being used by the application.

Why need to remove?

If we remove View Engines which is not being used by application, then it lead to improve the performance in our application.

Discussion:

  •  As default, ASP .NET MVC will search for the webform (.aspx) view engine first  to find the match  naming conventions. After that it start to search for the views that match the Razor view engine naming conventions.

Example : 1

Here i am creating a new controller with default action, but i don’t add view for this action method.

public class SampleController : Controller
{
public ActionResult Index()
{
return View();
}

}

In this situation i am try to run the application to access the sample controller, then it will show output as shown below

Example : 2

Let we  removing  the view engines and register only Razor view engine like below

protected void Application_Start()
{

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());

AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}

Explanation:

  • It can control by placing it in Global.asax file.
  • All Engine will be clear by using ViewEngines.Engines.Clear().
  • ViewEngines.Engines.Add(new RazorViewEngine()) it will again register razor view engine to the application

Output :

 

Implemening CKEditor in MVC 4 Razor application.

How to implement CKEditor in MVC 4 Razor application.

At present may editors are available in market. Here let we discuss about how to implement  simple CKEditor in mvc application

Step : 1

Create simple MVC Razor project

Step :2

Go to http://ckeditor.com/download link and download latest version and place in the project

Step : 3

Then make reference of ckeditor.js in the folder to view as show below

@{
ViewBag.Title = “Index”;
}
<script src=”~/ckeditor/ckeditor.js”></script>
<h2>Index</h2>
<div>@Html.TextArea(“editor”, new {@class = “ckeditor”, @id = “sampleEditor”})</div>

Step 4 :

Run the application

Note :

I have to added class “ckeditor” to  textarea . If we delete ,then it will shows as simple textbox not like editor

How to use multiple model in view

If we have two model classes like Customer details and Employee detail. ASP.NET MVC allows you to pass only One model to a view. The view can be bound with one and only one model. From the above statement, we understood that either pass customer or employee details to the view. Then What if a view requires to display both models?. Let us we discuss the situation as follows:

How to overcome?

In MVC we cannot pass more than one models from a controller to the single view. To overcome this we can use ExpandoObject class.

What is ExpandoObject ?

The .NET 4.0 framework actually includes an ExpandoObject class which provides a dynamic object that allows us to add properties and methods on the fly.

  • ExpandoObject is a sealed type so we can’t use it as a base class
  • It doesn’t serialize to XML or DataContractSerializer/DataContractJsonSerializer

From msdn, Represents an object whose members can be dynamically added and removed at run time.

When to use ?

In some time we need to display more than one type of model data in to the single view. For example i am having two models namely CustomerDetails and EmployeeDetails and if i need to display both information in single view then we can use the ExpandoObject.

Example :

Model :

Creating simple model namelu CustomerDetail.cs and EmployeeDetail.cs as shown below.

CustomerDetail.cs

public class CustomerDetail
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerAdress { get; set; }
}

EmployeeDetail.cs

public class EmployeeDetail
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeAdress { get; set; }
}

Controller :

public ActionResult Index()
{
dynamic detailModel = new ExpandoObject();
detailModel.EmployeeDetail = GetEmployeeDetail();
detailModel.CustomerDetail = GetcutomerDetail();
return View(detailModel);
}
private List<EmployeeDetail> GetEmployeeDetail()
{
List<EmployeeDetail> employeeDetail = new List<EmployeeDetail>();
employeeDetail.Add(new EmployeeDetail { EmployeeId = 1001, EmployeeName = "Aadharsh", EmployeeAdress = "xxxxxx" });
employeeDetail.Add(new EmployeeDetail { EmployeeId = 1002, EmployeeName = "GK", EmployeeAdress = "xxxxxx" });
return employeeDetail;
}
public List<CustomerDetail> GetcutomerDetail()
{
List<CustomerDetail> cutomerDetail = new List<CustomerDetail>();
cutomerDetail.Add(new CustomerDetail { CustomerId = 256, CustomerName = "Kavitha", CustomerAdress = "xxxxxx" });
cutomerDetail.Add(new CustomerDetail { CustomerId = 257, CustomerName = "Gnanam", CustomerAdress = "xxxxxx" });
return cutomerDetail;
}

View :

@using Multiple_Models_in_Single_View.Models;
@model dynamic
@{
ViewBag.Title = "Detail Page";
}
<div>============================</div>

<table>
<tr>
<th>Emp Id</th>
<th>Emp Name</th>
<th>Emp Adress</th>
</tr>
@foreach (EmployeeDetail employeeDetail in Model.EmployeeDetail)
{
<tr>
<td>@employeeDetail.EmployeeId</td>
<td>@employeeDetail.EmployeeName</td>
<td>@employeeDetail.EmployeeAdress</td>
</tr>
}
</table>
<div>============================</div>
<table>
<tr>
<th>Cus Id</th>
<th>Cus Name</th>
<th>Cus Adress</th>
</tr>
@foreach (CustomerDetail cutomerDetail in Model.CustomerDetail)
{
<tr>
<td>@cutomerDetail.CustomerId</td>
<td>@cutomerDetail.CustomerName</td>
<td>@cutomerDetail.CustomerAdress</td>
</tr>
}
</table>

OUTPUT

How to map multiple urls to the same controller/Action

In this post we are going to discuss about how to map multiple URLs to the same controller/Action by the custom route.

Below example shows how write custom route

Custom code must be place inside the RouteConfig.cs.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute( "MultipleUrls", "{phaseone,phasetwo}", new { controller = "home", action = "index", id = "" } );

routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
}
}

Explanation :

  •  MultipleUrls : Descripe the name of the route
  •  {phaseone,phasetwo} : controllers name with comma separator
  •  new { controller = “home”, action = “index”, id = “” } : It describe, where want to redirect for the above controllers

 OUTPUT :

Thanks to my friend manjunath for rise this question and make me find this solution

 

Action Result Return Type in MVC 4

ActionResult is a return type of a controller method in ASP.NET MVC. It help us to return models to views, other return value, and also redirect to another controller’s action method. There are many derived ActionResult types in MVC that we use to return the result of a controller method to the view.

What is ActionResult ?

  •  An ActionResult is a return type of a controller method in MVC.
  •  ActionResult are more specific for a particular view
  •  It is abstract class that has many subtypes

Types of ActionResult :

  • ViewResult
  • PartialViewResult
  • ContentResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • EmptyResult
  • FileResult
  • JavaScriptResult

Let we start discussion about types of ActionResult in one by one…

ViewResult :

  • It renders a specified view to the response stream.

 Example :

public ViewResult Index() {   return View(“sampleResult”); }

PartialViewResult:

  • Renders a specifed partial view to the response stream.

Example :

public PartialViewResult SamplePartialView()
{    return PartialView(“_LoadSamplePartial”); }

Note :

  • It will load the partial view to the main view

ContentResult :

  • It display the response stream without requiring a view .(like a plain text).

Example

public ActionResult About()
{
ViewBag.Message = “Your app description page.”;
return Content(“Sample Content Action”);
}

It simply write the string value in the page

RedirectResult :

  • It is used to perform an HTTP redirect to a given URL.

Example :

public ActionResult SampleRedirectResult()
{  return Redirect(“http://www.google.com/”); }

RedirectToRouteResult :

  • RedirectToResult is used to redirect by using the specified route values dictionary.

Example :

public ActionResult SampleRedirectToRouteResult()
{
return new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new
{
controller = “Sample”,
action = “SampleRedirectToRouteResultTest”,
Id = new int?()
}));
}

JsonResult :

  • Action methods return JsonResult (JavaScript Object Notation result) that can be used in ajax based application.

Example :

public ActionResult SampleJsonResult
{
… Logic here
return Json(sampleinfo);
}

EmptyResult : 

  • It return  NULL that is EmptyResult
  • return instance of EmptyResult class

Example :

return new EmptyResult();

FileResult :

  • Return a file from an action. (Pdf,Excel,image file,Html…)

Example :

public FileResult DownloadCustomerDetails()
{
//Parameters to file are
//1. The File Path on the File Server
//2. The content type MIME type
//3. Name of file To be save by Browser
string contentType = “application/pdf”;
string filepath = AppDomain.CurrentDomain.BaseDirectory + “/FileFolder/CustomerDetails.pdf”;
return File(filepath, contentType, “CustomerDetails.pdf”);

Output:

After calling the action method in browser , the file will ask for download as shown in below

http://localhost:52877/home/DownloadCustomerDetails

}

JavaScriptResult:

  • To improve clean separation of concerns by introducing the JavaScriptResult ActionResult.
  • Release notes says, “the JavaScriptResult class is used to execute JavaScript code that is created on the server and sent to the client.”

For Example,

Controller :

public JavaScriptResult SampleJavaScriptResult()
{
var s = “alert(‘Hi’)”;
return JavaScript(s);
}

View :

<script type=”text/javascript” src=”@Url.Content(“~/Home/SampleJavaScriptResult”)”></script>

Note :

The dynamic script file will be generated based on the action name (SampleJavaScriptResult)

Output:

After press F5, it will create the dynamic script file “SampleJavaScriptResult” which will append the content from action

Then it will display the alert message which was return from the action “SampleJavaScriptResult” as show in below

REST Services (Representational state transfer)

What is REST Services :

Definition : 1

  • The REST stands for Representational State Transfer.
  • REST is a set of principles that define how Web standards, such as HTTP and URLs, are supposed to be used.

Definition : 2

In simple, REST is a architectural style construct based on the principle using the Web fundamentals.

From msdn,

  • An architectural style, sometimes called an architectural pattern, is a set of principles.
  • An architectural style improves partitioning and promotes design reuse by providing solutions to frequently recurring problems.
  • You can think of architecture styles and patterns as sets of principles that shape an application.

Let we see Fundamentals/principles details

Resource :

In REST,  every thing will be treat as resource, for example

www.aadharsh.com/image/birthday (image resource)
www.aadharsh.com/user/GKA (Dynamically pulled resource)
www.aadharsh.com/audio/audfile (audio resource)

from above, first URL shows the image resource as the output… same thing for all other URL with different identifiers. Here image/audio/video/static page… every thing are treated as resource instead of thinking physical file/data.


Unique identifier

Every resources identifies by an URL, in earlier for identify all the resource by URL.
For example to identify the user detail we use like below

www.aadharsh.com/GetUserDetails.aspx

Now in REST, added one more constrain. That is every resources  must represent by an unique URL, For example

www.aadharsh.com/GetUserDetails/Kavi
www.aadharsh.com/GetUserDetails/Gnanamurugan

Here if we want to get the user detail for the kavi then we can get GetUserDetails/Kavi in same way for other users ( we want to append username at the end) not as before like this

www.aadharsh.com/GetUserDetails?Name=Kavi
Instead of using Generic page, REST point the unique identifiers to identify the resource

Uniform Interface :

Use simple and uniform interface, for example if client want to Add/Insert/Select/Delete user detail, we use like below method name to perform the above operation

  •   AddUserDetails (it combine with PUT)
  •   InsertUserDetails (it combine with PUT)
  •   SelectUserDetails (it combine with GET)
  •   DeleteUserDetails (it combine with DELETE)

When we watch closely the method name, it seems to be inconsistent and difficult to remember,so REST says to uses simple and uniform interface. This can be obtain by the uniform methods of HTTP protocol and combine the name with the resource operation.Let we see the HTTP protocol methods

  •  GET : Get the Resource
  •  PUT : Create/Update the resource
  •  DELETE : Delete the resource
  •  POST : submit the data to the resource

Communication should be representation :

Representation is nothing but request and response between the client and the server.

Stateless :

Each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server. In simple, HTTP have nothing to indicates when a session starts or ends.

Creating Web API using MVC 4 with Razor

Here we will create simple Web API Application using MVC 4 with Razor

What is Web API?

From msdn, ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

When to use Web API?

  •    Web API when you want to create a resource based services over HTTP that can use the full features of HTTP    (like   URIs, request/response headers,various content formats).
  •   Use Web API when we want to expand service at wide way like mobile,browser,tablet…
  •   If we need a Web Service and without using SOAP, then ASP.Net Web API is best choice.

why we use Web API ?

WCF gives you the flexibility to use other protocols, but the REST implementation is a bit more complicated when compare to Web API

For Detail about REST , Go here

Example :

Step : 1

Create new project -> choose MVC Web Application and click ok

Step : 2

Next, in project template choose Web API and click ok


After creating Web API application we can see the same structure as MVC Application but in App_start, separate router file is created for Web API (that is WebApiConfig.cs) as shown below.

Step : 3

Open Values controller (which was created in default for Web API) ie., ValuesController


Here i made with simple changes like below ,

public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string

[] { “aadharsh”, “GnanamKavi” };
}
public string Get(int id)
{
if (id == 1){
return “Get value using id” +”–>”+ id;
}
if (id == 2){
return “Get value using id” + “–>” + id;
}
return null;
}
}

NOTE :

  •   In MVC Application controller implements Controller interface but in Web API controller implements      ApiController as base
  •   In web API controller, action methods are actually HTTP methods ie., GET,PUT…

Step :  4

Run the Application. When we run the Web API using below URL,

http://localhost:53934/api/Values :   The Web API route to Get() method (WebApiConfig.cs) as shown below, because there is no parameter append after the method (URL without parameter)

http://localhost:53934/api/Values/1 :  The Web API route to Get(int id) method (WebApiConfig.cs) as shown below, because there is a parameter append after the method (URL with parameter)

Note :

  • Web API is a light weight architecture and good for various device which have limited bandwidth like smart phones.
  • It also supports the MVC features such as routing, controllers, action, filter… this makes  us very simple and robust
  • Using Web API, we can get the resource in various format (like xml,json..)
  • let we see how to call PUT,DELETE methods with simple explanation

  First we want to include in web.config

<system.webServer><modules runAllManagedModulesForAllRequests=”true”></modules ></system.webServer>

then we can call using jquery (type : ‘PUT’/’DELETE’/’POST’/’GET’)

$.ajax({
url: ‘/api/Values/’ + truckId,
type: ‘PUT’,
contentType: “application/json; charset=utf-8”,
data: json,
success: function (results) {
}
});

How to create Unorderlist using HTML Helpers with custom Attribute

Creating Unorderlist using HTML Helpers with custom Attribute

Please refer to know how to use Extend HTML Helpers   here

.CS File

namespace CustomeHelpers
{
public static class CreatingUnorderedList
{
public static MvcHtmlString CreatingUnorderedListUsingAttribute(this HtmlHelper htmlHelper, string name, string value, string id)
{
var builder = new TagBuilder(“li”);
builder.Attributes

[“id”] = id;
builder.Attributes[“type”] = “radio”;
builder.Attributes[“name”] = name;
builder.Attributes[“value”] = value;
//creating Custom attribue in the Element
builder.Attributes[“listId”] = name + “-” + id;
if (id == “0”)
builder.SetInnerText(“Start List ” + id);
else if (id == “4”)
builder.SetInnerText(“End List ” + id);
else
builder.SetInnerText(“List ” + id);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
}
}

Note : SetInnerText used for set the text/value for the element

View

<h2>Generating Unordered List using HTML Helpers</h2>
<ul>
@for (var loop_index = 0; loop_index < 5; loop_index++)
{
@Html.CreatingUnorderedListUsingAttribute(“custom_txtbox”, “Custom Helper Method”,loop_index.ToString())
}
</ul>

OUTPUT :



Below image shows  Unordered List with custom attribute listId in the li element