+ All Categories
Home > Software > The Asp Net stack

The Asp Net stack

Date post: 16-Jul-2015
Category:
Upload: flavius-demian
View: 122 times
Download: 1 times
Share this document with a friend
87
THE ASP.NET STACK Session 6
Transcript

THE ASP.NET STACK

Session 6

A bit about me

Timisoara .Net Meetup organizer.

Web and mobile freelancer.

Xamarin enthusiast.

In love with software architecture.

@flaviusdemian

/pub/flavius-demian/32/191/178

/demian.flaviusradu

Agenda

JavaScript

jQuery

The Asp.Net stack

The MVC pattern

Asp.Net MVC

Agenda

What are Object relational mappers?

Entity Framework

Entity Framework – Database First

Entity Framework – Model First

Entity Framework – Code First

Asp.Net Web API

JavaScript

JavaScript is a dynamic computer programming

language developed by Netscape for dynamic content.

It is most commonly used as part of web

browsers, whose implementations allow:

client-side scripts to interact with the user

control the browser,

communicate asynchronously

alter the document content that is displayed

JavaScript Advantages

JavaScript allows interactivity such as:

implementing form validation

react to use actions, handle keys, hovers, clicks

changing an image when moving the mouse over it

sections of a page appearing and disappearing

content loading and changing dynamically

custom HTML controls, ex: scrollable table, fancy checkboxes

JavaScript

JavaScript data types are:

numbers (integer, float)

boolean (true, false)

string

var my_Name = “Ion Ionescu”;

arrays

var my_array = [1, 5.3, “aaaa”]

dictionaries (hash tables)

var my_hast = { a : 2, b : 3, c : “text” };

Everything is “derived” from Object.

JavaScript

You can declare objects and assign properties dynamically to them:

var obj = {};

obj.name = 'name';

Function declaration is pretty straight forward:

function myFunct(){

//my code

};

Main functions:

setTimeout, setInterval, JSON.stringify, JSON.parse, alert, confirm, console.log -> for debugging.

JavaScript

JavaScript can be:

1. Inline/Embedded

2. Internal

3. External

JavaScript

Inline/Embedded

<html>

<head>

<title>inline js</title>

</head>

<body>

<button onclick=“alert(‘clicked me!’);”>Click me</button>

</body>

</html>

JavaScript

Internal

<html>

<head>

<title>internal js</title>

</head>

<body>

<p>Hello world</p>

<script type=“text/javascript”>

alert(“Hello!”);

</script>

</body>

</html>

JavaScript

External

<html>

<head>

<title> external js</title>

</head>

<body>

<p>Hello world</p>

<script src="myscripts.js"></script>

</body>

</html>

JavaScript

JavaScript is executed during page loading or when the browser fires an event.

Function calls or code can be attached as “event handlers” via tag attributes.

<img src=“logo.gif” onclick=“alert(‘clicked’)” />

JavaScript

JavaScript can attach event handler for DOM events so that the developer can implements his custom logic.

Mouse events:

onclick, onmousedown, onmouseup, onmouseover, onmouseout,

onmousemove,

Key events – only for input fields:

onkeypress, onkeydown, onkeyup

Interface events:

onfocus, onscroll

JavaScript

Form events:

onchange – for select input fields, but not only

onsubmit

allow you to cancel a form submission

useful for form validation

Various events:

onload, onunload

allowed only for the <body> element

fires when all content on the page was loaded/unloaded

JavaScript

Demo time:

Document load demo

Alert demo

Button click demo

Confirm demo

setTimeout demo

setInterval demo

onKeyPress demo

onSubmit demo

JavaScript tips

Almost always place your JavaScript files at the end of the body.

Be attentive at the JavaScript code you write, it can get messy.

Many developers use the revealing module pattern to organize their code:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

Try to modularize, do not use a tone of global variables because it the code can get harder to understand.

jQuery

jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.

It is used by over 60% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use today.

jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events,

and develop Ajax applications.

jQuery – “Write Less. Do More”

jQuery

$( [find something]).doSomething();

//Using the DOM

document.getElementById(‘status’).style.display = ‘none’;

//Using jQuery

$(“#status”).hide();

CSS Selector jQuery Method

jQuery - Basic selectors

$(“#header”) – by id

$(“.myButton”) – by class

$(“table”) – by tag name

$(“table.user-list”) – this is a combination and selected all the tables that have the class user-list

A very important and probably the most used function is document.ready

$( document ).ready(function() {

console.log( "ready!" ); //it executes when the entire page is ready

});

jQuery - Attributes

DOM Manipulation:

before(), after(), append(), appendTo(), remove()

Attributes:

css(), addClass(), attr(), html(), val(), text(), html()

$(“#status”).append(“<span>Operation succeeded </span>”);

alert($(“#status”).html());

$(“#status”).addClass(“myCustomClass”);

jQuery - Events

click(), hover(), submit(), change(), keypress()

$(document).ready(function(){

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

$(“#result”).html(“”);

//removes the children of the element with the id result, if any

});

});

jQuery - Ajax

load(), get(), post(), getJSON(), serialize()

$.ajax({

type: "POST",

url: link,

data: JSON.stringify(dataToSend),

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function (msg) {

$("#result").show();

},

error: function (msg) {

alert(msg);

}

});

jQuery - Effects

animate(), show(), hide(), toogle(),

slideUp(), slideDown(), slideToogle(),

fadeIn(), fadeOut(), transform()

$("#result").fadeIn(3000, function () {

$("#result").fadeOut(3000, function () { });

});

$ (“#myId”).animate({

transform: 'translateX(50px)'

});

jQuery - Components

Accordion

$(function() {$( "#accordion" ).accordion();

});………………………

<div id="accordion"><h3>Section 1</h3>

<div><p> Hello world </p>

</div><h3>Section 2</h3>

<div><p> Hello World </p>

</div></div>

jQuery - Components

jQuery - Components

Tabs

$(function() {$( "#tabs" ).tabs();

});………………………

<div id="tabs"><ul><li>

<a href="#tabs-1">Tab 1</a></li><li>

<a href="#tabs-2">Tab 2</a></li></ul><div id="tabs-1"><p>Hello world.</p>

</div><div id="tabs-2"><p>Hello word.</p>

</div></div>

jQuery - Components

jQuery - Components

Let’s see some demos

The Asp.Net stack

We will cover MVC and Web API.

The MVC Pattern

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces.

It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to the user.

The central component of MVC, the model, captures the behavior of the application in terms of its problem domain, independent of the user interface.

The MVC Pattern

The model directly manages the data, logic and rules of the application.

A view can be any output representation of information, such as a chart or a diagram; multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.

The third part, the controller, accepts input and converts it to commands for the model or view.

The MVC Pattern

The MVC Pattern

The MVC Pattern

Some advantages of the MVC pattern would be:

separation of concerns

testability

scalability

extensibility

decoupling

Some disadvantages of the MVC pattern would be:

too complex for small applications

Asp.Net MVC

Asp.Net MVC is one of the most used, if not the most used, component of the Asp.Net stack.

A brief history:

2007 Scott Gu sketches out MVC on a flight to the east coast

Show it off at a Alt.Net and it is a hit

2010 – appears MVC 2

2011 – appears MVC 3

2012 – appears MVC 4

2013 – appears MVC 5

MVC embraces Convention over Configuration

Asp.Net MVC

Convention over Configuration ?

Controllers name ends with Controller : UserController.

Controllers live in the Controllers folder.

Views live in the Views folder.

Views are named according to the controller name.

A View for the product controller would live in Views/Product.

Each View name is mapped on an action of a controller:

Views/Product/Edit.cshtml

Convention over Configuration in Entity Framework – Code First

Why Asp.Net MVC?

A new option for Asp.Net.

Simpler way to program Asp.Net.

Easily testable and TDD friendly.

More control over your <html/>.

More control over your URLs.

Why Asp.Net MVC?

Not for everyone! (car vs. motorcycle).

Not a replacement for WebForms.

Supports existing ASP.Net features.

Powerful URL-mapping component .

It’s open source : https://github.com/aspnet/Mvc :)

Asp.Net MVC project overview

Asp.Net MVC - Model

The model should contain all of the application business logic, validation logic.

public class UserModel

{

public Guid Id { get; set; }

public String Name { get; set; }

public String Email { get; set; }

}

Asp.Net MVC - Controller

The Controller is a class which tells the view what to display.

It derives from the base System.Web.Mvc.Controller class.

Controller can directly control the HTML to display, but shouldn’t.

The controller is the glue between the model and the view.

The controller generates the response to the browser request.

Asp.Net MVC - Controller

A controller is composed of one or more actions (which are special functions) that look like this:

[HttpGet] the HTTP verb

public ActionResult User() the name of the action

{

ViewBag.Text = "This is a text from the ViewBag";

return View(“User”,MvcApplication.CurrentUser);

}

the model served to the view

the returned result type

the name of the view

Asp.Net MVC - Controller

Controller actions:

are public methods of the controller class

cannot be a static method

return an action result

Action results:

respond to a browser request passed from an action

inherit from the base ActionResult class

are of multiple types:

ViewResult, EmptyResult, JsonResult

ContentResult, FileContentResult, FilePathResult

Asp.Net MVC - Views

Controllers should not know about the display to the user.

Controllers pass data to a View

There are three ways to pass data to the view:

ViewBag : ViewBag.Message = “Hello World”

ViewData : ViewData[“Message”] = “Hello World”

TypeSafe object

A view uses the Razor Syntax which is cleaner than the WebFormsView syntax and has been adopted by WebForms also.

Razor vs WebForms syntax

WebForms Razor

<% foreach( var item in items) { %>

<span>

Item <%: item.Name %>

</span>

<% } %>

@foreach( var item in items){

<span>

Item: @item.Name

</span>

}

Asp.Net MVC – Layouts

Layouts allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site.

Layouts are an alternative to master pages.

The file _Layout.cshtml represent the layout of each page in the application. It is located in the Shared folder inside the Views folder.

Asp.Net MVC – Layouts

The _ViewStart file in the Shared folder (inside the Views folder) contains the following content:

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

This code is automatically added to all views displayed by the application.

If you remove this file, you must add this line to all views.

Asp.Net MVC – Layouts

Asp.Net MVC – Partial Views

Partial Views are special views which render a portion of View content.

It’s like a user control in Web Form application so it can be reusable on multiple views. We can simplify the high complexity markup by splitting in to one or more partial views.

Thus Partial views are increasing the maintenance of HTML markup in ASP.NET MVC application.

You can call a partial view using 2 methods:

@Html.Partial

@Html.RenderPartial

Asp.Net MVC – Partial Views

@Html.Partial returns a string, @Html.RenderPartial calls Write internally, and returns void.

You can store the output of @Html.Partial in a variable, or return it from a function.

You cannot do this with @Html.RenderPartial because the result will be written to the Response stream during execution.

So @Html.RenderPartial() has faster execution than @Html.Partial() due to RenderPartial giving quick response to the output.

Asp.Net MVC

Let’s create our first MVC project.

Asp.Net MVC – HTML helpers

HTML helpers offer Asp.Net MVC a great advantage because they can be used to generate standard HTML elements such as inputs, dropdown lists, links and other elements.

This kind of methods usually return a string which is written in the view.

Their usage is optional and because Asp.Net MVC is so extensible, you can write your own HTML helpers.

Asp.Net MVC – HTML helpers

Some examples of HTML helpers:

@Html.HiddenFor(model => model.Id)

@Html.LabelFor(model => model.FirstName)

@Html.PasswordFor(model => model.Password)

@Html.EditorFor(model => model.Email)

@Html.DropDownList("Country", new SelectList(countries, “Id", “Id")

@Html.Partial("_MyPartialView", myCustomModel)

Asp.Net MVC – HTML helpers

A bit more complex helper, but very useful is HTML.BeginForm.

@using (Html.BeginForm("Users","Home", FormMethod.Post, new { id = "userForm"}))

{

@Html.AntiForgeryToken()

@Html.ValidationSummary(true, "", new { @class = “myClass" })

@Html.HiddenFor(model => model.Id)

@Html.LabelFor(model => model.LastName)

@Html.EditorFor(model => model.LastName)

@Html.ValidationMessageFor(model => model.LastName)

}

Bundling and Minification

The BundleConfig.cs file represents the place where you can create bundles that hold javascript or css files.

Bundling is a feature that makes it easy to combine or bundle multiple files into a single file.

You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.

Minification performs a variety of different code optimizations to scripts or css files, such as removing unnecessary white space and comments and shortening variable names to one character.

Asp.Net MVC – BundleConfig

This is sample of BundleConfig.cs:

Asp.Net MVC – Ajax Helpers

AJAX stands for Asynchronous JavaScript and XML.

Ajax is cooked into MVC.

It starts with jQuery, but you don’t have to know jQuery to use it!

Unobtrusive JavaScript – separation of concerns.

The key to use Ajax in MVC is to use Ajax Helpers:

Ajax Action Links

Ajax Forms

Asp.Net MVC – Ajax Action Link

Ajax Action Link is an anchor tag ( <a> ) with asynchronous behavior.

The syntax is Ajax.ActionLink.

Parameters (overloaded)

Link text

Name of action

Options:

Error handling

How to send the request

What happens with the result

Confirmation dialog

More

Asp.Net MVC – Ajax Form

Ajax form is an asynchronous form.

The syntax is Ajax.BeginForm.

Parameters (overloaded)

Action

Controller

Options

Insertion mode

Type (Get/Post)

Error handling

Target element

Asp.Net MVC

Let’s see another demo

Asp.Net MVC - Validation

In order to implement validation you can annotate the models

with some validation attributes or datatype attributes and you have client-side and server-side validation out of the box.

You can check if the model is valid by using the ModelState.IsValidproperty.

Also, there are some validation helpers that can help you such as:

Html.ValidationMessage()

Html.ValidationSummary()

Asp.Net MVC - Validation

There are some out of the box validation attributes such as :

Required,

StringLength,

RegularExpression,

Range

There are some out of the box data types attributes such as :

Email address,

Currency,

Credit card,

Time,

Postal code

Asp.Net MVC - Validation

public class UserModel //here we can see a model which has validation

{

[Required]

public Guid Id { get; set; }

[Required(ErrorMessage = "Please insert some text here.")]

public String Name { get; set; }

[StringLength(50, ErrorMessage = "The field length must be between {2} and {1}", MinimumLength = 5)]

public String Email { get; set; }

}

Asp.Net MVC - Validation

Demo

Asp.Net MVC - Routes

The Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.

The default URL format is controller/action/parameters:

/User/Edit/5

Asp.Net Routing is setup in two places:

Web.config – we will not cover.

Global.asax.cs and RouteConfig.cs – Routes are provided on the RegisterRoutes method of RouterConfig.cs and registered on the Application_Start method of the Global.asax.cs file

Asp.Net MVC - Routes

RouteConfig.cs

Global.asax.cs

Asp.Net MVC – Error handling

We all know that there is not a perfect app out there.

When a internal error (server error) occurs you can catch it in the Application_Error hook of the application, which resides in the Global.asax.cs class.

Asp.Net MVC – Error handling

Demo

What are ORMs?

ORM comes from object relational mapper.

ORMs typically provide the following functionality:

Creating object model by database schema

Creating database schema by object model

Querying data by object-oriented API

Data manipulation, CRUD – create, read, update, delete

ORM frameworks automatically generate SQL to perform the requested data operations.

What are ORMs?

ORMs advantages:

developer productivity -> writing less code

abstraction -> the complexity is hidden within the ORM

manageability of the CRUD operations for complex relationships

easier maintainability

ORMs disadvantages:

because they add a layer between the database and the application they add a performance overhead

sometimes the generated queries are not the most performant ones

Entity Framework

Entity framework (EF) is a standard ORM framework, part of .NET which provides a run-time infrastructure for managing SQL-based database data as .NET objects.

The relational database schema is mapped to an object model ( classes and associations).

Visual Studio has built-in tools for generating EF SQL data mappings, which consist of c# classes and XML.

EF provides a standard data manipulation API for accessing data stored in databases.

Entity Framework

One of the most important components of EF is the DbContext class.

The DbContext:

holds the database connection and the entity classes.

provides LINQ-based data access

implements identity tracking, change tracking for the CRUD operations

Another important component is composed by the entities. Each database table is typically mapped to a single entity class ( C# class).

Entity Framework

Using Entity Framework helps you to save time and focus on your business domain model.

With Entity Framework you can choose from one of the following approaches:

Database First

Code First

Model First

How to decide? A sketch

Database first

You should use database first when you already have a database and you want to generate a model from it.

Of course, you generate the model using the designer, which is a visual representation of the data.

Database first

Model First

You should use model first when you have no model and no database, yet and you like working with the designer.

Model First

Code First

You should use code first when you don’t have a database.

First, you define your classes and then you let the code first approach figure out how your database should look like.

Of course, when you use code first you don’t interact with the designer at all.

Code First

Asp.Net - Web API

Web API

is defined as RESTf-ul services

uses a modern HTTP programming model

obeys the ASP.Net routes

has built-in content negotiation

supports model binding and validation

Asp.Net - Web API

REST – representational state transfer:

stateless

cacheable

embraces the http protocols:

it uses the HTTP verbs GET, PUT, POST, DELETE

it returns standard HTTP Response Codes

Asp.Net - Web API

Modern programming model :

Content is delivered through API Controller constructs

Action Methods are named after HTTP methods

Routing

Proper use of HTTP Response codes

Asp.Net - Web API

This is a snippet of how it looks

References

Documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

http://api.jquery.com/

http://www.microsoftvirtualacademy.com/training-courses/introduction-to-asp-net-mvc

http://www.asp.net/aspnet/samples/aspnet-web-api

http://en.wikipedia.org/wiki/Model-view-controller

http://www.asp.net/aspnet/samples/aspnet-mvc

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api

References

Presentations:

http://www.slideshare.net/donotfold/jquery-introduction-8514887

http://www.pluralsight.com/courses/one-aspdotnet-from-scratch

http://www.pluralsight.com/courses/entity-framework-6-ninja-edition-whats-new

http://www.slideshare.net/maartenba/introduction-to-aspnet-mvc-presentation

http://www.slideshare.net/divya071/asp-net-mvc-12896247

http://www.slideshare.net/ThangChung/aspnet-web-api-13891270

http://www.slideshare.net/TelerikAcademy/11-adonet-entity-framework-c-and-databases


Recommended