asp.net ajax 4.0

28
Change the Rules ASP.NET Ajax 4.0 Fritz Onion

Upload: sampetruda

Post on 29-Nov-2014

4.075 views

Category:

Documents


6 download

DESCRIPTION

 

TRANSCRIPT

Page 1: ASP.NET Ajax 4.0

Change the Rules

ASP.NET Ajax 4.0

Fritz Onion

Page 2: ASP.NET Ajax 4.0

Change the Rules

About Fritz Onion• Cofounder of Pluralsight

– Developer training company specializing in Microsoft technologies

– Pluralsight On-Demand! - subscription library

– Pluralsight twitter feed: http://twitter.com/pluralsight

• Community contributions

– Author of Essential ASP.NET books, MSDN articles

– Conference / user group speaker (PDC, TechEd, VSLive!, DevWeek, …)

– Microsoft MVP for ASP.NET

• Contact info

– Email: [email protected]

– Blog: http://pluralsight.com/fritz

– Twitter: http://twitter.com/fritzonion

Page 3: ASP.NET Ajax 4.0

Change the Rules

ASP.NET Ajax Library (released with ASP.NET 4)

• Focus on client-side features

– Client data sources

– Script library refactoring

– Client script manager

– Client template rendering

– Declarative control/behavior instantiation

– Live data binding

– Observer pattern

– AdoNetServiceProxy

– DataContext, AdoNetDataContext

– Inclusion of and support for jQuery library

Page 4: ASP.NET Ajax 4.0

Change the Rules

ASP.NET Ajax Library

• Available on CodePlex

– http://ajax.codeplex.com

• Documentation, samples, tutorials available

– http://www.asp.net/ajaxlibrary/

• All scripts now loadable through Microsoft Ajax CDN

– http://ajax.microsoft.com/ajax/beta/0911/start.js

• Toolkit controls now part of core library

– No more separate installation

– Most controls available as client-only in addition to 'extenders'

• ASP.NET Ajax Library being contributed to the CodePlex foundation

– http://codeplex.org

• Standard & premier support for ASP.NET Ajax Library after RTM

Page 5: ASP.NET Ajax 4.0

Change the Rules

Client Script Loader

• Loads all scripts required by a component and executes them in the right

order

• Supports script combining

• Supports on-demand loading

• Just point to start.js and use Sys.require

– Sys.components namespace

for object dependencies

– Sys.scripts namespace for

pre-defined script collections

<script src="Scripts/start.debug.js"></script>

<script>Sys.require([Sys.components.dataView]);

Sys.onReady(function () {// use dataView here

}…

Page 6: ASP.NET Ajax 4.0

Change the Rules

Client Script Loader AliasesSys.scripts Value Script Description

AdoNet MicrosoftAjaxAdoNet.js Allows client-side code to interact with ADO.NET Data Services.

ApplicationServices MicrosoftAjaxApplicationServices.js Provides access to ASP.NET profile, authentication and role services.

ComponentModel MicrosoftAjaxComponentModel.js Provides behavior and component functionality.

Core MicrosoftAjaxCore.js Base script that contains core ASP.NET Ajax Library functionality and JavaScript language enhancements.

DataContext MicrosoftAjaxDataContext.js Contains the DataContext and AdoNetDataContext client-side classes.

Globalization MicrosoftAjaxGlobalization.js Contains language globalization functionality for dates, times and numbers.

History MicrosoftAjaxHistory.js Provides browser history functionality for Ajax applications.

jQuery jquery-1.3.2.min.js Minified jQuery library script.

jQueryValidate jquery.validate.min.js Minified jQuery Validate script used to validate form elements.

Network MicrosoftAjaxNetwork.js Contains core networking features used to communicate with remote sites and services.

Serialization MicrosoftAjaxSerialization.js Provides object serialization and deserialization functionality.

Templates MicrosoftAjaxTemplates.js Provides client-side template rendering functionality.

WebServices MicrosoftAjaxWebServices.js Contains a web service proxy class used to call web services.

Page 7: ASP.NET Ajax 4.0

Change the Rules

ScriptManager

• ScriptManager enhanced to use script loader

– <asp:ScriptManager… EnableCdn="true" />

• Effects controls that bring in script too (like menu)

– AjaxFrameworkMode – does not bring in all scripts

Page 8: ASP.NET Ajax 4.0

Change the Rules

Content Delivery Network (CDN)

• Microsoft hosts ajax/jQuery scripts on CDN

– Cached on 'edge' servers strategically placed around

the world

– Enables cross application caching

– Full list of files: http://www.asp.net/ajax/cdn

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"type="text/javascript"></script>

Page 9: ASP.NET Ajax 4.0

Change the Rules

Toolkit Controls• Toolkit controls now rolled into core release

– No separate install

• http://ajax.microsoft.com/ajax/beta/0911/extended/ExtendedControls.js

– In addition to server extenders, now available as pure client controls

<head><link href="scripts/extended/calendar/calendar.css" rel="stylesheet" type="text/css" /><script src="scripts/start.debug.js"></script> <script src="scripts/extended/ExtendedControls.js"></script> <script type="text/javascript"> Sys.require([Sys.components.calendar]);

Sys.onReady(function () {Sys.create.calendar("#dateInput");

}); </script></head><body>

Enter a date: <input type="text" id="dateInput" /></body>

Page 10: ASP.NET Ajax 4.0

Change the Rules

jQuery Integration

• All ASP.NET Ajax Library controls are

exposed as jQuery plug-ins

– Can use jQuery selector syntax to apply

$("#nameInput").watermark("Enter your name…");

Page 11: ASP.NET Ajax 4.0

Change the Rules

Client Templates• Client templates replicate HTML

– XHTML compliant

– Placeholder notation similar to Silverlight

• {{ Name }}

– Expression language is JavaScript

• {{BirthDate.localeFormat("dd/MM/yyyy")}}

– Interspersed code and markup

– Declarative behavior and events<table id="resultTable" class="sys-template"><tr> <td>{{CourseCode}}</td> <td>{{CourseCode + ":" + Course}}</td></tr>

</table>

Page 12: ASP.NET Ajax 4.0

Change the Rules

Sys.UI.DataView

• The DataView class applies data to an

HTML template<script src="http://ajax.microsoft.com/ajax/beta/0911/start.debug.js"></script><script>

Sys.require([Sys.components.dataView]);var courses = [

{ CourseCode: "AP17", Course: "ASP.NET Ajax Fundamentals" }, … ];

// The onReady callback will be called when the DOMReady event has fired, // and when any dynamically loaded scripts have loaded - as a result of // Sys.require(...).Sys.onReady(function () {

Sys.create.dataView("#resultTable", { data: courses }); );

</script>

Page 13: ASP.NET Ajax 4.0

Change the Rules

Sys.UI.DataView propertiespublic class Sys.UI.DataView : Sys.UI.Control,

Sys.UI.ITemplateContextConsumer{ //…public object data { get; set; }public object dataProvider { get; set; }public bool autoFetch { get; set; }public bool isFetching { get; }public string httpVerb { get; set; }public object items { get; }public object fetchParameters { get; set; }public object selectedData { get; }public int selectedIndex { get; set; }public int initialSelectedIndex { get; set; }public object selectedItemClass { get; set; }public int timeout { get; set; }public string fetchOperation { get; set; }public object itemPlaceholder { get; set; }public object templateContext { get; set; }public object itemTemplate { get; set; }}

Page 14: ASP.NET Ajax 4.0

Change the Rules

Sys.UI.DataView methods

public class Sys.UI.DataView : Sys.UI.Control, Sys.UI.ITemplateContextConsumer

{ //…public void abortFetch();public object getItem(source);public void refresh();public object fetchData(succeededCallback, failedCallback,

mergeOption, userContext);public void updated();}

Page 15: ASP.NET Ajax 4.0

Change the Rules

Attribute Binding

• Use sys:attr to bind attributes to data

fields in a template

– Defers interpretation of attributes until bound

to data<table id="resultTable" border="1" class="sys-template">

<tr><td><img sys:src="{{ImageUrl}}" /></td><td>{{CourseCode}}</td><td>{{Course}}</td>

</tr></table>

Page 16: ASP.NET Ajax 4.0

Change the Rules

Explicit binding• In addition to templates, it is possible to bind data explicitly to

elements

– Use Sys.bind in response to the itemRendered event

– Keeps markup clean

<script src="http://ajax.microsoft.com/ajax/beta/0911/start.debug.js"></script><script>Sys.require([Sys.components.dataView]);var courses = [

{ CourseCode: "AP17", Course: "ASP.NET Ajax Fundamentals" }, … ];

Sys.onReady(function () {Sys.create.dataView("#resultTable", { data: courses,

itemRendered: resultTableRendered });});

function resultTableRendered(dataView, ctx) {Sys.bind(Sys.get("#c1", ctx), "innerHTML", ctx.dataItem, "CourseCode");Sys.bind(Sys.get("#c2", ctx), "innerHTML", ctx.dataItem, "Course");

}</script>

<table id="resultTable" border="1" class="sys-template"><tr><td id="c1"></td><td id="c2"></td>

</tr></table>

Page 17: ASP.NET Ajax 4.0

Change the Rules

Customizing Templates• Expression language is JavaScript

• {{BirthDate.localeFormat("dd/MM/yyyy")}}

• Can leverage pseudo columns and interspersed code

and markup

$index Ordinal index or the row (0-based).

$dataItem Current item being bound.

Page 18: ASP.NET Ajax 4.0

Change the Rules

Template Pseudo-Columns<script>

function formatDataItem(item) {return String.format("({0}) Name: {1}", item.Id, item.Name);

}</script>…<table id="resultTable" border="1" class="sys-template"

sys:attach="dataview" dataview:dataprovider="SampleDataService.svc"dataview:fetchoperation="GetData"dataview:autofetch="true">

<tr><td>{{$index}}</td><td>{{formatDataItem($dataItem)}}</td>

</tr></table>

Page 19: ASP.NET Ajax 4.0

Change the Rules

Declarative Instantiation

• Support for client object creation without script

code

• Works for any Sys.UI.Control-derived client class

<body xmlns:sys="javascript:Sys"xmlns:dataview="javascript:Sys.UI.DataView">

…<table id="resultTable" class="sys-template"

sys:attach="dataview"dataview:data="{{courses}}">

Page 20: ASP.NET Ajax 4.0

Change the Rules

Web Service Invocation• DataView supports dataProvider and fetchOperation

properties to invoke WCF svcs– Service must support JSON

serialization and Ajax proxy

generation

function pageLoad(){

$create(Sys.UI.DataView, {dataProvider: "SampleDataService.svc",fetchOperation: "GetData",autoFetch: "true"

}, {}, {}, $get("resultTable"));}

// SampleDataService.svc WCF servicepublic class SampleDataService{

[OperationContract]public List<SampleData> GetData(){ … }

}

Page 21: ASP.NET Ajax 4.0

Change the Rules

Live Bindings

• Reflect changes live from data• <span>{binding Name}</span>

• <input sys:value="{binding Name}" />

• Reflect changes live back to data from user input

– No round-trip to server

• Convert and ConvertBack functions

Page 22: ASP.NET Ajax 4.0

Change the Rules

Live Binding Example<script>var titleValue = { Title: "sample title"};</script>

<body xmlns:sys="javascript:Sys"xmlns:code="http://schemas.microsoft.com/aspnet/code"xmlns:dataview="javascript:Sys.UI.DataView">

<div sys:attach="dataview" class="sys-template" dataview:data="{{ titleValue }}">

<h3>{ binding Title }</h3><hr />Set the title here:<input type="text" sys:value="{binding Title}" />

</div>

</body>

Page 23: ASP.NET Ajax 4.0

Change the Rules

LiveBinding with Conversion Functions

• Can specify convert and convertBack functions in live bindings

<script>var titleValue = { Title: "sample title", Amount: 42 };function toDollars(amt) { return '$' + amt; }function fromDollars(str) { return str.substring(1); }</script> …<div sys:attach="dataview" class="sys-template"

dataview:data="{{ titleValue }}"><h4>{ binding Amount, convert=toDollars}</h4><br />Set amount here:<input type="text"

sys:value="{binding Amount, convert=toDollars, convertBack=fromDollars}"

/></div>

Page 24: ASP.NET Ajax 4.0

Change the Rules

Observer Pattern• Sys.Observer adds observer functionality to ordinary

JavaScript objects causing notifications on change

– Used for live binding

<script>var itemsArray = [];function pageLoad() {

Sys.Observer.makeObservable(itemsArray);}function onEnterNewItem() {

var newItem = { Id: $get("_itemId").value, Name: $get("_itemName").value };

itemsArray.add(newItem);}</script>

Page 25: ASP.NET Ajax 4.0

Change the Rules

Observer Pattern Example

• DataView bound to observable array

– Binding updated whenever array updates

<ol id="orderedListView" class="sys-template"sys:attach="dataview"dataview:data="{{ itemsArray }}">

<li>{{Name + '-' + Id}}</li></ol><hr />Enter new item:<br />Id: <input type="text" id="_itemId" /><br />Name: <input type="text" id="_itemName" /><br /><input type="button" value="enter" onclick="onEnterNewItem()" />

Page 26: ASP.NET Ajax 4.0

Change the Rules

Sys.Data.DataContext• Sys.Data.DataContext provides a client-side data context

– Tracks changes

made to data

– Changes can

be propagated

to server with

SaveChanges

<script>var ctx = new Sys.Data.DataContext();ctx.set_serviceUri("sampleDataService.svc");ctx.set_saveOperation("SaveData");ctx.initialize();

</script>…<ol id="orderedListView" class="sys-template"

sys:attach="dataview"dataview:dataprovider="{{ctx}}"dataview:query="GetData">

<li><input type="text" value="{binding Id}" /><br /><input type="text" value="{binding Name}" />

</li></ol> <input type="button" onclick="ctx.saveChanges()" value="Save changes" />

Page 27: ASP.NET Ajax 4.0

Change the Rules

AdoNetServiceProxy• AdoNetServiceProxy class enables read-write interaction with ADO.NET Data

Servicespublic class Sys.Data.AdoNetServiceProxy : Sys.Net.WebServiceProxy,

Sys.Data.IDataProvider { //…public string path { get; set; }public bool replaceOnUpdate { get; set; }public string serviceUri { get; }public object createActionSequence();public object invoke(…);public object insert(…);public object fetchData(…);public object fetchDeferredProperty(…);public object query(…);public object update(…);public object remove(…);}

Page 28: ASP.NET Ajax 4.0

Change the Rules

Sys.Data.AdoNetDataContextSys.Data.AdoNetDataContext provides a context for an ADO.NET data

service

– Derives from DataContext, maps to ADO.NET data service methods

<div id="peopleView" sys:attach="dataview" class="sys-template"dataview:dataprovider= "{{ $create(Sys.Data.AdoNetDataContext,

{serviceUri: 'MovieReviewsService.svc'})}}"dataview:fetchoperation="movies"dataview:autofetch="true">

<fieldset><legend>

<span>{{movie_id}}</span></legend><em>{{title}}</em> - {{release_date}}

</fieldset></div>