Internet Programming - 05 06

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Internet Programming

jQuery
Web Servers
jQuery
• jQuery is a fast, small, and feature-rich JavaScript library.
• It makes things like HTML document traversal and manipulation, event handling, animation,
and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
• There are two versions of jQuery available for downloading:
◦ Production version - this is for your live website because it has been minified and compressed
◦ Development version - this is for testing and development (uncompressed and readable code)
◦ https://jquery.com/download/
jQuery (cont.)
• jQuery CDN (Content Delivery Network): such as Google
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">
</script>
</head>

• jQuery local version


<head>
<script src="jquery-3.7.1.min.js">
</script>
</head>
JavaScript jQuery
myElement = document.getElementById("id01"); Return the element with id="id01“:
myElement = $("#id01");
myElements = document.getElementsByTagName("p"); Return all <p> elements:
myElements = $("p");
myElements = Return all elements with class="intro“:
document.getElementsByClassName("intro"); myElements = $(".intro");
myElements = document.querySelectorAll("p.intro"); Return a list of all <p> elements with class="intro“:
myElements = $("p.intro");
myElement.textContent = "Hello Sweden!"; Set the inner text of an HTML element:
myElement.text("Hello Sweden!");
myText = document.getElementById("02").textContent; Get the inner text of an HTML element:
myText = $("#02").text();
myElement.innerHTML = "<p>Hello World</p>"; Set the HTML content of an element:
myElement.html("<p>Hello World</p>");
content = myElement.innerHTML; Get the HTML content of an element:
content = myElement.html();
JavaScript jQuery
myElement.style.display = "none"; Hide an HTML Element:
myElement.hide();
myElement.style.display = ""; Show an HTML Element:
myElement.show();
document.getElementById("demo").style.fontSize = "35px"; Change the font size of an HTML element:
$("#demo").css("font-size","35px");
document.getElementById("id02").remove(); Remove an HTML element:
$("#id02").remove();
myParent = Return the parent of an HTML element:
document.getElementById("02").parentNode.nodeName; myParent = $("#02").parent().prop("nodeName"); ;
Web Architecture
Client-Server Paradigm
Web Server
• web server responds to client requests (typically from a web browser) by
providing resources such as HTML documents.
• For example, when users enter a Uniform Resource Locator (URL) address,
such as www.deitel.com, into a web browser, they are requesting a specific
document from a web server.
• The web server maps the URL to a resource on the server (or to a file on the
server’s network) and returns the requested resource to the client.
• During this interaction, the web server and the client communicate using
the platform-independent Hypertext Transfer Protocol (HTTP), a protocol
for transferring requests and files over the Internet or a local intranet.
Web Server (cont.)
GET Request: HTTP Response
GET /books/downloads.html HTTP/1.1 HTTP/1.1 200 OK
If requested recourse cannot be found:
HTTP/1.1 404 Not found
Web Server (cont.)
• The server then sends one or more HTTP headers, which provide additional information about the data
that will be sent.
◦ Content-type: text/html
◦ MIME type image/jpeg
◦ MIME type text/plain
• The information provided in this header specifies the Multipurpose Internet Mail Extensions (MIME)
type of the content that the server is transmitting to the browser.
• MIME is an Internet standard that specifies data formats so that programs can interpret data correctly.
• The header or set of headers is followed by a blank line, which indicates to the client browser that the
server is finished sending HTTP headers.
• The server then sends the contents of the requested HTML document (downloads.html).
• The client-side browser parses the HTML markup it receives and renders (or displays) the results.
• The server normally keeps the connection open to process other requests from the client.
HTTP
• The Hypertext Transfer Protocol (HTTP) protocol allows
clients and servers to interact and exchange information in
a uniform and reliable manner.
• HTTP uses URIs (Uniform Resource Identifiers) to identify
data on the Internet.
• URIs that specify document locations are called URLs
(Uniform Resource Locators).
HTTP (cont.)
• The two most common HTTP request types (also known as request methods) are get and post.
• Get request typically gets (or retrieves) information from a server. Common uses of get
requests are to retrieve an HTML document or an image, or to fetch search results based on a
user-submitted search term.
• A get request sends information to the server as part of the URL
◦ www.google.com/search?q=deitel
◦ A ? separates the query string from the rest of the URL in a request.
◦ A name/value pair is passed to the server with the name and the value separated by an equals sign (=).
◦ If more than one name/value pair is submitted, each pair is separated by an ampersand (&)
◦ Get request typically limits the query string (i.e., everything to the right of the ?) to a specific number of
characters (2083 in IE)
HTTP (cont.)
• Post request typically posts (or sends) data to a server. Common uses of post requests are to
send form data or documents to a server.
• The post method sends form data as part of the HTTP message, not as part of the URL.
URL
• URL contains information that directs a browser to the resource that
the user wishes to access.
• http://www.deitel.com/books/downloads.html
• Hostname is the name of the server on which the resource residesis :
www.deitel.com
• The hostname is translated into an IP address
• This translation is performed by a domain name system (DNS) server
• DNS server I a computer that maintains a database of hostnames and
their corresponding IP addresses—and the process is called a DNS
lookup.
Multitier Application Architecture
• Web-based applications are multitier applications
(sometimes referred to as n-tier applications) that divide
functionality into separate tiers (i.e., logical groupings of
functionality).
Multitier Application Architecture (cont.)
• The bottom tier (also called the data tier or the information tier) maintains the application’s
data. This tier typically stores data in a relational database management system (RDBMS).
• The middle tier implements business logic, controller logic and presentation logic to control
interactions between the application’s clients and its data.
• The middle tier acts as an intermediary between data in the information tier and the
application’s clients.
Multitier Application Architecture (cont.)
• The middle-tier controller logic processes client requests (such
as requests to view a product catalog) and retrieves data from
the database.
• The middle-tier presentation logic then processes data from
the information tier and presents the content to the client.
• Web applications typically present data to clients as HTML
documents.
• Business logic in the middle tier enforces business rules and
ensures that data is reliable before the application updates a
database or presents data to users.
Multitier Application Architecture (cont.)
• The top tier, or client tier, is the application’s user interface,
which gathers input and displays output.
• Users interact directly with the application through the user
interface, which is typically a web browser, keyboard and
mouse, or a mobile device.
• In response to user actions (e.g., clicking a hyperlink), the client
tier interacts with the middle tier to make requests and to
retrieve data from the information tier. The client tier then
displays the data retrieved for the user. The client tier never
directly interacts with the information tier.
HTTP Session
• Session: an abstract concept to represent a series of HTTP requests and responses between a
specific Web browser and server
• The session's data is stored on the server (only 1 session per client)
• Sessions are often built on top of cookies: the only data the client stores is a cookie holding a
unique session ID on each page request, the client sends its session ID cookie, and the server
uses this to find and retrieve the client's session data.
HTTP Session (cont.)
• Client's browser makes an initial request to
the server
• Server notes client's IP address/browser,
stores some local session data, and sends a
session ID back to client.
• Client sends that same session ID back to
server on future requests
• Server uses session ID to retrieve the data
for the client's session later.
Session Tracking Techniques
▪ Tracking individual clients is known as session tracking.
▪ Personalization makes it possible for e-businesses to communicate effectively with their
customers and also improves users’ ability to locate desired products and services.
▪ To provide personalized services to consumers, e-businesses must be able to recognize clients
when they request information from a site.
▪ HTTP is a stateless protocol—it does not provide information regarding particular clients.
▪ Tracking techniques include Cookies and Session Variables.
• Tracking techniques in ASP.Net MVC: TempData, ViewData and ViewBag
Session Tracking Techniques (cont.)
• TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary.
TempData internally uses session variable and stays for a subsequent HTTP Request. This means
it maintains data when you move one controller to another controller or one action to
another action.
◦ Null checking and typecasting is required while using TempData

• ViewData maintains data when you move from controller to view. It is also a dictionary object
and derived from ViewDataDictionary.
◦ Null checking and typecasting is required while using ViewData.

• ViewBag is a dynamic type property of ControllerBase class which is the base class of all the
controllers. It’s a dynamic wrapper around ViewData casting is not required when you use
ViewBag. ViewBag only transfers data from controller to view, not visa-versa.
Cookies
• Cookies provide web developers with a tool for personalizing web pages.
• A cookie is a piece of data that is stored on the user’s computer to maintain information about
the client during and between browser sessions.
• A website may store a cookie on the client’s computer to record user preferences or other
information that the website can retrieve during the client’s subsequent visits. For example, a
website can retrieve the user’s name from a cookie and use it to display a personalized
greeting.
• Web Browsers store cookies as small text files on the client’s hard drive.
• When a user visits a website, the browser locates any cookies written by scripts on that site
and makes them available to any scripts located on the site.
• The cookies may be accessed only by scripts belonging to the same website from which they
originated .
Cookies (cont.)
• Cookies are accessible in JavaScript through the document object’s cookie property. JavaScript
treats a cookie as a string of text.
• A cookie has the syntax “identifier=value,” where identifier is any valid JavaScript variable
identifier, and value is the value of the cookie variable.
• When multiple cookies exist for one website, identifier-value pairs are separated by semicolons
in the document.cookie string.
• Each cookie has an expiration date, after which the web browser deletes it. This date can be
defined by setting the expires property in the cookie string.
• If a cookie’s expiration date is not set, then the cookie expires by default after the user closes
the browser window.
• A cookie can be deleted immediately by setting the expires property to a date and time in the
past.
ASP.NET Ajax
• Ajax: Asynchronous JavaScript and XML.
• ASP.NET Ajax is used to quickly and easily improve the user experience for the web applications.
• In a traditional web application, the user first fills in the form’s fields, then submits the form . The
browser generates a request to the server, which receives the request and processes it .
• The server generates and sends a response containing the exact page that the browser renders ,
which causes the browser to load the new page and temporarily makes the browser window blank.
• The client waits for the server to respond and reloads the entire page with the data from the
response. While such a synchronous request is being processed on the server, the user cannot
interact with the web page.
• If the user interacts with and submits another form, the process begins again.
• Every full-page refresh required users to reload the full page. Users began to demand a more
responsive model.
Traditional web application reloading the page for every user interaction
ASP.NET Ajax (cont.)
• Ajax web applications add a layer between the client and the server to manage communication between the two
• When the user interacts with the page, the client requests information from the server .
• The request is intercepted by the ASP.NET Ajax controls and sent to the server as an asynchronous request - the
user can continue interacting with the application in the client browser while the server processes the request.
Other user interactions could result in additional requests to the server.
• Once the server responds to the original request , the ASP.NET Ajax control that issued the request calls a client-
side function to process the data returned by the server. This function—known as a callback function—uses
partial-page updates to display the data in the existing web page without reloading the entire page.
• At the same time, the server may be responding to the second request and the client browser may be starting
another partial-page update.
• The callback function updates only a designated part of the page. Such partial-page updates help make web
applications more responsive, making them feel more like desktop applications.
• The web application does not load a new page while the user interacts with it.
Ajax-enabled web application interacting with the server asynchronously
AJAX XMLHttpRequest
• XMLHttpRequest object can be used to exchange data with a web server behind the scenes
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method, url, async, user, psw) Specifies the request
method: the request type GET or POST
url: the file location async: true (asynchronous) or false (synchronous)
user: optional user name psw: optional password
send() Sends the request to the server. Used for GET requests
send(string) Sends the request to the server. Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
Property Description
onload Defines a function to be called when the request is recieved (loaded)
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
statusText Returns the status-text (e.g. "OK" or "Not Found")
Database
• A database is an organized collection of data.
• Database management system (DBMS) provides mechanisms for storing, organizing, retrieving
and modifying data. Database management systems allow for the access and storage of data
without concern for the internal representation of the data in the database.
• Programs connect to, and interact with, a relational database via an interface—software that
facilitates communication between a database management system and a program.
• For example, Java developers can use the JDBC interface to interact with databases. ASP.NET
programmers communicate with databases and manipulate their data through the interface
provided by ADO.NET.
Relational Databases
• A relational database is a logical representation of data that allows the data to be accessed
without consideration of its physical structure.
• A relational database stores data in tables.
• Each column represents a data attribute.
Relational Databases (cont.)
• Entity-relationship (ER) diagram shows the database tables and the relationships among them.
• The first compartment in each box contains the table’s name.
• The names in italic are primary keys. A table’s primary key uniquely identifies each row in the
table. Every row must have a primary-key value, and that value must be unique in the table.
This is known as the Rule of Entity Integrity.
• A foreign key creates a relationship between two tables in which the record with a given
primary key can be referenced many times in the foreign key’s table.
SQL
• SQL (Structured Query Language) is a standard language for storing, manipulating and
retrieving data in databases.
ADO.NET Object Model
• The ADO.NET object model provides an API for accessing database management systems
programmatically.
• ADO.NET namespaces, System.Data.OleDb and System.Data.SqlClient, contain classes that
enable programs to connect with and manipulate data sources—locations that contain data,
such as a database or an XML file.
• Namespace System.Data.OleDb contains classes that are designed to work with any data
source that supports the OLE DB API.
• Namespace System.Data.SqlClient contains classes that are optimized to work with Microsoft
SQL Server databases.
ADO.NET Object Model (cont.)
• An object of class SqlConnection (namespace System.Data.SqlClient) represents a connection
to Microsoft SQL Server database.
• A SqlConnection object keeps track of the location of the data source and any settings that
specify how the data source is to be accessed. A connection is either active (i.e., open and
permitting data to be sent to and retrieved from the data source) or closed.
• An object of class SqlCommand represents a SQL command that a DBMS can execute on a
database. A program can use SqlCommand objects to manipulate a data source through a
SqlConnection. The program must open the connection to the data source before executing one
or more SqlCommands and close the connection once no further access to the data source is
required.
• A connection that remains active for some length of time to permit multiple data operations is
known as a persistent connection.
ADO.NET Object Model (cont.)
• Class DataTable (namespace System.Data) represents a table of data.
• A DataTable contains a collection of DataRows that represent the table’s data. A DataTable also
has a collection of DataColumns that describe the columns in a table.
• An object of class System.Data.DataSet, which consists of a set of DataTables and the
relationships among them, represents a cache of data—data that a program stores temporarily
in local memory. The structure of a DataSet mimics the structure of a relational database.
• An advantage of using class DataSet is that it is disconnected—the program does not need a
persistent connection to the data source to work with data in a DataSet.
• Connection string example
data source=(local);Integrated Security=True; initial catalog=“MyDatabase”
Language Integrate Query (LINQ)
• LINQ allows you to write query expressions, similar to SQL queries, that retrieve information
from a wide variety of data sources, not just databases.
• int[] values = { 2, 9, 5, 0, 3, 7, 1, 4, 8, 5 };
Language Integrate Query (LINQ) (cont.)
• Any method returns true if there’s at least one element, and false if there are no elements.
• First method returns the first element in the result. You should check that the query result is
not empty before calling First.
• Count method returns the number of elements in the results.
• let clause creates a new range variable. This is useful if you need to store a temporary result for
use later in the LINQ query.
LINQ to SQL
▪ LINQ to SQL enables you to access data in SQL Server
databases using the same LINQ syntax.
▪ All LINQ to SQL queries occur via a DataContext class,
which controls the flow of data between the program and
the database.
NoSQL Databases
• “NoSQL” databases such as MongoDB or Redis are alternatives to relational databases.
• There are many different types of databases that are classified as NoSQL. The most common
types are key-value stores , document stores and Graph databases.
• Many NoSQL databases are promoted based on the performance advantages they offer over
relational databases, and the benefit of avoiding doing any schema design or migrations.
Key-value stores
• A key-value store can be thought of as similar to a hash or a dictionary in dynamic
programming languages, in that the only way of addressing content is by using a key, and the
actual data stored at that key is opaque.
• Many key-value stores do offer some abstractions over this; for example, Redis allows a key to
refer to a set or a list, but the rule of finding a value using only a key still applies.
• The actual value stored at each key need not be alike, and could widely differ in structure
between keys.
Document stores
• Document stores like MongoDB.
• In a document store, although a document will often have a unique ID like a key, it is often just a
field inside a larger document.
• These “documents” tend to hold data structured as JSON or XML, and the key difference
between these types of stores and key-value stores is that you can look up data based on the
content of the document, not just the key.
• There are also hybrids between key-value stores and document stores. DynamoDB, for
example, behaves like a key-value store, but you can also add a schema to describe the type of
data stored at a key that allows you to query on the value too. This schema is used to define an
index.
• For performance, both relational and NoSQL databases allow you to specify an index on a table
or collection, which can be used for fast lookups by looking up the data in an index, rather than
searching all the raw data in response to a query.
Graph databases
• Graph databases such as Neo4J represent data as a graph and allow you to write queries by
traversing the graph.
• Columnar databases such as Cassandra work by storing data by the column, rather than by the
row, as in a traditional relational database. This is usually done for performance reasons when
dealing with very large data sets.
SQL or NoSQL
• Whether or not to go relational or NoSQL depends on the type of data you have.
• Most NoSQL databases do not allow joining, so can work out to be less performant for certain types
of query.
• This is often worked around by repeating information inside documents (for example, author name,
rather than linking to an author table), a process known as denormalization.
• A database that is normalized does not contain any repeated or redundant information. Although
denormalized tables are not necessarily problematic, they do make it easier to introduce
inconsistencies, and can make it harder to update data that appears in many places in the database.
• Although NoSQL databases avoid the constraint of formally specifying a schema, you will often
want to have some type of schema to keep a reasonable data structure, either to be read from in
your application or to create indexes.
• NoSQL databases can also be faster to write to, so if you have many more writes than reads, this
can be a better fit, but for most other types of data, a relational database will serve you well.
Thank You
References
▪ Deitel, Harvey M., Paul J. Deitel, and Tem R. Nieto. Internet & world wide web: how to
program.
▪ The Full Stack Developer: Your Essential Guide to the Everyday Skills Expected of a Modern Full
Stack Web Developer, Northwood, Chris.
▪ https://www.dotnetperls.com/sqlconnection

You might also like