Lecture 17 PowerPoint

advertisement
BIT 285:
(Web) Application Programming
Instructor: Craig Duckett
Lecture 17: Tuesday, March 3, 2015
ASP.NET AJAX,
Introduction to Web API & REST API
 Assignment 3: REST Framework is due on Tuesday, March 17th
THE 'INTENTION' OF ASSIGNMENT 3—"FEATURE CREEP" (A REAL-WORLD SCENARIO)
I HAVE REWRITTEN THE ASSIGNMENT 3 DIRECTIONS. LET'S HAVE A LOOK...
 Final Exam is on Tuesday, March 17th
2
What's Up with HTTP?
http://www.w3.org/Protocols/rfc2616/rfc2616
3
What's Up With HTTP?
HTTP stands for Hypertext Transfer Protocol. It's a stateless, application-layer protocol for
communicating between distributed systems, and is the foundation of the modern web. As a
web developer, we all must have a strong understanding of this protocol and how it works,
especially since several methodologies have been developed to take advantage of it in new and
different ways.
4
HTTP Basics
HTTP allows for communication between a variety of hosts and clients, and supports a mixture
of network configurations.
To make this possible, it assumes very little about a particular system, and does not keep state
between different message exchanges.
This makes HTTP a stateless protocol. The communication usually takes place over TCP/IP, but
any reliable transport can be used. The default port for TCP/IP is 80, but other ports can also be
used.
Custom headers can also be created and sent by the client.
5
HTTP Basics
Communication between a host and a client occurs, via a request/response pair. The client
initiates an HTTP request message, which is serviced through a HTTP response message in
return. We'll look at this fundamental message-pair a bit later.
The current version of the protocol is HTTP/1.1, which adds a few extra features to the previous
1.0 version. The most important of these, in my opinion, includes persistent connections,
chunked transfer-coding and fine-grained caching headers. We'll look at these briefly a bit later.
6
URLs
At the heart of web communications is the request message, which are sent via Uniform
Resource Locators (URLs). I'm sure you are already familiar with URLs, but for completeness
sake, I'll include it here. URLs have a simple structure that consists of the following components:
The protocol is typically HTTP, but it can also be HTTPS for secure communications. The default
port is 80, but one can be set explicitly, as illustrated in the above image. The resource path is the
local path to the resource on the server.
7
HTTP Verbs
URLs reveal the identity of the particular host with which we want to communicate, but the action
that should be performed on the host is specified via HTTP verbs. Of course, there are several actions
that a client would like the host to perform. HTTP has formalized on a few that capture the essentials
that are universally applicable for all kinds of applications. These request verbs are:
GET: fetch an existing resource. The URL contains all the necessary information the server needs to
locate and return the resource.
POST: create a new resource. POST requests usually carry a payload that specifies the data for the new
resource.
PUT: update an existing resource. The payload may contain the updated data for the resource.
DELETE: delete an existing resource.
The above four verbs are the most popular, and most tools and frameworks explicitly expose these
request verbs. PUT and DELETE are sometimes considered specialized versions of the POST verb, and
they may be packaged as POST requests with the payload containing the exact action: create, update
or delete.
8
Status Codes
With URLs and verbs, the client can initiate requests to the server. In return, the server responds with status
codes and message payloads. The status code is important and tells the client how to interpret the server
response. The HTTP spec defines certain number ranges for specific types of responses:
1xx: Informational Messages This class of codes was introduced in HTTP/1.1 and is purely provisional. The
server can send a 100-continue message, telling the client to continue sending the remainder of the
request, or ignore if it has already sent it.
2xx: Successful This tells the client that the request was successfully processed. The most common code is
200 OK.
3xx: Redirection This requires the client to take additional action. The most common use-case is to jump to
a different URL in order to fetch the resource.
4xx: Client Error These codes are used when the server thinks that the client is at fault, either by requesting
an invalid resource or making a bad request. The most popular code in this class is 404 Not Found
5xx: Server Error These codes are used when the server thinks that the client is at fault, either by
requesting an invalid resource or making a bad request. The most popular code in this class is 404 Not
Found
9
Request-Response Message Formats
So far, we've seen that URLs, verbs and status codes make up the fundamental pieces of an HTTP
request/response pair.
10
Request-Response Message Formats
Let's now look at the content of these messages. The HTTP specification states that a request or response
message has the following generic structure:
It's mandatory to place a new line between the message headers and body. The message can contain one or more
headers, of which are broadly classified into:
• general headers
• request specific headers
• response specific headers
• entity headers
11
Request Format
The request message has the same generic structure as above, except for the request line which looks like:
A typical request message might look like:
12
Response Format
The response format is similar to the request message, except for the status line and headers. The status
line has the following structure:
13
Tools to View HTTP Traffic
There are a number of tools available to monitor HTTP communication. Here, we list some of the more
popular tools.
Undoubtedly, the Chrome Devtools is a favorite among web developers:
14
Tools to View HTTP Traffic
There are also web debugging proxies, like Fiddler for Windows and Charles for Apple OSX.
15
Using HTTP in Web Frameworks & Libraries
jQuery Ajax
Because jQuery is primarily a client-side library, its Ajax API provides the opposite of a server-side
framework. In other words, it allows you to read response messages and modify request messages. jQuery
exposes a simple API via jQuery.ajax()
16
Just For Fun…
IP Addresses Explained
http://netforbeginners.about.com/od/navigatingthenet/f/IP-Addresses-Explained.htm
How Does the Internet Work
http://www.tldp.org/HOWTO/Unix-and-Internet-Fundamentals-HOWTO/internet.html
17
AJAX
18
AJAX
• AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and
more interactive web applications with the help of XML, HTML, CSS, and Java Script.
• Ajax uses HTML for content, CSS for presentation, along with the Document Object Model and JavaScript for
dynamic content display.
• Conventional web applications transmit information to and from the sever using synchronous requests. It
means you fill out a form, hit submit, and get directed to a new page with new information from the server.
• With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update
the current screen. In the purest sense, the user would never know that anything was even transmitted to the
server.
• XML is commonly used as the format for receiving server data, although any format, including plain text, can be
used.
• AJAX is a web browser technology independent of web server software.
• A user can continue to use the application while the client program requests information from the server in the
background.
• Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger.
• Data-driven as opposed to page-driven.
19
AJAX Links of Interest
• AJAX Tutorial (W3Schools)
• What is AJAX? (TutorialsPoint)
• How AJAX Works
• AJAX Learning Guide (TechTarget)
• AJAX Explained with Code Examples (YouTube)
20
ASP.NET AJAX
21
ASP.NET AJAX
ASP.NET AJAX, previously called "Atlas", is a Microsoft implementation of an AJAX based framework,
created for ASP.NET (although it can be used on other platforms as well).
AJAX stands for Asynchronous JavaScript and XML, which, very simply put, is a way of transferring data
between the server and client without sending the entire page, and thereby creating a complete postback.
AJAX allows for what is called "partial page rendering" which allows for a richer experience for the user,
since loading dynamic content can be done in the background, without refreshing and redrawing the entire
page. If you have ever used Gmail or Outlook Web Access, you have used an Ajax enabled web application.
While it's perfectly possible to use Ajax without Microsoft ASP.NET AJAX, a lot of things are way easier,
since Microsoft has wrapped some of the most tedious parts of Ajax into their implementation. For
instance, the three most popular browsers (Chrome, Firefox, Internet Explorer) require different ways of
using Ajax, and have different JavaScript implementations. ASP.NET AJAX simplifies this a lot and allows you
to write the same code to target these three main browsers.
22
ASP.NET AJAX
DEMO: ajaxdemo1.zip
23
ASP.NET AJAX
In the markup part, we use two new things, when compared to regular ASP.NET: The ScriptManager
control and the UpdatePanel control.
The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is
added, and has to be included on every page where you wish to use AJAX functionality.
After the manager, we have one of the most used controls when working with AJAX, the UpdatePanel. This
control allows you to wrap markup which you would like to allow to be partially updated, that is, updated
without causing a real postback to the server.
Besides those two controls, everything else is standard controls, with no modifications that would indicate
alternate behavior.
24
ASP.NET AJAX
Try running the example, and click the button.
The label will be updated with our usual Hello world text, and the current time. Try repeatedly clicking the
button, and you will see the label get the current timestamp each time.
Notice the wonderful absence of a blinking window and a running status bar - everything is done without
updating anything but the label!
If you wish to see how this page would work without AJAX, try setting the "enablepartialrendering" of the
ScriptManager to false like this:
This will disallow the use of partial rendering on the page, and show you how it would work without AJAX
(the page would postback and reload with every click of the button).
25
ASP.NET AJAX
The UpdatePanel control is probably the most important control in the ASP.NET AJAX package. It will apply
AJAX functionality to controls contained within it, allowing partial rendering of the area.
We already used it in the ajaxdemo1 example, and now we will go into more depth with other aspects of
the control.
The <asp:UpdatePanel> tag has two child tags: the ContentTemplate and the Triggers tags.
The ContentTemplate tag is required, since it holds the content of the panel. The content can be anything
that you would normally put on your page, from literal text to web controls.
The Triggers tag allows you to define certain triggers which will make the panel update it's content.
The next example will show the use of both these child tags.
26
ASP.NET AJAX
DEMO: ajaxdemo2.zip
27
ASP.NET AJAX
So, what's this example all about?
Try running it, and click the two buttons. You will notice that then first button updates only the first
datestamp, while the second button updates both. Why?
We have set the Panels to update conditionally, which means that their content is only updated if
something insides them causes a postback, or if one of the defined triggers are fired.
As you can see, the first UpdatePanel carries a trigger which references the second button. This will ensure
that the first panel is updated even when a control on a different UpdatePanel is used.
The AsyncPostBackTrigger tag is pretty simple—it only takes two attributes, the controlid, a reference to
the control which can trigger it, and the eventname, which tells which eventtype can cause the trigger to
fire. If you wish for the content of a UpdatePanel to be updated no matter what, you may change the
updatemode property to Always.
In general, you should only have UpdatePanels around areas where you wish to do partial updates. Don't
wrap your entire page within an UpdatePanel, and don't be afraid to use several panels, since this will give
you more control of which areas update and when they do it.
28
ASP.NET AJAX
A big problem with AJAX enabled pages in general, is that, by design, each action doesn't represent a state
in your browser, which means that you can't use the Back and Forward buttons to shift between states, and
because the URL doesn't change, a specific state can't be bookmarked or linked to by the user.
This effectively limits the situations in where you can use AJAX in general and the UpdatePanel control
specifically.
Fortunately, Microsoft has solved this problem with the History feature. It can be enabled on the
ScriptManager control, and basically works by adding information to the URL after the # character, which is
normally used for navigating between various parts of the same page.
Let's try creating a sample page which will first show you the problem, and then another page where we fix
it afterwards.
29
ASP.NET AJAX
Demo: ajaxdemo3.zip
30
ASP.NET AJAX
Try running the page and see for yourself.
When you select a new color from the dropdown list, the change is reflected in the label control below it,
and because of the UpdatePanel around it, no real postback is performed and the label is updated without
the page reloading.
This is all very good, but as you can see, no matter how many times you change the color, the URL does not
change and no state is tracked, resulting in dead Back and Forward buttons.
31
ASP.NET AJAX
Let's change that, by making the following changes: The ScriptManager should have the EnableHistory
property set to True and we need to subscribe to the OnNavigate event, like this:
In the Code Behind, we add a single line to our dropdown list event, and then we define our Navigate event
for the ScriptManager, like this:
Demo: ajaxdemo4.zip
32
ASP.NET AJAX
Try running the page now.
Each time you change the color, you will see the URL change, but still without a real postback/page reload,
and you can now use your Back/Forward buttons in the brower.
You will also see that the URL in the address bar actually be copied to a new browser window, and when
the page is loaded, the color is now the same as when you copied the URL. It works!
One thing that might bother you, is the fact that the URL looks very cryptic, like this:
Default.aspx#&&/wEXAQUNU2VsZWN0ZWRDb2xvcgUFR3JlZW6BwCysI0shYsZauxImdaPIIPEYSA==
That's because the values are encoded for security reasons. However, in a lot of cases, the values you store
are really not that important and you might want a more naturally looking URL instead of the more secure
one.
33
ASP.NET AJAX
This can be accomplished by using the EnableSecureHistoryState property on the ScriptManager, like this:
Now when you use the page, the URL will look like this instead:
Default.aspx#&&SelectedColor=Red
Much simpler, but obviously it also allows the user to enter values that you may not have expected, which
you should consider and prepare for when using this feature.
Demo: ajaxdemo5.zip
34
ASP.NET AJAX
One of the problems with Ajax, is the fact that since it's asynchronous and in the background, the browser
will not show you any status.
With fast servers and fast methods, this is not a big problem, but whenever you have a method which takes
up a bit of time, the user is very likely to get impatient.
Fortunately, ASP.NET AJAX solves this problem for us as well, with a nice control called UpdateProgress. It
will use your own template to show that an asynchronous method is working.
Have a look at the following example, which will show the control in action. It will be explained afterwards.
35
ASP.NET AJAX
Demo: ajaxdemo6.zip
36
ASP.NET AJAX
This simple example will just show you how easy it is to use the UpdateProgress control. Once the button is
clicked, the script sleeps for 5 seconds (don't use code like that in your real projects - it's for
demonstrational purposes only!), and the "Loading..." text is displayed on your page. You can use anything
in the ProgressTemplate, including ordinary markup and other controls. A common use is an animated GIF,
positioned strategically on the page using CSS positioning.
You can even have multiple UpdateProgress controls on the page, and by using the
AssociatedUpdatePanelID property, you can make sure that the UpdateProgress is only shown when a
certain UpdatePanel is updated.
The DynamicLayout property is nice to know as well. It tells whether or not the page should reserve space
for your progress control. If it's set to true, which is the default, the space is dynamic, hence it's not
reserved, but taken when the control is shown. If you wish to reserve the space, set this property to false.
To see the difference, add the property to our example and change it back and forth.
If some of your postbacks are fast, the UpdateProgress will only be shown for a very short amount of time,
resulting in a blinking behavior, which may confuse your users. For that reason, you may specify a minimum
amount of time to occur before showing the progress control. This can be done with the DisplayAfter
attribute. Specify a number of milliseconds to elapse before showing the progress control, e.g. 2000 if you
wish to wait for 2 seconds.
37
ASP.NET AJAX
Timer controls allow you to do postbacks at certain intervals. If used together with UpdatePanels, which is
the most common approach, it allows for timed partial updates of your page, but it can be used for posting
back the entire page as well. Here is a small example of using the Timer control. It simply updates a
timestamp every 5 seconds.
Demo: ajaxdemo7.zip
38
ASP.NET AJAX
This is all very simple.
We have a normal UpdatePanel, which carries a Trigger reference to our new Timer control.
This means that the panel is updated when the Timer "ticks", that is, fires the Tick event. The Timer control
uses the interval attribute to define the number of milliseconds to occur before firing the Tick event. As you
can see from our Code Behind code listing, we just update the DateStampLabel each time the Timer fires.
Of course, this could be done more efficiently with a simple piece of JavaScript, which updates the time on
the client side instead of involving the server.
The example is only used to demonstrate the potential of the Timer control.
39
Suggested ASP.NET AJAX Links of Interest
• Microsoft AJAX (Microsoft)
• ASP.NET AJAX (Microsoft)
• ASP.NET AJAX Tutorial
40
REST
Recommended: http://www.quora.com/What-is-REST-in-laymans-terms (8 Answers)
Recommended: http://web.archive.org/web/20130116005443/http://tomayko.com/writings/rest-to-my-wife
41
REST
• REST stands for Representational State Transfer. It relies on a stateless, client-server, cacheable
communications protocol -- and in virtually all cases, the HTTP protocol is used.
• REST is an architecture style for designing networked applications. The idea is that, rather than using complex
mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls
between machines.
• RESTful applications use HTTP requests to post data (create and/or update), read data (e.g., make queries),
and delete data. Thus, REST uses HTTP for all four CRUD (Create / Read / Update / Delete) operations.
• REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls) and Web Services (SOAP,
WSDL, et al.).
• Despite being simple, REST is fully-featured; there's basically nothing you can do in Web Services that can't be
done with a RESTful architecture.
• REST is not a "standard". There will never be a W3C recommendation for REST, for example. And while there
are REST programming frameworks, working with REST is so simple that you can often "roll your own" with
standard library features in languages like Perl, Java, or C#.
42
FYI: REST API and Web API
Note: If you wanted to rework Assignment 3 as a Web Form Web Application, you could take advantage of
the ASP.NET WEB API. It is possible to convert your Web Form Web Site to a Web Form Web Application,
although it is a pretty involved process, which involves creating a new empty Web Application projecting
and copying your files to it from the Web Site.
https://msdn.microsoft.com/en-us/library/vstudio/aa983476%28v=vs.100%29.aspx
YouTube How To Video: https://www.youtube.com/watch?v=oXptokM0v7w
Converting Website to Web Application:
http://www.programajama.com/courses/bit285/expert/book/0101.pdf
Converting Website to Web Application:
http://www.programajama.com/courses/bit285/expert/videos/0101.mp4
Recommended: http://video.ch9.ms/ch9/bec0/7d653c5c-1313-4f4e-a8ed-37ce4fe6bec0/WC103_high.mp4
43
Suggested REST Links of Interest
• Learn REST: A RESTful Tutorial
• Learn REST: A Tutorial
• Intro to REST (Google)
• Learn REST: A RESTful Tutorial (Video)
• REST API in Five Minutes
• A Beginner’s Guide to HTTP and REST
• Build RESTful APIs with ASP.NET
• Learn About ASP.NET Web API (Microsoft)
• RESTful Web Services: The Basics (IBM)
• Tutorial: Building an ASP.NET Web API RESTful Service
44
Lecture 17: In-Class Exercise
From the menu bar, select Lectures and go to the Lectures 17 bar and select Lecture 17 ICE to begin
working on today's in-class exercises.
45
Download