asp.net overview - alvin lau

31
ASP.NET 4+ Overview Alvin Lau Solutions Consultant, Datacraft MVP (ASP.NET/IIS) since Jul 2005 SGDOTNET Council Member [email protected]

Upload: spiffy

Post on 07-Nov-2014

4.298 views

Category:

Documents


10 download

DESCRIPTION

 

TRANSCRIPT

Page 1: ASP.NET Overview - Alvin Lau

ASP.NET 4+ Overview

Alvin Lau

Solutions Consultant, Datacraft

MVP (ASP.NET/IIS) since Jul 2005

SGDOTNET Council Member

[email protected]

Page 2: ASP.NET Overview - Alvin Lau

ASP.NET 4+ Overview

• Advancements in ASP.NET 4.0

• ASP.NET MVC 3.0

• Questions and Answers

Agenda

Page 3: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Page 4: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

• Core Services

• Ajax

• Web forms

• Dynamic Data

• Web Application Deployment

Overview

Page 5: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Web.config file refactoring

Extensible Output Caching

Core Services

<?xml version="1.0"?>

<configuration>

<system.web>

<compilation targetFramework="4.0" />

</system.web>

</configuration>

<caching>

<outputCache defaultProvider="AspNetInternalProvider">

<providers>

<add name=“DiskCache”

type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/>

</providers>

</outputCache>

</caching>

<%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache"

%>

public override string GetOutputCacheProviderName(HttpContext context)

{

if (context.Request.Path.EndsWith("Advanced.aspx"))

return "DiskCache";

else

return base.GetOutputCacheProviderName(context);

}

Page 6: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Auto-start

Core Services

(applicationHost.config)

<applicationpools>

<add name="MyApplicationPool" startMode="AlwaysRunning" />

</applicationpools>

<sites>

<site name="MySite" id="1">

<application path="/"

serviceAutoStartEnabled="true"

serviceAutoStartProvider="PrewarmMyCache" >

<!-- Additional content -->

</application>

</site>

</sites>

<!-- Additional content -->

<serviceautostartproviders>

<add name="PrewarmMyCache"

type="MyNamespace.CustomInitialization, MyLibrary" />

</serviceautostartproviders>

public class CustomInitialization :

System.Web.Hosting.IProcessHostPreloadClient

{

public void Preload(string[] parameters)

{

// Perform initialization.

}

}

Page 7: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

RedirectPermanent helper (Issue HTTP 301 Moved Permanently

Response)

Shrinking Session State (Using System.IO.Compression.GZipStream

class)

Core Services

<sessionState

mode="SqlServer"

sqlConnectionString="data source=dbserver;Initial

Catalog=aspnetstate"

allowCustomSqlDatabase="true"

compressionEnabled="true"

/>

Page 8: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

• Performance Monitoring (new performance counters)

– % Managed Processor Time

– Managed Memory Use

Core Services

Aspnet.config

<?xml version="1.0" encoding="UTF-8" ?>

<configuration>

<runtime>

<appDomainResourceMonitoring enabled="true"/>

</runtime>

</configuration>

Page 9: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Open-source Jquery

– jQuery-1.4.1.js

– jQuery-1.4.1.min.js

– jQuery-1.4.1-vsdoc.js

CDN Support

Script Manager Explicit Scripts

Ajax

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-

1.4.2.js" type="text/javascript"></script>

<asp:ScriptManager ID="sm1" EnableCdn="true" runat="server"

/>

<asp:ScriptManager ID="sm1" AjaxFrameworkMode="Explicit"

runat="server">

<Scripts>

<asp:ScriptReference Name="MicrosoftAjaxCore.js" />

<asp:ScriptReference Name="MicrosoftAjaxComponentModel.js" />

<asp:ScriptReference Name="MicrosoftAjaxSerialization.js" />

<asp:ScriptReference Name="MicrosoftAjaxNetwork.js" />

</Scripts>

</asp:ScriptManager>

<%@ Page Language="C#" ... >

<head runat="server">

<title>Show jQuery</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtFirstName" runat="server" />

<br />

<asp:TextBox ID="txtLastName" runat="server" />

</div>

</form>

<script src="Scripts/jquery-1.4.1.js"

type="text/javascript"></script>

<script type="text/javascript">

$("input").focus( function() { $(this).css("background-color",

"yellow"); });

</script>

</body>

</html>

Page 10: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Set meta tags

View State for Individual Controls

ViewStateMode (Enabled, Disabled, Inherit)

Web Forms

<%@ Page Language="C#" AutoEventWireup="true"

CodeFile="Default.aspx.cs"

Inherits="_Default"

Keywords="These, are, my, keywords"

Description="This is a description" %>

<asp:PlaceHolder ID="PlaceHolder1" runat="server"

ViewStateMode="Disabled">

<asp:PlaceHolder ID="PlaceHolder2" runat="server"

ViewStateMode="Enabled">

<%@ Page Language="C#" AutoEventWireup="true"

CodeBehind="Default.aspx.cs"

Inherits="WebApplication1._Default"

ViewStateMode="Disabled" %>

Page 11: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Browser Capabilities Providers

Replacing ASP.NET Browser Capabilities

1. Create provider class from HttpCapabilitiesProvider and overrides

GetBrowserCapabilities method

2. Register provider with application

– browserCaps section in web.config or machine.config

– Write code in Application_Start (Global.asax)

Caching HttpBrowserCapabilities Object (same process)

Extending ASP.NET Browser Capabilities (same process)

Web Forms

public class CustomProvider : HttpCapabilitiesEvaluator

{

public override HttpBrowserCapabilities

GetBrowserCapabilities(HttpRequest request)

{

HttpBrowserCapabilities browserCaps =

base.GetHttpBrowserCapabilities(request);

if (browserCaps.Browser == "Unknown")

{

browserCaps = MyBrowserCapabilitiesEvaulator(request);

}

return browserCaps;

}

}

Page 12: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Easier to use routing

PageRouteHandler class

New properties - HttpRequest.RequestContext, Page.RouteData

New expression builders -

System.Web.Compilation.RouteUrlExpressionBuilder,

System.Web.Compilation.RouteValueExpressionBuilder

RouteUrl

RouteValue

RouteParameter class

Web Forms

public class Global : System.Web.HttpApplication

{

void Application_Start(object sender, EventArgs e)

{

RouteTable.Routes.MapPageRoute("SearchRoute",

"search/{searchterm}", "~/search.aspx");

RouteTable.Routes.MapPageRoute("UserRoute",

"users/{username}", "~/users.aspx");

}

}

RouteTable.Routes.Add("SearchRoute", new

Route("search/{searchterm}",

new PageRouteHandler("~/search.aspx")));

protected void Page_Load(object sender, EventArgs e)

{

string searchterm = Page.RouteData.Values["searchterm"] as

string;

label1.Text = searchterm;

}

http://localhost/search/scott

<asp:HyperLink ID="HyperLink1" runat="server"

NavigateUrl="<%$RouteUrl:SearchTerm=scott%>">Search for

Scott</asp:HyperLink>

http://localhost/search/scott

<asp:sqldatasource id="SqlDataSource1" runat="server"

connectionstring="<%$ ConnectionStrings:MyNorthwind %>"

selectcommand="SELECT CompanyName,ShipperID FROM Shippers

where

CompanyName=@companyname"

<selectparameters>

<asp:routeparameter name="companyname" RouteKey="searchterm"

/>

</selectparameters>

</asp:sqldatasource>

Page 13: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

• Setting Client IDs (ClientIDMode property)

– AutoID (legacy)

– Static

– Predictable

– Inherit

Web Forms

<%@ Page Language="C#" AutoEventWireup="true"

CodeFile="Default.aspx.cs"

Inherits="_Default"

ClientIDMode="Predictable" %>

<system.web>

<pages clientIDMode="Predictable"></pages>

</system.web>

<tc:NamingPanel runat="server" ID="ParentPanel"

ClientIDMode="Static">

<tc:NamingPanel runat="server" ID="NamingPanel1"

ClientIDMode="Predictable">

<asp:TextBox ID="TextBox1" runat="server"

Text="Hello!"></asp:TextBox>

</tc:NamingPanel>

</tc:NamingPanel>

<div id="ParentPanel">

<div id="ParentPanel_NamingPanel1">

<input

name="ctl00$ContentPlaceHolder1$ParentPanel$NamingPanel1$TextBox

1"

type="text" value="Hello!"

id="ParentPanel_NamingPanel1_TextBox1" />

</div>

Page 14: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

ASP.NET Chart Controls

Web Forms

Page 15: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

• QueryExtender Control

Web Forms

<asp:LinqDataSource ID="dataSource" runat="server">

TableName="Products">

</asp:LinqDataSource>

<asp:QueryExtender TargetControlID="dataSource" runat="server">

<asp:SearchExpression DataFields="ProductName,

Supplier.CompanyName"

SearchType="StartsWith">

<asp:ControlParameter ControlID="TextBoxSearch" />

</asp:SearchExpression>

</asp:QueryExtender>

<asp:LinqDataSource ID="dataSource" runat="server">

TableName="Products">

</asp:LinqDataSource>

<asp:QueryExtender TargetControlID="dataSource" runat="server">

<asp:RangeExpression DataField="UnitPrice" MinType="Inclusive"

MaxType="Inclusive">

<asp:ControlParameter ControlID="TextBoxFrom" />

<asp:ControlParameter ControlID="TexBoxTo" />

</asp:RangeExpression>

</asp:QueryExtender>

<asp:LinqDataSource ID="dataSource" runat="server"

TableName="Products">

</asp:LinqDataSource>

<asp:QueryExtender TargetControlID="dataSource" runat="server">

<asp:PropertyExpression>

<asp:ControlParameter ControlID="CheckBoxDiscontinued"

Name="Discontinued" />

</asp:PropertyExpression>

</asp:QueryExtender>

<asp:LinqDataSource ID="dataSource" runat="server"

TableName="Products">

</asp:LinqDataSource>

<asp:QueryExtender TargetControlID="dataSource" runat="server">

<asp:CustomExpression OnQuerying="FilterProducts" />

</asp:QueryExtender>

protected void FilterProducts(object sender,

CustomExpressionEventArgs e)

{

e.Query = from p in e.Query.Cast()

where p.UnitPrice >= 10

select p;

}

Page 16: ASP.NET Overview - Alvin Lau

Advancements in ASP.NET 4.0

Enable on any ASP.NET application

Dynamic Data

<asp:GridView ID="GridView1" runat="server"

AutoGenerateColumns="True"

DataKeyNames="ProductID" DataSourceID="LinqDataSource1">

</asp:GridView>

<asp:LinqDataSource ID="LinqDataSource1" runat="server"

ContextTypeName="DataClassesDataContext" EnableDelete="True"

EnableInsert="True"

EnableUpdate="True" TableName="Products">

</asp:LinqDataSource>

GridView1.EnableDynamicData (typeof(Product));

DetailsView1.EnableDynamicData(typeof(Product), new {

ProductName = "DefaultName" });

Page 17: ASP.NET Overview - Alvin Lau

Enhancements with ASP.NET 4.0

Web Packaging

Web.config transformation

Database deployment

One-click publish for web applications

Web App Deployment

Web.config

Debug

Release

Staging

Testing

Page 18: ASP.NET Overview - Alvin Lau

Advancements in ASP.Net 4.0

Core Services

Extensible Request Validation

Range of allowable URLs

Object caching

Extensible HTML, URL, HTTP Header Encoding

Multi-targeting

Ajax

jQuery

CDN

ScriptManager

Web Forms

Persisting Row Selection

CSS Improvements

Rendering Improvements

Dynamic Data

Declarative syntax

Entity templates

New Field templates

Creating links

Support M:M (EF)

Web App Deployment

Web Packaging

Web.config transformations

DB deployment

One-Click Publish

Many more…

Page 19: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

Page 20: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

Razor View Engine

Controller improvements

Model validation improvements

Nuget integration

Partial page output caching

Scaffolding improvements

Overview

Page 21: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

New view engine (Razor syntax)

Includes IntelliSense and color colorisation for Razor syntax

Can be unit tested

Includes HTML helpers

Chart, WebGrid, Crypto, WebImage, WebMail

Razor View Engine

Page 22: ASP.NET Overview - Alvin Lau

Demo – Razor View Engine

Page 23: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

Global Action Filters

Controller Improvements

public static void RegisterGlobalFilters(GlobalFilterCollection

filters)

{

filters.Add(new HandleErrorAttribute());

filters.Add(new HandleLoggingAttribute());

}

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);

RegisterRoutes(RouteTable.Routes);

}

Page 24: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

“ViewBag” property

“ActionResult” types

HttpNotFoundResult class – HTTP 404

HttpRedirectResult class has boolean “Permanent” property – HTTP 302 or

HTTP 301

Controller Improvements

public ActionResult Index()

{

ViewBag.Message = "Welcome to ASP.NET MVC!";

return View();

}

public ActionResult Test(int id)

{

return HttpNotFound();

}

Page 25: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

JavaScript and Ajax improvements

Client-side validation enabled by default

Remote validator

Controller Improvements

public class User

{

[Remote("UserNameAvailable", "Users")]

public string UserName { get; set; }

}

Page 26: ASP.NET Overview - Alvin Lau

Demo – Remote Validator

Page 27: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

JSON Binding support

Controller Improvements

jQuery("#ajaxGrid").jqGrid({

url: '@Url.Action("GridData")',

datatype: "json",

jsonReader: { repeatItems: false, id: "EventId" },

colNames: ['EventId', 'EventName', 'EventDate', 'StartTime', 'EndTime',

'AllDay'],

colModel: [

{ name: 'EventId', editable: true, sortable: false, hidden: true },

{ name: 'EventName', editable: true, sortable: false, hidden: false },

{ name: 'EventDate', editable: true, sortable: false, hidden: false },

{ name: 'StartTime', editable: true, sortable: false, hidden: false },

{ name: 'EndTime', editable: true, sortable: false, hidden: false },

{ name: 'AllDay', editable: true, sortable: false, hidden: false },

],

rowNum: 3,

pager: '#ajaxGridPager',

width: '850',

height: '10.5em'

}),

Page 28: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

“DataAnnotations” metadata attributes

“ValidationAttribute” Class

Validation Interfaces

IValidatableObject, IClientValidatable interfaces

Dependency Injection Improvements

Model Validation Improvements

public class User {

[Required]

public string Password { get; set; }

[Required, Compare("Password")]

public string ComparePassword { get; set; }

}

Page 29: ASP.NET Overview - Alvin Lau

ASP.NET MVC 3.0

NuGet Integration

Partial-Page Output Caching

Scaffolding Improvements

Other new features

[OutputCache(Duration = 3600, VaryByParam = "id")]

public ViewResult Details(int id)

{

return View(personRepository.GetById(id));

}

Page 30: ASP.NET Overview - Alvin Lau

Resources

Overview of ASP.NET 4 and VS 2010 Web Development http://www.asp.net/learn/whitepapers/aspnet4#0.2__Toc253429246

Unobstrusive JavaScript http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

ASP.NET MVC 3 http://www.asp.net/mvc/mvc3#overview http://msdn.microsoft.com/en-us/library/gg416514(v=VS.98).aspx

ASP.NET MVC 3.0 Service Location (Dependency Injection) http://bradwilson.typepad.com/blog/2010/07/service-location-pt1-introduction.html

Steven Sanderson’s Blog about MVC Scaffolding http://blog.stevensanderson.com/category/scaffolding/

Page 31: ASP.NET Overview - Alvin Lau

Alvin Lau Solutions Consultant, Datacraft MVP (ASP.NET/IIS) SGDOTNET Council Member [email protected]