We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Thursday, February 1, 2018



Full Tutorial of ASP .Net MVC in easy way (part-3)



Filter in Asp.Net mvc


->Asp .Net mvc introduced a new concept called filter.

-> Filter used add additional logic at the time of processing the request.

->Filters are executed either before/after action method processing.

-> Filters are implemented with the help of corresponding attribute class.

-> Filters with addition logic or for our action method.

->This logic is referred preprocessing post processing logic.


Types of Filters

In MVC5  filters are 4 types

1. Authentication

2. Authorization

3. Action Filter

4. Result filter

5. Exception filters


Note:




->To implement any custom filter we need inherit a class called “FilterAttribute”.

->We have to implement corresponding interface base on t



.Execution Filter







1. Create MVC Application and “Filter” Folder.

2. Add a class file to “Filter” folder Filter Name MycustomFolder.cs

3. Define the Mycustomefilter class as follow.

Using System.Web.Mvc;
Using System.IO;

namespace MVCApplication.Filters

{

Public class myCutomFilterAttribute: FilterAttributeIActionFilter

{
Public void OnActionEcecuted(ActionExecutedContextFilter context)
{
StreamWrite sw=new SteramWriter(“D:\\filterLog.txt”,true);

Sw.WriteLine(“Action method Execution completed at”+DateTime.Now.Tostring());
Sw.WriteLine(“-----“);
Sw.Close();
}
Public void OnActionExecuting(ActionExecutingContext FilterContext)

{
StreamWriter sw=new StreamWriter(“D:\\FilterLogs.txt”,true);
Sw.writeLine(“Action method execution starts at”+DateTime.Now.Tostring());
Sw.Close();
}
}
}
Add HomeController and prepare requested Action method with Mycustom.Filter

Using mvcApplicatuon.Filters;

namespace mvcApplication.Controllers

{
Public class HomeController:Contoller
{

[MycustomFilter]
Public ActionResult Index()
{
}
}

View

<h2>ASP.Net MVC Filter DeptApplication<h2>
<hr/>

What is Layout View?

->Layout view is a special type of view in to master page in Asp.Net webAplication.

->Layout views are used to maintain a common layout (structure) across all of the views in our application.
-> It act as a via template that we can create rest of the views with the same structure.

Advantages

->We can avoid duplications of code in view pages.
->Application development will be faster and easier.
->Reduce the time and effort of programmer.

Files that are involved in logout views.

1.~/views/shared/_Layout.cshtml

2.~/views/_viewsStart.cshtml

Important points related Layout
1. @viewBagTitle

-> The page title will be inserted here. The title which we set in context views(eg:index.cshtml)


2. @RenderBody()

-> At the time of execution, razor engine will execute the corresponding content views and result will be placed at “ @RenderBody()” location.

Note:

We can’t use “@RenderBody()” method more than one time in the same layout.

FAQ: - What is the purpose of _viewstart.cshtml?

Ans:-The _viewstart.cshtml file will execute before processing of each view page.

>Generally this file contains setting the layout name that is used processing the views.

-> Location: ~/view/_viewstart.cshtml
->RenderBody()""at "uslt razor engine will execute the code

Steps for creating custom Layout

1. Add view page to “shared” folder

Name: _Layout2

Unchecked the “use a layout or master page” check.

Click “Add” button.

2. Add the following items in our layout file (_layout2.cshtml)
a) <title> @viewBag.Title</title>

b) @RenderBody

3. Refer Layout2.cshtml at the time of adding our regular view for action methods.

->Right click an Action method.

->Add view.

->Click browse button

-> Select “_layout2.cshtml”.

-> Click “Ok”.

->Click “Add” button.
Note:

Now the above view is returning “_Layout “instead of _Layout”.

Cashing of Asp.Net MVC

->Cashing is one of the important concepts in web applications to improve the performance of the web application.

->Cashing provides a way to store frequently accessed page output and reusing cached copies.
->Asp.net MVC supports the cashing so that we case the processed action method output.

Advantage of cashing

->Reduce server round trips.
-> Reduce database server round-trips(if db programming include)
-> Reduce network traffic.
->Avoid processing time for every in request.

Implementation

->Cashing in MVC is implemented by using [outputcashe] attribute.

->We have to apply [outputcashe] at action method so that we can cache the executed output of requested action.

Uses:
[outputCashe(Duration=n, Location =outputCashLocation.Server,varByParam=”none”)]
outputcashLocation: it is a implementation belong to System.UI namespace.

Example:
Create ASP.Net MVC Application and Add Emp table by using Entity framework “Database first” approach.
 Add HomeController and define the following. HomeController.cs

using System.Web.UI;

using MVCApplication.Model;
namespace MVCApplication.Controlls

{
Public class HomeController:Controller

{

TestDbEntities db=new TestDBEntities();

[OutputCache(Duration=20, Location=OutputCashLocation.server,varyByParam=”none”)]

Public ActionResult Index ()
{

Response.Write(“This action method is processed at:”+DataTime.Now.ToString(“T”));

List<Emp>empList=db.EMPs.ToList();

Return view(empList);

}

[OutputCashe(Duration=90,location=OutCacheLocation.Server,varyByParam=”dno”)]

Public ActionResult Index(int dno)

{
Response.Write(“This action method is processed at:”+ DateTime.Now.Tosting(“T”);

Var q1=from e1 in db.Emps.ToList()

Where e1.DEPTNO==dno Select e1;

Return view(q1);

}
}
}
Step3

Add view page for above action methods.

Strongly typed views with scaffold template (List);

Step4.

Run and Test

Security in ASP.NET MVC Applications

->Asp.Net MVC applications also provide different option like normal ASP.NET web Application.

->Similar to Asp.Net we have to use web.config file to enable security related setting.
->These setting should be provided in “web.Config” that is in root folder.

1. <Authentication> tag is used to configure which type of security that we are using in our application.
2. <Authorization> tag is used to allow or deny the user.

Apply security for MVC Application

We can apply the security for MVC application at three different levels.
1. Application Level-
->Web.config<authorization> tag
2. Controller Level-

-> [Authorize] attribute

[Authorize]

Public class HomeController: Contoller

{
//required action methods
}

3. Action method Level-

[Authorize]

Implementation

1. Provide corresponding setting in web.config.

2. Create Account Controller with Login Action with corresponding code.

Library Information:

namespace: System.web.Sequrity

Class: FormsAuthentication

Method: Redirect FormLoginPage()

3. Apply [Authorize] attribute to controller/action to provide security.

Application Level(in web .config)

<authorization>

<deny users=”?”/>

</authorization>

Create ASP.NET MVc Application to apply security by using FormAuthentication.

1. Provide corresponding setting in web.config
<authentication mode=”Forms”>
<Forms LoginUrl=”~/Account/Login” defaultUrl=”/” name=sec_ck” timeout=”20”/>

</authentication>

2. Add AccountController and define Login () action methods as follows.


AccountController.cs
using System.Web.Security;
namespace MVCApplication.Contoller
{
Public class AccountCntoller:Contoller

{

Public ActionResult Login()

{

return view();
}

[HttpPost]


Public ActionResult Login (string uid,string pwd)

{

If(uid==”admin” && pwd==”admin123”)

{
FormsAuthentication.RedirectedformLoginPage(uid,false);

{

else

{

viewBag.Message=”Invalid userid or password”;

}return view();

Login.cshtml

<h2>Login Page</h2>

@using(Html.BeginForm())

{
@Html.Label (“User Id:”)

@Html.TextBox (“uid”)

<br/>

@Html.Label (“Password:”)

@Html.Password(“pwd”)

<br/>

<input type=”submit” value=”Login” name=”submit”/>

}
@{

If(IsPost==true)

{
<span>@viewBag.Message</span>

}
Add HomeController
HomeController.cs
namespace mvcApplication.Contollers
{
[Authorize]

nublic class HomeController:Conroller
{
Public ActionResult Index()
{
return view();
}
public ActionResult Index2()

{
return view();
}

Add view page for above action methods

4. Execute the application

Note:
->Try to apply security for action methods by using [Authorize] attribute.
-> Project level with <authorization> tag.

AJAX

AJAX programming with jQuery in ASP.Net MVC.

Q.What is AJAX?

-> AJAX stands for Asynchronous JAVA Script and XML.

Using AJAX

->We can communicate with server implicitly.

-> We can implement partial page updates.
->Actually it is client side programming technique to communicate with sever.

Q. How to implement AJAX programming?

-> We can implement AJAX by using java script.

->We can also use any client side frameworks like jQuery.

Q. What is jQuery?

->JQuery is Java Script library.
-> JQuery provides collection of predefined methods to implement any kind of JavaScript related activities easily.
->We can also communicate with server by using AJAX based method of jQuery.

Note:

To implement jQuery we have to downloaded JQuery file(*.JS) from www.JQuery.com.

->by default every MVC Application provides JQuery- 1.7.1.js file under

“Scripts” folders.(“Empty “template does not includes).
How to add JQuery/JavaScript code in view page.

->Bydefalut layout page will include jQuery file so that every view will get automatically.

-> We have to use selector ($()) to access any html element.

Eg: $(“#b1”).click ()


$(“#text1”).val()


$.get();

$(“#p1”).html()

etc

NOTE:

->If we want to write any JavaScript in view pages we have to use the following code block.


@section scripts

{

<script>

//js code

//JQuery code

</script>

}
Ex: - Create MVC application to display employee count based on deptno use jQuery to communicate with server.

1. Create MVC Application and add “Emp” table to models using Entity Framework Database first approach.

2. Add HomeController and define following action methods.

HomeController.cs

using mvcApplication.Model;

namespace class HomeController:Controller

{
TestDbEntities db=new TestDbEntities();
Public ActionResult Index()
{
return view();
}
Public string GetDept(int id)

{
var q1=from e1 in db.EMPs.ToList
Where e1.DEPTNO=id

Select e1;

Int n=q1.count ();
String str=”Department no:”+id;
Str=str +”<br/>Employee count:”+n;
return str;
}

}

}
Index.cshtml
<h2> Ajax program in MVC with jQuery </h2>

<hr/>
Enter id:<input type:”text” name =”t1” id=”t1”/>

<br/><br/>

<input type=”button” id=”b1” value =”Get message”/>

<br/><br><p id=”p1”></p>

@section scripts

{
<script src=”JQuery 1.11.1.min.js”>
</script>

<script>
$(document).ready (function(){

$(“#b1”).click (function(){

var n=$(“#t1”).val();
var url=”Home/GetDate/”+n;

$.get(url,function(data){
$(“#p1”).html(data);
});
});
</script>
}
Getting Started with ASP.NET Web API 2


Create a Web API Project

We will use ASP.NET Web API to create a web API that returns a list of products. The front-end web page uses jQuery to display the results.

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and thenProject.
In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Name the project "ProductsApp" and click OK.
In the New ASP.NET Project dialog, select the Empty template. Under "Add folders and core references for", check Web API. Click OK.

We can also create a Web API project using the "Web API" template. The Web API template uses ASP.NET MVC to provide API help pages. I'm using the Empty template because I want to show Web API without MVC. In general, we don't need to know ASP.NET MVC to use Web API.

Adding a Model

A model is an object that represents the data in our application. ASP.NET Web API can automatically serialize our model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

Let's start by creating a simple model that represents a product.

If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.
Name the class "Product". Add the following properties to the Product class.namespace ProductsApp.Models { public class Product { public int Id { get; set; } public string Name { get; set; }public string Category { get; set; } public decimal Price { get; set; } } }

Adding a Controller

In Web API, a controller is an object that handles HTTP requests. We'll add a controller that can return either a list of products or a single product specified by ID.

Note: If we have used ASP.NET MVC, we are already familiar with controllers. Web API controllers are similar to MVC controllers, but inherit the ApiController class instead of the Controller class.

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.
In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.
In the Add Controller dialog, name the controller "ProductsController". Click Add.
The scaffolding creates a file named ProductsController.cs in the Controllers folder.
We don't need to put our contollers into a folder named Controllers. The folder name is just a convenient way to organize our source files.
If this file is not open already, double-click the file to open it. Replace the code in this file with the following:using ProductsApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; namespace ProductsApp.Controllers { public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Sohan", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Sonu", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Ramu", Category = "Hardware", Price = 16.99M } }; public IEnumerable<Product> GetAllProducts() { return products; } public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } } }

To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, we would query a database or use some other external data source.

The controller defines two methods that return products:
The GetAllProducts method returns the entire list of products as an IEnumerable<Product> type.
The GetProduct method looks up a single product by its ID.
That's it! We have a working web API. Each method on the controller corresponds to one or more URIs:

Controller Method

URI

GetAllProducts

/api/products


GetProduct

/api/products/id

For the GetProduct method, the id in the URI is a placeholder. For example, to get the product with ID of 5, the URI is api/products/5.
Calling the Web API with Javascript and jQuery
In this section, We'll add an HTML page that uses AJAX to call the web API. We'll use jQuery to make the AJAX calls and also to update the page with the results.

In Solution Explorer, right-click the project and select Add, then select New Item.

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".

Replace everything in this file with the following:

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
 <head> <title>Product App</title> </head>
 <body>
 <div>
 <h2>All Products</h2> 
<ul id="products" /> </div>
 <div> <h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
 <input type="button" value="Search" onclick="find();" />
 <p id="product" /> 
</div> 
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script> 
var uri = 'api/products'; 
$(document).ready(function () { // Send an AJAX request $.getJSON(uri).done(function (data) 
{ // On success, 'data' contains a list of products.
 $.each(data, function (key, item) {
 // Add a list item for the product.
 $('<li>', { text: formatItem(item) }).appendTo($('#products')); 
});
 });
 }); 
function formatItem(item) { return item.Name + ': $' + item.Price; }
 function find() { var id = $('#prodId').val();$.getJSON(uri + '/' + id) .done(function (data)
 { $('#product').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); } </script>
 </body>
 </html>

There are several ways to get jQuery. In this example, I used the Microsoft Ajax CDN. We can also download it from http://jquery.com/, and the ASP.NET "Web API" project template includes jQuery as well.
Getting a List of Products
To get a list of products, send an HTTP GET request to "/api/products".

The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.$(document).ready(function () { // Send an AJAX request $.getJSON(apiUrl) .done(function (data) { // On success, 'data' contains a list of products. $.each(data, function (key, item) { // Add a list item for the product. $('<li>', { text: formatItem(item) }).appendTo($('#products')); }); }); });

Getting a Product By ID

To get a product by ID, send an HTTP GET request to "/api/products/id", where id is the product ID.function find() { var id = $('#prodId').val(); $.getJSON(apiUrl + '/' + id) .done(function (data) {$('#product').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); }

We still call getJSON to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.
Running the Application

Press F5 to start debugging the application. The web page should look like the following:

To get a product by ID, enter the ID and click Search:

If you enter an invalid ID, the server returns an HTTP error:

Using F12 to View the HTTP Request and Response

When we are working with an HTTP service, it can be very useful to see the HTTP request and request messages. We can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:
Locate the entry for the relative URI “api/products/”. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if we click the Request headers tab, we can see that the client requested "application/json" in the Accept header.

If we click the Response body tab, we can see how the product list was serialized to JSON. Other browsers have similar functionality. Another useful tool is Fiddler, a web debugging proxy. We can use Fiddler to view our HTTP traffic, and also to compose HTTP requests, which gives us full control over the HTTP headers in the request.

No comments: