ajax asynchronous javascript and xml:

45
AJAX Asynchronous JavaScript and XML: JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as .Net, etc. Partial refresh: It lets you update part of a web page without having to reload the entire page. RIA: Rich Internet Application Quick response time, interactive page

Upload: sampetruda

Post on 20-Jun-2015

1.973 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: AJAX Asynchronous JavaScript and XML:

AJAX

• Asynchronous JavaScript and XML:– JavaScript, Document Object Model, Cascade Style

Sheet, XML, server-side script such as .Net, etc.

• Partial refresh: It lets you update part of a web page without having to reload the entire page.

• RIA: Rich Internet Application– Quick response time, interactive page

Page 2: AJAX Asynchronous JavaScript and XML:
Page 3: AJAX Asynchronous JavaScript and XML:

How AJAX Updates a Page

• When an event happens, JavaScript (AJAX engine) prepares a request and sends it to the web sever.

• The server receives the request and processes it.• The server prepares a response and sends it back to

the browser.• The JavaScript parses the response to update the

page.

Page 4: AJAX Asynchronous JavaScript and XML:

ASP.Net AJAX Server Controls

• ScriptManager: Enables the use of other AJAX controls.

• UpdatePanel: A control that encloses standard ASP.net controls to be updated asynchronously (asynchronous postback)

• Timer control: Trigger partial refresh at a set time interval.

Page 5: AJAX Asynchronous JavaScript and XML:

Creating Page with AJAX

• 1. Add a ScriptManager control

• 2. Add UpdatePanel control

• 3. Add ASP.Net controls to the UpdatePanel

Page 6: AJAX Asynchronous JavaScript and XML:

Postback or Asynchronous PostBack

• Page.IsPostBack

• ScriptManager1.IsInAsyncPostBack

Page 7: AJAX Asynchronous JavaScript and XML:

Example 1: Two Counters

Page 8: AJAX Asynchronous JavaScript and XML:

Dim PostbackCounter, AsyncCounter As Integer Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Session("PCounter") = PostbackCounter Session("Acounter") = AsyncCounter Else PostbackCounter = Session("PCounter") End If If ScriptManager1.IsInAsyncPostBack Then AsyncCounter = Session("Acounter") End If End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click PostbackCounter += 1 TextBox1.Text = PostbackCounter.ToString Session("PCounter") = PostbackCounter End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click AsyncCounter += 1 TextBox2.Text = AsyncCounter.ToString Session("Acounter") = AsyncCounter End Sub

Page 9: AJAX Asynchronous JavaScript and XML:

Example 2: Retrieve Customer Name

Page 10: AJAX Asynchronous JavaScript and XML:

Page.IsPostBack and ScriptManager1.IsInAsyncPostBack

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then

TextBox3.Text = "First time" Else TextBox3.Text = "PostBack" End If If ScriptManager1.IsInAsyncPostBack Then TextBox2.Text = " IsAsyncPostBack" Else TextBox2.Text = " Not AsyncPostBack" End If End Sub

Page 11: AJAX Asynchronous JavaScript and XML:

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid='" & TextBox1.Text & "';" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() objDataReader.Read() TextBox2.Text = objDataReader("cname") objDataReader.Close() End Sub

Page 12: AJAX Asynchronous JavaScript and XML:

Cookies

Page 13: AJAX Asynchronous JavaScript and XML:

Data in Cookies

• Which web site set the cookie• Expiration date

– DateTime data type– TimeSpan data type

• One or more pieces of data• Keys: A collection of cookie’s names• Define a new cookie:

– Dim CookieCID as new HttpCookie(“cid”)

• Add to: Response.Cookies– Response.cookies.add(cookieCID)

Page 14: AJAX Asynchronous JavaScript and XML:

Cookie’s Properties

• System.Web/HttpCookie– Name– Value– Expires

• To write a cookie:– Response.Cookies.Add(cookieObj)

Page 15: AJAX Asynchronous JavaScript and XML:

Creating Cookiesdim cookieCID as New HttpCookie("cid")

dim cookieCNAME as new HttpCookie("cname")

dim dt as dateTime=dateTime.now()

dim ts as new TimeSpan(30,0,0,0)

cookieCID.value=textbox1.text

cookieCname.value=textbox2.text

cookieCID.expires=dt.add(ts)

cookieCname.expires=dt.add(ts)

response.cookies.add(cookieCID)

response.cookies.add(cookieCNAME)

Note: The name(or key)of cookieCID is “cid”

FireFox: Tools/Options/Privacy

Page 16: AJAX Asynchronous JavaScript and XML:

Reading CookiesDim custid as string

Dim custName as string

custid=request.cookies("cid").value

custname=request.cookies("cname").value

Page 17: AJAX Asynchronous JavaScript and XML:

Using Cookie with DataReader

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String Dim objDataReader As OleDbDataReader Dim cid As String cid = Request.Cookies("CID").Value strSQL = "select * from webcustomer where CustID= '" & cid & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() objDataReader = objComm.ExecuteReader() If objDataReader.Read() = True Then Session("cname") = objDataReader("CustName") Response.Write("<hr>Welcome:" & objDataReader("CustName") & "<hr>") Else Response.Write("<hr>We don't have your record <hr>") End If objConn.Close()

Demo:ASPNET/CookieGreeting.aspx

Page 18: AJAX Asynchronous JavaScript and XML:

Sending Email From an ASP.Net Page

Page 19: AJAX Asynchronous JavaScript and XML:

• Send a confirmation message.

• Send a document to a user as attachment.

• Forgot password?

Page 20: AJAX Asynchronous JavaScript and XML:

Simple Mail Transport Protocol (SMTP)

• Email messages are text files.• InetPub\MailRoot

– PickUp directory: • SMTP monitors this directory and sends any messages found

in this directory.

– Drop:• Incoming messages received by SMTP are written to this

directory.

– BadMail:• If an email cannot be delivered or returned to the sender it is

moved to this directory.

Page 21: AJAX Asynchronous JavaScript and XML:

ASP.Net Email Classes

• SmtpClient class– System.Net.Mail

• Define a SmtpClient object– Dim mailClient As New SmtpClient("dchao100L")

• Method:– MailClient.Send(From, To, Subject, messageText)

• MailClient.Send(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text)

– MailClient.Send(System.Net.Mail.MailMessage)

• Demo:– Import system.net.mail

Page 22: AJAX Asynchronous JavaScript and XML:

Using MailMessage Class to Set Email Properties

• Email properties:– Attachments– Bcc– Body– BodyFormat

• Text or Html

– Cc– From– Headers– Subject– To

Page 23: AJAX Asynchronous JavaScript and XML:

MailMessage Class Example with AttachmentDim mailClient As New SmtpClient("dchao100L")Dim mailMsg As New MailMessage Dim FromAddr As New MailAddress(TextBox1.Text) Dim ToAddr As New MailAddress(TextBox2.Text) mailMsg.From = FromAddr mailMsg.To.Add(ToAddr) mailMsg.Subject = TextBox3.Text mailMsg.Body = TextBox4.Text Dim attach As New Attachment("c:\welcome.htm") mailMsg.Attachments.Add(attach) mailClient.Send(mailMsg)

Page 24: AJAX Asynchronous JavaScript and XML:

Demo: ForgotPasswordDim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL, emailAddress As String emailAddress = TextBox1.Text strSQL = "select * from users where email= '" & emailAddress & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If Not objDataReader.Read() Then Response.Write("We don't have your record" & "</br>") Else Dim mailClient As New SmtpClient("dchao100L") Dim objMsg As New MailMessage() Dim FromAddr As New MailAddress("webmaster@dchao100L") objMsg.From = FromAddr Dim ToAddr As New MailAddress(emailAddress) objMsg.To.Add(ToAddr) objMsg.Subject = "Your password" objMsg.Body = "Your password is: " & objDataReader("password") mailClient.Send(objMsg) Response.Write("<hr>Your password is sent to your email account<hr>") End If

Page 25: AJAX Asynchronous JavaScript and XML:

Sending email to a new customer Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String strSQL = "insert into webCustomer values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "')" Dim objComm As New OleDbCommand(strSQL, objConn) objComm.ExecuteNonQuery() Dim mailClient As New SmtpClient("dchao100L")MailClient.Send(“webmaster@dchao100L”, textBox5.text, “welcome new customer”,”welcome to join us!”)

Page 26: AJAX Asynchronous JavaScript and XML:

UpLoading Files

Page 27: AJAX Asynchronous JavaScript and XML:

FileUpload Control

• Properties:– PostedFile:

• This is a System.Web.HttpPostedFile class

• FileName: This name contains the path of the posted file.’

– Contentlength

– ContentType

• Method:– SaveAs – this method save the posted file on server.

Page 28: AJAX Asynchronous JavaScript and XML:

Save Uploaded FilePrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As Dim FileName As StringDim strFilePath As String = "c:\inetpub\wwwroot\images\"FileName = FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf("\") + 1) strFilePath = strFilePath & FileName FileUpload1.SaveAs(strFilePath) 'FileUpload1.PostedFile.SaveAs(strFilePath) Response.Write("File: " & FileName & " is saved on server") End Sub

Page 29: AJAX Asynchronous JavaScript and XML:

Insurance Claim Example

• Uploading claim pictures for insurance cases.• Each case may have many pictures.• Database:

– CaseTable: CaseID, CaseDate, Agent– CasePics: CaseID, PicPathName

• Each picture is named: CaseID + PictureName and saved in folder: Images

• Create a web page with a dropdown list of CaseID, a File Field control to choose file, and a upload button. The uploaded picture will be saved in the Images folder and a record will be entered in CasePics file.

• Demo: Insurance/UploadPic.aspx

Page 30: AJAX Asynchronous JavaScript and XML:

Code Example Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\InsurancePic.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from CaseTable;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("caseID")) Loop objConn.Close() End If End Sub

Page 31: AJAX Asynchronous JavaScript and XML:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim CaseID As String Dim FileName As String Dim strFilePath As String = "c:\inetpub\wwwroot\images\" FileName = FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf("\") + 1) CaseID = ListBox1.SelectedItem.Text FileName = CaseID & FileName strFilePath = strFilePath & FileName FileUpload1.PostedFile.SaveAs(strFilePath) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\InsurancePic.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "Insert Into CasePics Values ('" & CaseID & "','" & strFilePath & "')" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() objComm.ExecuteNonQuery() End Sub

Page 32: AJAX Asynchronous JavaScript and XML:

Picture File

• Access:– OLE field– Picture file name:

• Relative reference• Absolute reference

• Creating links to picture files• Insert pictures in web page

– IMG tag

Page 33: AJAX Asynchronous JavaScript and XML:

Creating Links to Pictures(aspnetprodlistpic.aspx)

sub Page_Load()

dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb"

dim objConn as new OledbConnection(strConn)

dim strSQL as string = "select PicID, PicDescription, PicPath from PictureTable;"

dim objComm as new OledbCommand(strSQL,objConn)

objConn.open()

dim objDataReader as oledbDataReader

objDataReader=objComm.executeReader()

do while objDataReader.Read=True

response.write ("<p><a href='http://localhost/images/" & objDataReader("PicPath") & "'>" & objDataReader("PicDescription") & "</a></p><br>")

loop

objConn.close()

end sub

Page 34: AJAX Asynchronous JavaScript and XML:

Insert Pictures with IMG Tagssub Page_Load()

response.write("<p align='center'><font size='5'><b>Available Pictures</b></font></p>")

dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb"

dim objConn as new OledbConnection(strConn)

dim strSQL as string = "select PicID, PicDescription, PicPath from PictureTable;"

dim objComm as new OledbCommand(strSQL,objConn)

objConn.open()

dim objDataReader as oledbDataReader

objDataReader=objComm.executeReader()

do while objDataReader.Read=True

response.write ("<p><img border='0' src='http://localhost/images/" & objDataReader("PicPath") & "' width='198' height='151'></p>")

loop

objConn.close()

end sub

Note: src=‘../images/

Page 35: AJAX Asynchronous JavaScript and XML:

Repeater Control

• Replace the Do Loop• To use a Repeater control:

– 1. Add the Repeater to the web page– 2. Add a data source to the Repeater– 3. Switch to Source view to add the HTML tag

of the control you want to repeat by adding a ItemTemplate.

– 4. Use the DataBinder to bind the control to the data source.

Page 36: AJAX Asynchronous JavaScript and XML:

Repeater Templates

• ItemTemplate - Use this template for elements that are rendered once per row of data.

• AlternatingItemTemplate - Use this template for elements that are rendered every other row of data. This allows you to alternate background colors, for example.

• HeaderTemplate - Use this template for elements that you want to render once before your ItemTemplate section.

• FooterTemplate - Use this template for elements that you want to render once after your ItemTemplate section.

• SeperatorTemplate - Use this template for elements to render between each row, such as line breaks.

Page 37: AJAX Asynchronous JavaScript and XML:

Repeater Example<asp:Repeater ID="Repeater1" runat="server" DataSourceID="AccessDataSource1"> <ItemTemplate> <img border='0' src='../Demo1/Images/<%# DataBinder.Eval(Container.DataItem, "PicPath")%>' width='198' height='151' alt='<%# DataBinder.Eval(Container.DataItem, "PicDescription") %>' />

</ItemTemplate> <SeparatorTemplate> <br /> </SeparatorTemplate></asp:Repeater> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="c:\Salesdb.mdb" SelectCommand="SELECT [PicID], [PicDescription], [PicPath] FROM [PictureTable]"> </asp:AccessDataSource>

Page 38: AJAX Asynchronous JavaScript and XML:

Using DataBinder to Bind the Control in a Template

• System.Web.UI– DataBinder

• Methods– Eval(object, string): Evaluates data-binding expressions at run time.– <%# DataBinder.Eval(Container.DataItem, "PicDescription") %>

• Note: The databinding expression <%# some expression %> is evaluated in the language of the page.  The actual type of DataItem is determined by the type of the datasource. For example, if the datasource is a Dataview, the type of DataItem is DataRowView.  If the type of the datasource is an array of strings, the type of DataItem is String.  If the datasource is a collection of strongly-typed objects (for example "Employees" objects), the type of DataItem is Employees.

Page 39: AJAX Asynchronous JavaScript and XML:

Calendar

• Properties:– SelectionMode: Day, Week, Month– SelectedDate– SelectedDates

• Event:– SelectionChanged

Page 40: AJAX Asynchronous JavaScript and XML:

AdRotator

• AdRotator displays images in an advertisement file which is an XML file with properties of images to display.

Page 41: AJAX Asynchronous JavaScript and XML:

Advertisement File Example

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

<Advertisements><Ad><ImageUrl>../Demo1/Images/cake.jpg</ImageUrl>

<NavigateUrl>default.aspx</NavigateUrl><AlternateText>Great Cake</AlternateText><Impressions>1</Impressions><Keyword>TestAd</Keyword>

</Ad><Ad><ImageUrl>../Demo1/Images/earth2.jpg</ImageUrl>

<NavigateUrl>default.aspx</NavigateUrl><AlternateText>Beautiful Earth</AlternateText><Impressions>1</Impressions><Keyword>TestAd</Keyword>

</Ad>Note: ../ads.xml

Page 42: AJAX Asynchronous JavaScript and XML:

Advertisement Properties

• ImageURL• NavigateURL: The page you go to when you click

an image.• AlternateText: Text displayed for browsers do not

support image.• Keyword: Categorize advertisements, can be used

with AdRotator’s KeyWordFilter property.• Impressions: The relative frequency a particular

advertisement should be shown.

Page 43: AJAX Asynchronous JavaScript and XML:

Validation Controls

• CompareValidator: (Collating sequence comparison)– Properties:

• ControlToValidate• ErrorMessage• Operator: Greater, LessThan, …• ValueToCompare

• RangeValidator:– MaximumValue, MinimumValue

• RequiredFieldValidator

Page 44: AJAX Asynchronous JavaScript and XML:

• CustomValidator: Checks the user’s data entry using validation logic from a customer method you write processed on the server or the client. Use the ClientValidationFunction property to call a client-site validation script. For server-site validation, this control raises an ServerValidate event where you can write an event procedure to validate data. The OnServerValidate event is triggered by: Page.IsValid statement

Page 45: AJAX Asynchronous JavaScript and XML:

Demo: CustomValidator

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

If Page.IsValid Then ‘Note: This statement trigger the ServerValidate event

Response.Write("Valid")

Else

Response.Write("not valid")

End If

End Sub

Private Sub CustomValidator1_ServerValidate(ByVal source As System.Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate

If Not IsNumeric(TextBox1.Text) Then

args.IsValid = False

Else

args.IsValid = True

End If

End Sub