All posts by Thiyagu

WCF Service Application vs WCF Service library

 

What is WCF ?

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.

Most of the users confuse where to use WCF Service Application and WCF Service library, so here let we find the result for this confusion

where to use Service Application ?

  • If you want WCF services to be host in different platforms,like IIS, Windows service,console application.
    you should choose WCF Library and you can just reference your library from your new host.
  • A service application includes a website host already setup for you.

Where to use WCF Service library ?

  • If you want your Services host to be host in IIS/ASP.NET only, then  we can use WCF Application.
  • A service library is a library of services that a host can reference and startup.

Diff between WCF Service library and WCF Application 1

Creating WCF Service Application

Let we create WCF Service Application by using New –> Project –> Choose WCF Service Application

In the Service Library we having IService1 for the service implementation and Service1 as an App.config file for the configuration (instead of web.config as in the Service Application).

In WCF Service Application, we have the following

  • service contract (IService1.cs),
  • service implementation (Service1.svc.cs), and
  • web configuration file (web.config).

then we  have a service host file (Service1.svc).  This  service host file would not be available in WCF Service Library.

 

Creating  WCF Service library

Let we create WCF Service library by using New –> Project –> Choose WCF Service Library

In WCF Service library ,we have the following

  • service contract (IService1.cs),
  • service implementation (Service1.cs), and
  • App configuration file ( instead of web.config )

From the below image we can see  the service host file is not be present in it, so if needed we want to create it manually

How to consume WCF service in MVC

Here we going to discuss about how to  consuming the WCF service in MVC. For creating WCF refer here

Step 1:

Create a new project and add Service References by right click the project as show below

and in Add Service Reference wizard, enter the address of the service and click ok button to check the availability of the service method. we can also change the namespace to consumed service. Finally click ok to add the service reference to our application

Step 2:

Check whether service added correctly as like below screen by double click the service name to open the object browser window (check with web config file for reference)

If service name space is not added correctly in the above screen then right click the the service and choose ‘Configure Service Reference’, in that wizard unchecked the ‘Reuse types in referenced assemblies’ options and click OK ( it will update in webconfig also )

Step 3:

Create Controller to implement the service.

public ActionResult Index()
{
ServiceReference1.Service1Client uDetail = new ServiceReference1.Service1Client();
string uName = uDetail.DisplayUserName("Aadharsh GK");
return Content(uName);
}

Here i am creating instance for the service and passing the parameter to get result string.

Step 4:

Run the application

Output

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

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.