Web X.0: "32 Techknowledge
Web X.0: "32 Techknowledge
0
(Code - ITC602)
Tushar R. Agarwal
M.S., Carnegie Mellon
Product Manager @ $4.5 Billion NYC Startup
Ex-Goldman Sachs, Ex-PwC
Project Management Professional, Agile Certified Practitioner,
Certified Scrum Product Owner & Certified Scrum Master
IT Infrastructure Library Certified
"32 TechKnowledge
“SP publications
Mumbal University
Third Year of Information Technology (2019 Course)
Subject Code Subject Name Credits
ITC602 Web X.0 03
Course Objectives :
1. Understand the basic concepts related to web analytics and semantic web.
2. Understand how TypeScript can help you eliminate bugs in your code and enable you to scale
your code.
4, Apply MongoDB for frontend and backend connectivity using REST API.
5. Apply Flask web development framework to build web applications with less code,
0 Prerequisite 02
Introduction to WebX.0
(Refer Chapter 1)
Type Script
Introduction to AngularJS
Self-learning Topics : MVC model, DOM model, Javascript functions and Error
Handling (Refer Chapter 3)
Module Course Module / Contents Periods
4
MongoDB and Building REST API using MongoDB
REST API : Examining the rules of REST APIs, Evaluating API patterns,
Handling typical CRUD functions (create, read, update, delete), Using Express
and Mongoose to interact with MongoDB, Testing API endpoints
Introduction, Flask Environment Setup, App Routing, URL Building, Flask HTTP
06
Methods, Flask Request Object, Flask cookies, File Uploading in Flask
Developing RIA using AJAX Techniques : CSS, HTML, DOM, XML HTTP
Request, JavaScript, PHP, AJAX as REST Client
05
Introduction to Open Source Frameworks and CMS for RIA : Django, Drupal,
Joomla
(Refer Chapter 6)
Total 39
OOO
WF Web X.0 (MU) 1 Table of Contents
———— ee
Strategy to choose your web analytics tool, Measuring the success ofa website; Web 3.0 and Semantic Web : Cha wae stics
Semantic Web, Components of Semantic Web, Semantic Web Stack, N-Triples and Turtle, Ontology, RDF and SPARQ
Self-learning Topics : Semantic Web Vs Al, SPARQL Vs SQL
Ww TechKnowledge
Padlicatiangs
a, |
1.8.10 Aggregation
soeessssnne 1-23
1811 GLOUPINg
.mnsi nm tan si nas n uina tnimu nt imun tni es. 1-23
1.8.12 Describe
1-24
1.8.13 Update
1-24
1814 Asko.
19 Differences between SQL and SP
ARQL
kop
teh
Chapter 2 : TypeScript
2-1 to 2-24
Syllabus : Overview, TypeScript Internal Architec
ture, TypeScript Environment Setup, TypeScript Types, variable
operators, Decision Making and loops s and
, T ypeScript Functions, TypeScript Classes and Objects, TypeScript
Topics : Javascript Vs TypeScript
Modules Self-learning
wW TechKanwledge
PaBticatians
BF Web X.0 (MU) 3 Table of Contents
ee
———=
2.10.5 = Method Overriding
2.10.6 — Encapsulation -
2.10.7 Interfaces 19
2.11 TypeScript Modules ”
ww TechKaowledge
ablicationgs
3.16 The ng-style Directive
338
3.17 Angular]S Built-In Helper Functions
a
3.17.1 angular.copy
339
3.17.2. angular.equals
#39
3.17.3. angular.isArray
40
3.17.4 angular.isDate
*40
3.17.5 angularmerge
=e
3.17.6 angular.isDefined and angular.isUndefined 3-41
3.17.7 angular.toJson
34
3.18 Using Angular]S with TypeScript
7
Chapter 4: MongoDB and Building REST API using MongoDB Elio 431
Syllabus : MongoDB: Understanding MongoDB, MongoDB Data Types, Administering User Accounts, Configuring Access Control,
Adding Ate MongoDB Driver to Nodejs, Connecting to MongoDB from Node.js, Accessing and Manipulating Databases,
Manipulating MongoDB Documents from Node.js, Accessing MongoDB from Nodejs, Using Mongoose for Structured Schema and
Validation.
REST API: Examining the rules of REST APIs, Evaluating API patterns, Handling typical CRUD functions (create, read, update,
delete), Using Express and Mongoose to interact with MongoDB, Testing API endpoints
Self-learning Topics : MongoDB vs SQL DB
ae TechKnowledg?
SF pattie atirnt
4 Web X.0 (MU) 5 Table of Contents
—
Syllabus : Introduction, Flask Environment Setup, App Routing, URL Building, Flask HTTP Methods, Flask Request Object, Flask
cookies, File Uploading in Flask
Self-learning Topics : Flask Vs Django
Pe TechKnowledge
Publications
SF Web X.0 (MU) 6 Table of Contents
Chapter 6: Rich Internet Application -1 to 6-34
Syllabus : AJAX : Introduction and Working, Developing RIA using AJAX Techniques : CSS, HTML, DOM, XML HTTP Request,
JavaScript, PHP, AJAX as REST Client Introduction to Open Source Frameworks and CMS for RIA: Django, Drupal, Joomla
Self-learning Topics : Applications of AJAX in Blogs, Wikis and RSS Feeds
O00
es ee LE ae 7 — =
—s———
| Evolution of Web X.0; Web Analytics 2.0 : Introduction to Web Analytics, Web Analytics 2.0, Clickstream
Analysis, Strategy to choose your web analytics tool, Measuring the success of a website; Web 3.0 and Semantic
| Web : Characteristics of Semantic Web, Components of Semantic Web, Semantic Web Stack, N-Triples and
Web 2.0
People-Centric
Web 1.0
Info-Centric
Flg.1.1.1
o In the very nascent or beginning stages of the WWW, or as we will now call it, Web 1.0, is all about publishing
information as a one-way medium. The objective was to share information with the world as widely and as fast as
possible. This stage set the foundation for the web as we know it today, It is in that phase that the HTTP and Web
Browsers were born.
o Web 2.0 was the paradigm shift from publishing to participating, Users were encouraged to not just put
information out there, but communicate with others and let information “evolve”. This was the birth of social
media and community resource-sharing. Basic social media like MySpace and Wikipedia were born.
“SE
Web 1.0 Web 2.0 Web 3.0 Web 4.0 Web 5.0
; Old and discarded | Old, but still in | Current iteration | Moving from theoretical | Still theoretical
- almost out of use | use where net] with maximum | to real
bandwidth is | users
low
One way | Two way | Two way | Two way communication | Two way communication
-communication communication | communication with ability to co-relate with ability to understand
with ability to
change
Provide Get and provide | Get, update and | Get, update and provide | Get, update, provide relevant
information information provide relevant information information by inferring
information who the user is
No website | Minor website | Massive updates | Massive updates possible | Massive updates will be
updates updates _ from | possible from | from both end user and | possible by every linked
| end user end user data from similar users | entity on the world wide
on the world wide web web
Examples are | Examples _are | Examples are | Examples are Siri and | Examples are Skynet from
news websites online Facebook —_and | Alexa Terminator movies and Allie
calculators LinkedIn A.l. from The 100
e Tech Knowledge
~ pubiicarions
__Ail
BF web X.0 (MU) 1.3 Introduction to Web X.0
1.2 Web Analytics 2.0
at 1. Setting goals
md 2. Collecting data
o Setting Goals : The business decides the high-level goal or what it is they want to achieve. Examples could be
increasing sales & customer satisfaction or enhancing the brand’s image. The goal could be quantitative like
decreasing the value of per marketing dollar spent from $1 per customer acquired to $0.8 or subjective like
enhancing the business’ rating on the customer satisfaction index.
o Collecting Data : Depending on the use case for the data, the business decides and collects data according to their
needs. HTTP header will get the business geographical information, web crawling and keystroke logging will give
the business your path followed on a website, a customer's unique identification number will give them their
purchase history and so on.
o Processing Data : This step involves aggregating the information, cleaning it to make it usable and turning it into
actionable results.
o Identifying Key Performance Indicators (KPIs) : KPIs tell the business how useful the actionable insights and
results are and enable continuous monitoring of these indicators to understand short and long term patterns in
customer behavior.
o Developing a Strategy : The business decides what the next step once they have understood what the customer
wants and what insights they have received from a large number of customers. This step can dictate any changes
necessary to the business model to get and retain more eyeballs.
o Experimenting and Testing : The business in this step tests out different tactics to see which one works best.
This strategy is called A/B Testing. It tests how different customers respond to different content under different
conditions. Here, a customer is shown multiple kinds of pre-chosen strategies and the business tracks the
customer's response to each of them to determine what worked best.
W TechKnewledge
Publications
WF web x.0 (Mv) 1-4 Introduction to Web X.9=
' ® Offsite Web Analytics: In this solution, the business aggregates all information outside of the organization's website to
provide an analysis of how well the business is operating as a whole, what customer segments look like when
combined, the health of different divisions of the business split by race, geography, etc. Offsite analytics usually
pertains to high level insights instead of detailed information about any one consumer.
e Onsite Web Analytics: On-site web analytics has a very laser sharp focus. It tracks visitors to the website and
understands how they interact with it. How many and which pages did you go through before you bought something,
why did you leave the website and what kind of products you might like.
The above explanation of Web Analytics is as it exists today, but it was not always so rosy. After the birth of the WWW, for
almost a decade, the old web analytics was all about clickstream or clickpath. This refers to the series of hyperlinks or web
pages you visit in a sequence before you reach what you want. This could be on a specific website or all over the web.
Log files are used to store what sites you visit and in what order and they help report user behavior, where they are coming
from (advertisement on Instagram perhaps) and where they are going after they leave you (your competitor for a cheaper
price maybe). As an example, if you leave Amazon's webpage to immediately go check Flipkart for a better rate, Amazon will
want to know that and vice-versa.
o Log files store IP Addresses and not names and can be quite unreliable at determining correct user sessions, so
analytics can often be mixed up with different users.
o Individualization is expensive and if even one wrong recommendation is made to a customer, they might deviate
to something entirely different from what they want on the website, causing them to leave and causing even more
losses than if no individualization was used.
Let us start directly with the major differences between Web Analytics 1.0 and Web Analytics 2.0.
Ww TechKnowledge
Publicatians
SF Web X.0 (MU) 1-5 Introduction to Web X.0
Table 1.2.1 : Differences between Web Analytics 1.0 and Web Analytics 2.0
3 Scope of analysis is only your business Scope of analysis is you and your
competitors
4 Decision making is manual based on reports created Decision making is more automated
5 Business needs of the highest paid person (HiPPo) | Customer needs are important
are important
Clickstream determines the what - what data we want to actually see and store.
Multiple Outcomes Analysis is the how much - by how much have the sales increased, how much has the cost decreased and
how much has the customer loyalty increased.
Experimentation and testing & the customer are the why - why are we choosing the tactic we have chosen to achieve the
desired outcome with the customer.
Competitive intelligence determines what else - what else could you be doing that your competitors are doing to get more
business and keep what you have.
Insights are the gold - the gold about what your customers want that you are mining for!
Voice of customer
The Why
Competitive intelligence
The What Else
The Gold!
Fig.1.2.3
W TechKnewledge
Publicatians
. 5 Introduction to Web X.9
SF web X.0 (MU) = _
Tool
1.2.4 Choosing the Right Web Analytics
first tool you come
web anal ytic s tool or any tool for that matter, is jumping to the
The biggest mistake in choosing th e right
what tool is righ t for us.
across. We hardly ever consider the qu alities that determine
Who makes the decision? Some man ina suit or is the customer's needs
core to determining the short and long term goals.
on the biggest, baddest tool on the market just
Buying a tool that serves your needs now is better than spending money
world may not be the same place in three years.
because you expect to use it’s full functionality over three years. The
If you are looking for less integration efforts and get started right away, an ASP tool may not be the best idea. It may be
cheap but not what you need to scale fast.
From time to time, new browsers and devices come into the market and bring with them various mechanisms to capture
data online - JavaScripts, logs, sniffers, beacons, etc. You want a vendor whose data quality remains consistent and can
capture as many modes of information retrieval as possible.
wy Tech Knowledge
Publications
SF Web X.0 (MU) 1-7 Introduction to Web X.0
Question 4; What is the Total Cost of Ownership (TCO) for your tool?
This is a lot more than just the annual subscription fee. It includes the licensing, integration, support, any additional
hardware you may need, licensing, additional hiring and training and even the risk you take by hiring the vendor. If things
go bad, will your organization brush it off or fire you for your poor judgement? There is a cost associated even with the free
tools, so ask all you need from a vendor to calculate this effectively.
Your organization loses business if the vendor is offline or fails at their job. How good their backup and support services are
is important to make an informed decision.
You may need insights not just on all customers, but on specific segments. Why are my sales down in Gujrat but not in
Mumbai. Why are the millennials buying my products but not Gen Z. Why are most visitors from Kerala signing in between
8-10 PM only? Can the vendor give you detailed enough segments to better understand your consumer base?
Question 7 : How can I export data from your system into my company’s system?
You may want this data for reporting, aggregation, regulations or any other reason. Knowing this will help better plan for
what you buy.
Question 8 : Can I integrate other external data and tools into your service?
A tool should be nimble enough to integrate all top data sources and tools in the market instead of making it unnecessarily
difficult to do so. This shows the vendor's insecurity in their own service.
Question 9 : What are the new features your company has planned for your future to stay ahead.of your
competition?
Ifa company is not agile enough to make quick changes, chances are that a competitor will beat them right from under their
noses and your business may find better value somewhere else.
You will probably get twisted answers but they can also help you understand the vendor. In the long term, the relationship
with good people will be more important than the technologically best tool available in the market.
You have now shortlisted a few vendors. But which one to choose?
Three Bucket Strategy : Categorizing vendors for their diverse offerings is important. Let us assume that A, B and C are
similar vendors and X, Y and Z are similar vendors, If you chose A initially, don’t like it and then switch to
vendor B, which is
very similar to A, you've basically fallen into a trap. Comparing vendors and bucketing them into categories ensures
that
you not capture how different and similar vendors are but also saves you from getting stuck with a similar
vendor in case
the original choice does not work out.
If you have the budget to, choosing a tool from each bucket will give you the highest range
of functionalities and ensure you
make a truly diverse and differentiated choice.
wy TechKnowledga
Publications
SF Web x.0 (MU) Introduction to Weh xX.
=
1.3. Measuring the Success of your Website -
1.3.1 Top KPls
Measuring how successful a website is depends on asking yourself how important the website is and what purpose it serves
or what need it satisfies, We have Key Performance Indicators (KPIs) to measure what that looks like. Let us look at a few
possible KPIs that companies use to track success for a website:
How many visitors who visited the website actually completed what they came to the website for? Some companies
quantify this using on-exit surveys, some track the pages customers go through and guess their purpose. Spending
money is not the only intended outcome. This metric tells us how successfully customers can get to what is important
to them and help you set your priorities.
2. Share of Search
How many customers visit your website as compared to your competitors? How fast is your share of that pie growing
when compared to others? Is it fast enough? This metric tells us how well the marketing dollars are spent to attract
eyeballs and determines the health of your website compared to your competitors in the same space.
3. Visitor Loyalty and Recency
Visitor loyalty tells us how many times a certain customer visits your website. Are most of your
customers just fleeting?
They come and go like the wind? Or do they stick with you? Recency dictates the interval
between their visits. They
may visit your site multiple times every day or once a month. There is a fine line here.
You don’t want only one visitor _
visiting the site all the time. You want your metric to show a large customer base
and a large chunk of them revisit at
frequent intervals.
4. RSS/Feed Subscribers
Really Simple Syndication or RSS how many people are staying tuned
to your site’s blogs or releases as subscribers.
This is important because the subscriber traffic is outside your website and
is not tracked by web analytics tools. This
is the behavior shown by your committed website audience who look
for your content rather than you having to push it
out to them.
5. Percentage of Valuable Exits
Pe TechKnowledge
Publications
SE Web X.0 (MU) 1-9 Introduction to Web X.0
1.3.2 Macro and Micro Website Conversions
A macro conversion is the key customer conversion on your website. For instance, a successful sale on an e-commerce
website or a completed customer sigh-up form. A micro conversion talks about the small interactions a customer has like
the blog sign-up or a potential customer watching a newly featured video. Micro conversions often foretell and create desire
and precede the macro conversion.
Table 1.3.1 shows differences between Macro and Micro Conversion.
Table 1.3.1 : Differences between Macro and Micro Conversion
The Semantic Web or Web 3.0 is based on several component standards and tools as explained below:
e XML: XML gives semantic web a basic format for the use of structured documents and has no particular semantics. It
has many parts:
e XML Schema : XML Schema is a language that gives the semantic web its data typing and allows the XML-created
document structure to be restricted enough to allow predictable computation. No typing could mean lack of typing and
unpredictable document reading capabilities.
¢ Resource Description Framework (RDF) : RDF is an easy three-part data model (subject, predicate, object) that is
used to refer to objects or resources within the semantic web and how these objects or resources relate to each other.
An RDF model is usually shown with XML.
¢ Uniform (or Universal) Resource Identifiers (URI) : URIs are short strings created using ASCII characters that
identify all that is available on the Web. This could be documents, videos, audio, images, downloadable files, unknown
file types, viruses, services, electronic mailboxes and everything else. URIs (also called uniform resource locators, or
URLs) give us access to address resources in a simplified and easy-to-understand way and with just one click, they can
help download information, log into servers and issue different kinds of commands over the web.
e URI contains the URL (Uniform Resource Locator) and the URN (Uniform Resource Name). If the web is your memory
palace, URIs are the tools and manipulations we use to find our way around that palace.
Ww TechKnowledga
* pubtications
Pe:
SF web X.0 (MU) 1-10 Introduction to Web XO
—
Resource Description Framework Schema (RDF-S) : RDF-S describes the properties, the classes within and the
hierarchies within. It stores extensive knowledge of the data model. It allows information to be identified, collated ang
interconnected by different systems, This is similar to a SuperClass in Object Oriented Programming where it describes
the relationships between the objects it contains.
Web Ontology Language (OWL) : OWL is basically the data dictionary. It stores the meaning of all terminology and the
relationships between them. The terms and their relationships are called an ontology. It is a semantic web language
that was designed to store rich and complex language. It is a computational logic-based old-school language that is
exploited by other computer programs all over the web.
The Semantic Web Stack describes the architecture of the Semantic Web (Web 3.0).
The Semantic Web is a combined movement spearheaded by an international standards body widely known as the World
Wide Web Consortium (W3C).
WSC promotes a common data format all over the World Wide Web for ease of use and access. By pushing for the inclusion
of semantic content in web pages all over the world and targeting for massive adoption, the Semantic Web can convert the
current web as we know it, which is dominated by unstructured and semi-structured documents into a well designed web
of structured data.
The Semantic Web stack was the first step that was built on W3C's Resource Description Framework (RDF).
Fig. 1.4.1 shows the Semantic Web Stack, the hierarchy of languages as they exist today (and is constantly changing), where
each layer in the stack makes use of the functionalities of the layers under it.
, The stack shows how various technologies all over the world are standardized for Semantic Web and are organized to make
| the Semantic Web as we want it to be possible. It also portrays how Web 3.0 is basically an extension of and not a
replacement of the classical hypertext web from the 90’s.
Trust
Proof
Unifying Lagic
Ontologies: Rules:
_ OWL RIF/SWRL oO
Querying: 3
SPARQL 3
Taxonomies: RDFS 8
8
Data interchange: RDF
<
Syntax: XML
—_—_—
ay TechKnowledge
SP pupiications
SF Web X.0 (MU) 1-11 Introduction to Web X.0
The bottom layers of the semantic web stack contain old technologies of the times past that are well renowned from
hypertext web and provide a base upon which the semantic web was built.
Internationalized Resource Identifier (IRI), a general way of writing URI, gives us a way to uniquely identify resources and
information all over the semantic web. Semantic Web requires unique identification to allow access and manipulation of
resources within the newer top meant for Semantic Web.
UNICODE is meant to represent and allow manipulation of text in multiple languages to facilitate wider information access.
Semantic Web can also help act as a translator between documents in multiple human languages.
XML is the web’s markup language that allows creation of documents made up of semi-structured information. Semantic
web gives meaning or “semantics” to use a better word to semi-structured information.
XML Namespaces are a way to use markups from multiple sources. Semantic Web is all about stitching data together, and so
this ensures that more than one source can be used in a document.
Middle layers of the semantic web stack contain technologies that have been standardized by the World Wide Web
Consortium to enable the creation of semantic web applications by end users.
e Resource Description Framework (RDF) is meant to create statements in the form of so-called triples. It allows
information about resources to be stored in the form of a graph - and this is why the semantic web is often referred to
as the Giant Global Graph.
e RDF Schema (RDF-S) provides the very basic vocabulary for the RDF as explained in the semantic web components.
Using RDF-S, it is possible to create a large hierarchy of classes and properties that describe them.
° Web Ontology Language (OWL) extends the RDFS by adding additional constructs that can describe the semantics of
RDF statements. It allows creating and manipulating additional constraints like cardinality (just like databases), placing
any number of restrictions of values, or characterizing properties like transitivity. It is based on description logic and
can thus add the power to reason with the semantic web.
e SPAROQL is an RDF querying language and it is used to query an RDF-based data store. Querying languages are required
to retrieve any level of intelligence for semantic web applications.
e RIF is a rule interchange format. It is important, for example, to allow describing relations that cannot be directly
described using description logic used in OWL.
Unrealized Semantic Web Technologies
Top layers of the semantic web stack contain technologies that are yet to be standardized by the W3C or are ideas and
possible technologies that should be implemented in order to realize the dream of the Semantic Web as we want it.
e Cryptography is essential to ensuring and verifying that the semantic web statements are coming from a trusted
by using
source and haven’t been spoofed or manipulated while transferring data in any way. This can be achieved
appropriate digital signatures (mostly public-private key pairs) of RDF statements.
are
Trust is meant to indicate that derived statements are coming from a trusted source and that derived statements
following all necessary rules while being converted from new information.
we
© User Interface is the final user-facing layer that enables us to use semantic web applications. It is the only layer
interact with.
Ww TechKnowledge
Publications
~
1 Semantic Web is as much about the data (graph | Artificial Intelligence is a field of study and it
models with their entities and relationships) as it is | focuses on the logic used to achieve an
about the logic (rules and inferences) outcome and is not concerned with the data.
2 End goal of Semantic Web is to exhibit intelligent | End goal of artificial intelligence is to exhibit
behavior (a very modest goal). human-level intelligence (a very lofty goal).
3 Semantic Web twists and updates the knowledge | Artificial Intelligence twists the model and
(data) to increase the size of the known world to | the computational methodology to achieve
achieve the end goal. the end goal.
4 Semantic Web is the infrastructure for Artificial | Artificial Intelligence is one field of study
Intelligence which is used to convert documents into | that makes use of the output from Semantic
machine readable documents just like Natural | Web, ie. machine readable documents.
Language Processing converts language into machine
readable language. Its output is the input for A.l.
5 Semantic Web's inferences use straightforward rules | Artificial Intelligence makes use of a
and thus lack the complexity of traditional Artificial | complicated web of modelling paradigms
Intelligence. and feedback mechanisms that is lacking in’
Semantic Web.
The Resource Description Framework (RDF) is a highly flexible technology which can address a wide variety of problems.
The RDF is a language created to support the workings of the Semantic Web, in the same way that HTML has helped
jumpstart the original Web.
The RDF is a framework for supporting resource descriptions within the Semantic Web, or metadata (data descriptions
about data), for the Web. RDF gives us common structures that are used for interoperable XML data exchanges throughout
the Web.
RDF is just a standard model for data exchange on the Web. It has many features that allow for data merging even if the
underlying schemas and architectures are different, and it even supports the evolution of such schemas.
RDF expands the interlinked structure of the Web to use Uniform Resource Identifiers to identify the relationship between
things and the two ends of this linked relationship (this is usually referred to as a “triple”). Using this model, RDF
facilitates
both structured and semi-structured data to be mingled and shared all over the Web through different applications.
This interlinked data structure forms a directed and labeled graph where the edges of the graph represent the
name of the
link between two endpoints. These are the graph nodes. This graph is the easiest possible model to remember for RDF
and
is an easy to understand visual explanation.
ey TechKnowledge
~ puplications
SF Web X.0 (MU) 1-13 Introduction to Web X.0
Suraj Leonardo Da Vinci
La Joconde a Washington
Fig. 1.5.1
1.6.1. Turtle
Turtle is the Terse RDF Triple Language - a textual representation of an RDF graph. The below Turtle document will detail
the relationship between Venom and Spiderman from the Marvel Multiverse:
@base <http://example.org/>.
@prefix rdf: <http://www.abc.org/2021/02/22-rdf-syntax-ns#>
@prefix rdfs: <http://www.abc.org/2021/01/rdf-schema#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/>.
@prefix rel: <http://www.abc.net/schemas/relationship/>.
<#venom>
rel:enemyOf <#spiderman> ;
afoaf:Human; # inthe Marvel multiverse
foaf:name "Venom’ .
<#spiderman>
rel:enemyOf <#venom> ;
a foaf:Human ;
foaf:name "Spiderman”, "author"@in.
P.S. “foaf” is the machine-readable ontology, which is short for “friend of a friend” and is used to describe persons.
An RDF-graph consists of triples containing a subject, a predicate and an object.
Simple Triples: The simplest triple statement is just a sequence written as (subject, predicate, object), separated by a
whitespace and ending with a‘.' after each triple.
<http://abc.org/#spiderman> <http://www.abc.net/schemas/relationship/enemyOf><http://abc.org/#venom> .
ey TechXnowledge
Publications
| >
BE web x.0 (MU) 1-14 Introduction to Web x
Predicate Lists: The same subject can be referenced by multiple predicates, We can write a series of predicates and objects,
separated by ';', following a subject. This shows a series of RDF Triples associated to that subject and each predicate ang
object associated to one triple.
The following examples are different ways of writing triples:
1.6.2 N-Triple
N-Triple is a format used for storing and transmitting data. It uses plain text serialization to denote RDF erapes Ba
(relationships). “=.
The simplest N-triple is a sequence of 3 terms: a subject, a predicate and an object.
Each is separated by a whitespace and is terminated by a period: '.' after the triple.
<http://example.org/#tushar> <http://www.example.net/relationship/friendOf> <http://example.org/#suraj> .
This format breaks down an RDF graph into its component triples, with one displayed as one line. N-Triples that have been
created from the same RDF graph will always produce the same result and thus look the same, making it a very effective
method to verify and validate the processing ofan RDF/XML document.
The basic structure of an N triple is:
| SF TechKnowledge
Publications
BF Web X.0 (MU) 1-15 Introduction to Web X.0
where name isa string. The predicate is always a uriref, and the object can bea uriref, a blank node, or a literal.
A basic and rudimentary understanding of the N-Triples is sufficient to understand the next topic, which is of utmost
importance: SPARQL.
The primary element of the OWL is an International Resource Identifier. Each entity has an IRI associated with it.
Classes, their properties, associated individuals and data types are the building blocks of the Web Ontology Language.
Classes are conceptual entities. In the common tongue, think of them as common nouns. Author, publisher, paper, worker,
etc. will all be Classes in OWL.
Instances of these Classes will be the Individuals. Tushar as an individual is the author of this book. Think of Tushar
belonging to the CLass Author.
Properties are relationships and are of two types:
1. OWLDatatypeProperty : this denotes the relationship between an individual and a datatype. Eg: hasName,
hasTitle, etc. “Tushar” with the title “Author” would be an example.
2. OWLObjectProperty : this denotes the relationship between individuals and individuals, hasAuthor would be an
excellent example. An instance of the Book Class with the name “WebX.0” has an author who is an instance of the
Class “Author” with the name “Tushar”.
Let us see some basic constructs in OWL:
BF TechKnowledge
Publicucions
BF web x.0 (MU) 1-16 Introduction to Web x9
1.7.3. OWL Class Relations and Constructors
Taxonomy or classification is important for modelling, It helps model relationships between entities like Classes ang
subClasses and understand the properties that exist in the data.
Consider the following constructs:
o Every Author is a Contributor. This tells us that “Author” is a subClass of “Contributor”.
© Every Author is a Writer and vice-versa, This tells us that “Author” and “Writer” are equivalent Classes.
o An Author cannot be a Subscriber and vice versa. This tells us that “Author” and “Subscriber” are disjoint Classes,
OWL has some predefined Classes that help determine hierarchy.
© < owl: Thing > is always the topmost Class, meaning that all other Classes are subClasses of this Class. The
complementary Class to this Class is < owl: Nothing > and it is the bottommost class, meaning that it is the subClass
of all other Classes.
A few complex Class constructors have been explained below:
© <owl: intersectionOf> (conjunction) - This denotes a Class that is an intersection of two other classes, meaning
members of this new Class are members of both Classes that this new Class is an intersection of.
© <owl: unionOf> (disjunction) - This denotes a Class that is a union of two other classes, meaning members of this
new Class are members of either or both of the Classes that this new Class is a Union of.
o <owl: complementOf> (negation) - This denotes a Class in terms of a second Class such that any members of the
second CLass are not members of this Class.
Even more complex class expressions can be created using property restrictions that impose restrictions on the properties
of a Class. OWL has the following restrictions available for use:
<owl : someValuesFrom> +3 age :
<owl : allValuesFrom> ‘
<owl : minQualifiedCardinality>
<owl : maxQualifiedCardinality>
<owl : qualifiedCardinality>
The example below shows us how to use <ow! : someValuesFrom> restriction.
It is the OWL way to write "every book must have at least one author”. Other restrictions can be utilized with a similar
syntax.
< owl: Class rdf: about = "Book” >
< rdfs : subClassOf>
< owl: Restriction >
< owl: onProperty rdf: resource = "hasAuthor’/ > (7)
< owl: someValuesFrom rdf: resource = "Author”/ >
< /owl ; Restriction >
< rdfs : subClassOf >
< /owl: Class >
o <rdfs:subPropertyOf>,
o <rdfs : equivalentProperty> and
o <rdf:inverseOf>.
Ifa certain property_1 is a sub property of property_2, then if property_1 holds true, property_2 will also always hold true.
If property_1 and property_@ are equivalent to each other, then both are sub properties of each other. If property_1 is the
inverse of property_2, then if property_1 holds true for (x,y), property_2 will hold true for (y,x).
The Web Ontology Language supports inherent reasoning as explained already. The OWL has a piece of software called the
reasoner that makes these matches internally and supports multiple reasoning services as will now be explained:
1, Ontology Satisfiability : The reasoner determines if the input ontology is consistent and is free of any contradictions.
For example, “Tushar” is an instance of Class “Author” and “Tushar” is also a negation of Class “Author”. Both cannot
exist simultaneously.
2, Instance Checks : Check if an instance ofa Class is correctly created.
3. Class Satisfiability : If a Class exists in data, it must have an instance. A Class with no instance is like a variable never
used - it’s worthless.
4. Subsumption : Ensure that a subClass declared for a Class has been declared correctly.
5. Classification : Generates all subClass relationships for any given Ontology.
1.8 SPARQL
RDF or the Resource Description Framework is a labeled and
directed format to store graph data and represent it on the
World Wide Web (WWW). RDF is made use of to represent
personal information about individuals, social network graphs
that denote connections between individuals and provide
a way to integrate multiple sources of information. RDF define
the syntax and the necessary semantics of the s
SPARQL, which is a querying language for the
Resource Description
Framework. This language was designed keeping in mind the use
cases and requirements of the RDF.
Ww Tech Knowledge
Publications
>
YF Web X.0 (MU) 1-18 Introduction to Web Xo
—,
Before we begin in earnest, let’s take a simple example where data for a graph will be given with Turtle, so each triple can
be explicitly shown.
Let us look at a simple query over a simple piece of data:
1.8.1 Data
{
<http://learningtest.org/titles/book1> <http:/ /abc.org/dc/titles/1.1/title> ?title .
}
Result
title
SPARQL Learning
Explanation
The SPARQL query above will find the title of the book from the data graph shown
in the form of a triplet. The SELECT
clause of the query identifies the variables in the result and the WHERE
clause provides the graph pattern to mate
against. The graph here is a simple triple pattern with one variable in the object
position (7title). yi
This can be confusing. Let's imagine a graph for a band called “Funk” with an 1207S.
album called “Funky” and a song in that ~~“.
album called “Full Funk” released on December 29, 1994. This band has 4 members:
Tushar, Hardik, Ram and Prerna
Each of them is also a solo player.
Here's the graphical representation of such a band:
raFippe :-More-Funky
Ke : ie,
:date
*More_ Funky" tatty,
rdf. ‘type
("1999-10-03 e 4 Solo Singer
:Prerna
Z,.
cartist 6.
type oe
:Full_Funk Wan “Full Funk"
‘date
!| "1994-12-29"
le
"OT 405
Fig. 1.8.1
Ww Tach Knowledge
FH pupiications
we Web X.0 (MU) 1-19 Introduction to Web XO.
1.8.2 SELECT
The primary SPARQL query is a simple SELECT query which is similar to an SQL query. It has two parts:
WHERE {
<graph pattern to search>
}
The result of this query will be a table with one column for each selected variable and a row for each pattern that matched.
1.8.3 TRIPLES
We can make use of triple patterns to find any matching triples in the graph we have shown above and the variables in the
query become wildcards that can match with any node.
SELECT ?album
WHERE {
?album rdf:type :Album .
}
This is a simple SPARQL SELECT query with just one triple pattern: album rdf:type :Album.
This is a task to search for any nodes where the rdf:type is “Album”.
Result
album
:Funky
:More_Funky
We can use multiple triple patterns together as a graph pattern. Let’s add a triple pattern to the query above and get the
artist with each album.
SELECT *
{
?album a :Album.
}
Ww TechKnowledge
Publications
= s¥
album artist
‘Funky ‘Funk
:More_Funky | :Tushar
Let us add another triple pattern to get album and artist inform
ation for only artists of the SoloSinger type.
SELECT *
{
?albuma:Album.
?artist a :SoloSinger.
}
Here, only one member is found:
album artist
:More_Funky | :Tushar
1.8.5 Ordering Results
If the query above was run on a much larger
dataset with hundreds of songs and albums, you
will get hundreds of rows in
no specified order. Plus, SPARQL does not have
an inbuilt orderin & system, so everytime you run
it, the table might look
different.
ah
To get results sorted by ordering them using a condition,
use the keyword “ODRER BY” just like SQL:
SELECT *
{
?albuma:Album.
cartist artist.
:date ?date.
}
ORDER BY ?date
Result
1.8.6 Slicing
If the database is too large and the result is taking too much time to compute, you can also just slice the result
to get only a
few rows. This is done with the “LIMIT” keyword.
Ww TechKnowledge
Publications
SF Web X.0 (MU) 1-21 Introduction to Web X.0
In the query below, out of the two rows in the last example, only one will be shown and just to show more functionality, I
have also reversed the “ORDER BY" keyword to show dates in descending order (just like SQL).
SELECT *
{
2album a :Album ,
sartist ?artist.
:date ?date
}
ORDER BY desc(?date)
LIMIT 1
Result
1.8.7 Filters
Results can be filtered based on any needed criteria using the comparison, logical and mathematical operators just like SQL.
1, Comparison operators are as follows: (=, !=, <, <=, >, >=)
SELECT *
{
?album a :Album .
sartist 7artist.
:date ?date
FILTER (?date >= "1995-01-01")
}
ORDER BY ?date
Result
We can also use a function to convert dates to just the year component and then filter on that as shown below:
SELECT *
{
?album a:Album.
Wy TechKnowledge
Publications
>
BF Web X.0 (MU) 1-22 Introduction to W
eb X9
——
tartist Partist.
date ?date
ORDER BY ?date
ORDER BY ?date
Result
ORDER BY ?date
Result
1.8.9 Deduplication
Let us assume that the dataset has a large number of albums and son gs. If we
select only the year from all songs and print
that, if any songs/albums were released in the same year, we'll see a
large number of duplicates. In order to handle this
issue, we use the keyword “DISTINCT” just like SQL. We will only see two
rows because our limited dataset has only two
items,
sartist artist.
sdave tute
BIND (year(?date) AS ?year)
}
ORDER BY ?date
He Techinawtedse
puniicaciens
RF Web X.0 (MU) 1-23 Introduction to Web X.0
Result
date
1994
1999
1.8.10 Aggregation
Aggregation refers to applying functions to a list of values rather than just one. If we want to find the earliest date of release
of the band’s songs/albums and latest date for the band’ songs/albums, we will use the MIN/MAX functions on the
aggregated dates of all songs/albums available in the dataset.
Many built-in aggregate functions are available in SPARQL: COUNT, SUM, MIN, MAX, AVG, GROUP_CONCAT, and SAMPLE.
{
Jalbum a :Album.
:date ?date
}
Result
minDate maxDate
“1994-12-29” | “1999-10-03”
{
?album a :Album
}
Result
count
2
1.8.11 Grouping
We can also group results from multiple rows and variables to condense them into tables that provide aggregated or
combined intelligence. This is useful for reporting.
{
?album a :Album;
:date ?date ;
Wver TechKnowledge
Publications
BE Web X.0 (MU) 1-24 _Introductionto Web x,
—,
GROUP BY ?year
ORDER BY ?count
Result
year | count
1994 | 1
1999 | 1
1.8.12 Describe
DESCRIBE returns the RDF graph. It is useful when you don’t know anything about the graph.
DESCRIBE : Funk
The resulting triples has :Funk as the subject.
:Funk a :Band ;
smember :Tushar , :Hardik, :Ram, :Prerna ;
:name "Funk" ;
:description "...",
1.8.13 Update
We can add to the RDF graph using SPARQL. Let us another member to the “Funk” band:
INSERT { a Fog,
?2member a :Suraj .
}
WHERE {
?band a :Funk;
member ?member
}
Result : Suraj is now a member of the band “Funk”.
1.8.14 Ask
These queries return a boolean value if the graphical expression used has a match and returns false if no match is found.
This query is used to find boolean answers and is faster than querying for actual data, so in cases when the database is large
and you only need an answer but don't care about the data, this is a great feature.
The following example query is asking if there is any band in the database that has been credited as the writer of a song:
ASK {
?band a :Band.
?song :writer ?band.
}
Result: true.
———
4 Tech Knowledge
Publications
SF Web X.0 (MU) 1-25 Introduction to Web X.0
==
SPARQL SQL
Used to access a web of linked data Used to access relational databases
SPARQL was designed to deal with data where relationships are often SQL was designed to use data without
stated in the data. relationships.
SPARQL supports ASK queries where the answer is a boolean True or No ASK support in SQL.
False.
Review Questions
Q.1 Explain the progression of the Web from 1.0 to 5.0. (5 Marks)
Q.2 Whatis Clickstream Analytics? State its benefits and drawbacks. (5 Marks)
Q.3 What questions do you ask a vendor before you choose one for your company? (10 Marks)
Q.4 What are the top KPls that help determine the success of your website? (5 Marks)
Q.5 — Give the full form of and define the following: a) RDF and b) URI (5 Marks)
Q.6 Explain in simple language: the Semantic Web Stack. (10 Marks)
Q.7 Differentiate between the Semantic Web and Artificial Intelligence. (5 Marks)
Q.8 Give an example of a Simple Triple in two ways: a) one simple sentence in English, and b) the sentence's Subject
Predicate Object form. (5 Marks)
Q.9 Explain OWL its basic constructs and its types of properties. (10 Marks)
Q.10 What is OWL? Explain the three ways in which OWL properties can be related to each other. (5 Marks)
Q.11 What are OWL profiles? Explain the 5 OWL profiles. (10 Marks)
Overview, TypeScript Internal Architecture, TypeScript Environment Setup, TypeScript Types, variables and
operators, Decision Making and loops, TypeScript Functions, TypeScript Classes and Objects, TypeScript
TypeScript is an open-source, object-oriented programming language which was created and is still maintained by
Microsoft.
TypeScript is an extension of JavaScript. It becomes an extension by adding additional data types, classes, and other object-
oriented features like type-checking. By doing so, TypeScript becomes a superset of JavaScript which compiles just like
plain old JavaScript.
JavaScript is a dynamic programming language but it has no type system. It provides the most basic and primitive data
types like string, number and object, but cannot check any values assigned to a variable. JavaScript variables must be
declared using the “var” keyword, and can be made to point to a value, but it doesn’t have any functionality to support
classes and other object-oriented programming features. So, in the absence of a type system, it is quite difficult to use
JavaScript to create complex applications with multiple people developing and maintaining the same code.
Having a type system increases the quality of the code, increases readability and legibility & makes it easy to maintain and
refactor the entire codebase. But most importantly, any errors can be caught at the compile time itself rather than being
pushed ahead to runtime. This is where TypeScript has an advantage: it catches any errors at compile-time itself, so that
you can fix them before you run your code. TypeScript also supports object-oriented programming features like multiple
data types, classes, enums and a lot more and by doing so, it allows JavaScript to be used at scale.
TypeScript compiles into basic JavaScript. This means that the TypeScript compiler is implemented in TypeScript but can
also be used with any browser or JavaScript engines like Nodejs. All of the popular JavaScript frameworks like Angular.js
and WinJS have been written using TypeScript.
e Cross-Platform : TypeScript can run on any platform that JavaScript can run on. The TypeScript compiler can also be
installed on any OS (Windows, Mac, Linux, Ubuntu).
¢ Object-Oriented : TypeScript gives you access to powerful OOP features like Classes, Interfaces and Modules. We can
write pure OOP code for both client and server side.
ayy
VS Managed
Language Service Editors
VS Shim tsserver
(Shims.ts) (Server.ts)
wy TechKnowledge
Publications
SF Web X.0 (MU) 2-3 TypeScript
e Standalone Compiler (tsc) : It chiefly handles reading and writing files for all the supported engines (e.g. Node,js). It
does the actual parsing of code, type checking within the code and the transformation of TypeScript into JavaScript.
¢ VS Managed Language Service : It exposes a layer around the core compiler to support a set of edit-operations like
statement completions, signatures, formatting and outlining, colors, etc. The language service gives us a slightly new
perspective around working with code and source files as compared to other compilation interfaces. It basically
contains the TypeScript language elements.
° Language Service (services.ts) : It gives birth to information that helps the tools provide better features like
IntelliSense (what parameters you type, what values to use, keep track of data types, etc) or automated refactoring.
e Standalone Server (tsserver) : The standalone server wraps the compiler and the services layer within it and exposes
them to the end user through a JSON protocol.
TypeScript is an Open Source Object Oriented Programming Language. It can run on absolutely any browser and on any
Operating System. All we need are some tools to write and then subsequently test a Typescript program.
Text Editor : A text editor will aid in the writing of a source code file. Examples of such text editors include Notepad,
Notepad++ on Windows, vim or vi on Linux, Atom, Pages on Mac, etc. Text editors can vary with the OS being used.
The source code files for TypeScript are saved with the extension “.ts”
The TypeScript Compiler : The TS compiler is also just a .ts file which has been compiled down to JavaScript (,js) file. The
TypeScript Compiler or TSC creates a JavaScript version of the .ts source code file that has been passed. This is called
transpilation, This TS compiler will however, not process any raw JS file given to it. The TS compiler handles exclusively
“ts” or “.d.ts” files.
Node.js : Node.js is an open source runtime environment that is used for server-side JavaScript programs. It is needed for
JavaScript runs without any browser assistance. It can be downloaded as Node.js source code or as a pre-built .exe installer
for your OS.
1. Number: Numbers are the most basic floating point values. They can be assigned any numeric value like decimals,
hexadecimals, binaries, and octals.
Examples
Examples
W TechKnowledye
Publitations
EF web X.0 (Mv) 2-4 TypeScript
Sa
3. Boolean: For true/false flags and indicators, we use the “boolean” keyword.
Examples
Examples
// correct
let person: [string, number] = ["Tushar", 1994);
// error
W TechKnowledge
Pudlreatioos
SF Web X.0 (MU) 2-5 TypeScript
Examples
Example
}
: '
What is a Variable?
A variable is, in terms of computer programming, just a reserved space in memory with a name attached to it that can store
a value once assigned to that memory. It is simply a memory container. It can be both full and empty based on whether the
programmer has actually assigned a value to that block or declared the variable and left it unassigned.
Declare the variable data type and its value together. var myName:string = “Tushar”
Declare the variable data type without a value and the | var myName:string;
variable will automatically be set to undefined.
Declare the variable’s value but not the data type. The | var myName= Tushar”
variable’s data type will be automatically inferred and set.
Declare neither the data type of the variable nor its value. | var myName;
The data type of such a variable will now become “any” and
it will be set to undefined.
Ww TechKnowledge
Publications
¥
RF Web X.0 (MU) TypeScript
TypeScript Variable Typing
=
TypeScript follows Strong Typing for Variables - meaning that the data type on both sides of an “ =“ must be the same, ora
compilation error will be thrown as shown below :
\ Example
Example Code
console.log(x);
The compiler sees the first occurrence of the variable and reads 5 as a number and assigns it to the variable. If we now try
to assign a string value to it, the compiler will throw an error.
e Global Scope : Declared outside programming constructs and can be accessed from anywhere in your source program.
e Class Scope : These are the variables defined within a class but outside all of that class’ methods. Any object of this
class can make use of the class variables.
e Local Scope : These variables are defined within the methods, loops or functions (class constructs) within a class and
can only be accessed by the class construct that created it.
class VaiablerScoping {
S Techknowledye
BF spiications
|
BF Web X.0 (MU) 2-7 TypeScript
dummyFunction():void {
var local_var = 3; // local variable
}
}
2.6 TypeScript Operators
What is an Operator?
An operator explains the calculations / processing to be performed on data. The data over which these calculations are to
be performed are known as the operands.
Ini+2 = 3.
1 and 2 are the operands, while + and = are the operators, 3 is the result on the operation.
The operators supported by TypeScript are as shown in Fig. 2.6.1.
TypeScript Operators
me 1. Arithmetic operators
=! 2. Logical operators
= 8. Type operators
Ww Tech Knowledge
Publications
a “Sa
Description Example
Operator
&& (AND) | The operator returns true only if all the expressions specified | (A> 10 && B> 10} is False
return true
|| (OR) The operator returns true if at least one of the expression specified | (A > 10 || B > 10) is True
returns true
! (NOT) The operator returns the inverse of the expressions result. | ! (A> 10) is True
For E.g.:! (> 5) returns false
These operators test the relationship between the operands and return a boolean value, i.e. True or False.
Table 2.6.3 : Relational Operators
=e Equality (A == B) is False
~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the | (~B) is- 4
operand
Se TechKnowledst
SP puoricarion®
SF Web X.0 (MU) 2.9 TypeScript
Operator Description Example
<< (Left shift) It moves all the bits In its first operand to the left by the number of | (A<< 1) is 4
places specified in the second operand. New bits are filled with
zeros, shifting a value left by one position is equivalent to
multiplying by 2, shifting two positions is equivalent to multiplying
by 4.and so on.
>> (Right shift) Binary right shift operator. The left operands value is moved right | (A >> 1)is 1
by the number of bits specified by the right operand.
>>> (Right shift with zero) This operator is just like the >> operator except that the bits | (A>>>)is 1
shifted in on the left are always zero.
+= (Add and Assignment) It adds the right operand to the left operand | C + = Ais equivalenttoC=C+A
and assigns the result to the left operand
- = (Subtract and Assignment) | it subtracts the right operand form the left | C- = Ais equivalenttoC=C-A
operand and assigns the result to the left
operand
* = (Multiply and Assignment) | It multiplies the right operand with the left | C* = Ais equivalenttoC=C*A
operand and assigns the result to the left
operand
/ = (Divide and Assignment) It divides the left operand with the right
operand and assigns the result to the left
operand
This is a unary operator denoted using the keyword “typeof”. It returns the data type of the operand fed to it.
Var x= 1994
If condition
is true
Conditional =
code —@)
™
Fig. 2.7.1
Let us look at the kinds of decision statements supported
by TypeScript
Table 2.7.1
We can use just one ‘is’ statements inside an offer ‘is’ or ‘else if statemen
t
4. Switch statement
Sometimes, a code block may need to be executed several times. The basic loop structure
is applicable to TypeScript where
for as long as a condition remains set by a programmer, a block of code will execute
on demand over and over again.
Ww TechKnowledst
Publications
BF Web X.0 (MU) 2-11 TypeScript
—=
Conditional
code
lf condition
j is true
If condition
is false
Condition
9
Fig. 2.8.1
Table 2.8.1
1. | Forloop
The for loop is an implementation of a definite loop
2. | While loop
The while loop executes the instructions each time the condition specified evaluates to true
3. do ... while
The do... while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition
for the first time the loop executes
}
Output
let x: number = 2;
while (x < 5) {
console.log (x )
Xt+;
2
3
4
let x: number = 2;
do {
console.log{ x)
X++;
} while (x <5)
Output
The “break” keyword can be used in TypeScript as well to break out of a construct within which it is invoked.
It essentially
ends the “loop”.
If condition
on is false
| Conditional ae
code
If condition
is true
Fig. 2.8.2
var X= 1;
while (x <= 20) {
if (x% 10 == 0) {
console.log("The loop was broken at: " + x);
break;
}
x++;
wy hea Knowledge
pupiicatian?
Ml
SF Web X.0 (MU) 2-13 TypeScript
The “continue” keyword moves back to the condition and does not execute the subsequent statements after the keyword in
the conditional block for the current iteration. It simply goes back to re-evaluate the condition.
If condition is false
Conditional
code
If condition is true
Fig. 2.8.3
var num:number = 0
var count:number = 0;
for(x=0;x<=10;x++) {
if (x % 2==0) {
continue
}
console.log ("Current loop number: "+x) //outputs 1,3,5,7,9
}
2.9 TypeScript Functions
Functions are the primary code blocks of any programming language. Only with functions can we implement object-
They make the program reusable because the same function can be called any number of times. They make the code
maintainable by keeping it short and allowing different functions to handle different functionalities.
Functions can be created with or without parameters. Parameters or as many call them, arguments to a function are the
operands passed to a function that need to be worked upon within the function. TypeScript requires the same number of
parameters to be passed during invocation as were defined for that function - no more and no less. We will see examples of
this ahead.
In TypeScript, functions are of two types - named functions and anonymous functions
wy TechKnowledge
Publications
BF Web x.0 (MU) 2-14
Table 2.9.1
ee Named Function Anonymous Function
The function is declared with a proper name and is The function is just an expression and is stored
: in a variable. The
“
invoked by that name. function has no name and Is thus invoked using the variable name
Example Function Example Function
function printSomething(
) let printVariable = function()
{ (
console.log("Hello World!"); console.log("Hello World!");
} \
displayQ); printVariable ();
Output Output
Hello World! Hello World!
If we want to write a named function with proper If we want to write an anonymous function with proper
parameters and return types, it would look like this: parameters and return types, it would look like this:
Output
Output 3
3
2.9.2 Arrow Functions
Arrow functions are an alternate way of writing anonymous functions. Some languages even call them lambda functions.
Using a fat arrow as depicted in the example below ( => ), we no longer need to use the “function” keyword. Parameters are
passed as usual within the parentheses and the function is enclosed with curly braces.
Example Arrow Function
let addNumbersVariable= (x: number, y: number): number => {
console.log(x+y);
}
addNumbersVariable(1, 2);
Output
3
An arrow function like a normal anonymous function, can also be written without any parameters:
let printConsoleVariable = () => console.log ("Hello World!");
printConsoleVariable ();
Output
Hello World!
wane
puntlicet!
32 Web X.0 (MU) 2-15 TypeScript
2.9.3 Function Overloading
TypeScript allows for the concept of function overloading by allowing you to reuse a function name with different
parameter types and return types. The only condition enforced by TypeScript is that the number of parameters
for the
overloaded functions should be the same.
console.log (a+b);
}
Input
Output
Tushar Agarwal
Input
Output
When you don’t know how many parameters your function may receive, you use this functionality. TypeScript can bundle
multiple arguments to a function using a variable and bind them together to be used.
As an example, you want users to enter their name. A person could have 1 string in their name (Beyonce) or they could have
even six (Parampeel Parambatur Chinnaswami Muthuswami Venugopal Iyer). In such a case, rest parameters can be used:
function buildPersonName(firstName: string, ..RemainingName: string|[]) {
}
non
let variableName = buildPersonName("Parampeel", "Parambatur ", "Chinnaswami ,» "Muthuswami ", “Venugopal ” ’
“lyer”);
Output
Output
Beyonce
Ww TechXnewledge
Publications
BF Web X.0 (MU) 2-16 TypeScript
Classes are the blueprint in Object Oriented Programming used to create objects.
The “class” keyword is used in TypeScript to declare a class. After this keyword, you add the name of the class. A class
definition in TypeScript must include these:
o Fields: These are the variables declared in a class. This is the data used by objects,
o Constructors : They provide memory for the objects of a class.
© Functions: The actual work / processing for which the class was created. Also called methods.
All these components of the class combined are the data members for this class.
class Person
{
//field
name:string;
//constructor
constructor(name:string)
{
this.name = name
}
//function
printName():void
{
console.log("Nameis : "+this.name)
}
}
This is an example Class called Person. It has a field called “name”. Please note that the “var” keyword is not necessary here
and hence has not been used.
The constructor here is the special function that initializes the variables in this class. In TypeScript, we define a constructor
for a class using the “constructor” keyword. Just like any other function, a constructor can also have parameters.
The “this” keyword refers to the current instance of the class. You will see that the parameter name on the right hand side is
the same as the class’ field on the left hand side. And so, we prefix the class’ field with the keyword “this”,
printName( is a simple function defined here. You will note that the keyword “function” is not needed here and thus, has
not been used.
We create a new instance ofa class in TypeScript by using the keyword “new” followed by the name of the class you want
to create an instance of. This is then assigned to a variable object.
var object_name = new class_name([ arguments if any ])
The RHS here invokes the new class constructor along with any parameters if defined.
var object1 = new Person("Tushar")
ww TechKnoutedge
Pupiscaciars
eee Ter CaN ETENEInITEnTOS TENN
SE
ee Web X.0‘ (MU) 2-17 TypeScript
2.10.3 Accessing Attributes and Functions via Objects
Th e functions an d attributes defined within a class can be accessed after an object for that class has been created using the
dot notation ("."),
Let us access the Class created above,
TypeScripts allows a class to inherit another class’ methods and functions via the use of the keyword “extends”. The class
that uses an existing class’ methods is called the child class while the class being used is the parent class.
Child classes will inherit all the properties and the methods except any private ones.
class Shape
{
Perimeter:number
constructor(p:number)
{
this.Perimeter = p
{
printPerimeter ():void
{
console.log("Perimeter of the square: “+this.Perimeter)
}
var obj = new Square (115);
obj.printPerimeter ()
Output
wy TechKnowledge
Publications
BF Web X.0 (MU)
2-18 TypeScript
Inheritance is of three distinct
kinds
——
class A
{
protected printSomething()
{
console.log("Printing from Class A”)
}
// Expose the protected method as a public function
public callPrintSomething()
{
this.printSomething();
}
class B extends A
{
// Overriding the method from Class A
protected printSomething()
{
super.printSomething();
console.log("Printing from Class B”)
}
var x = new A();
x.callPrintSomething();
Output
ww TechKnowledge
Pyblicariors
SE Web X.0 (MU) 2-19 TypeScript
vary = new B ()
y.callPrintSomething ();
Output
2.10.6 Encapsulation
Classes in TypeScript or most other object oriented programming languages for that matter, can
control visibility of their
resources/data to decide what part of the code can access what kind of
data.
Programmers call the keywords used for data hiding (encapsulation) access
modifiers.
Table 2.10.1
1. | Public
A public data member has universal accessibility. Data member in a class are public by default
2 Private
Private data members are accessible only within the class that defines these members. If an external class
member tries to access a private member, the complier throws an error.
3. Protected
A protected data member is accessible by the members within the same class as that of the former and also by
the members of the child classes.
Example
class DataHidingOrEncapsulation{
x:string = "Tushar”
private y:string = “Agarwal”
}
var obj = new DataHidingOrEncapsulation()
console.log(obj.x)
Output
Tushar
console.log(obj.y)
Compilation Error
2.10.7 Interfaces
An interface defines a structure for any classes you define in your program. It is a contract. If a class or method in the
program uses the interface, it can access all its methods but only if it adheres to the structure defined by the interface.
Ww Tech Knowledge
Publicatiuns
SF Web X.0 (MU) 2-20 TypeScript
—
{
keyComponent: number;
valueComponent: string;
}
The following are examples that make use of this interface:
let x: KeyValuePair = { keyComponent:1, valueComponent:"Tushar" };
// Successful
let y: KeyValuePair = { keyComponent:1, value:"Tushar" };
// Compilation Error: value’ doesn't exist in KeyValuePair
let z: KeyValuePair = { keyComponent:1, valueComponent:1 };
// Compilation Error: Incorrect data type
In the above example, an interface “KeyValuePair “ has been defined and it has two properties:
1) keyComponent and
2) valueComponent.
Variables x and y have been defined as KeyValuePair type, so they must follow the structure defined by the Interface. Only
an object with a number type (keyComponent) and a string type (valueComponent) can be assigned. Any change to the
name or data type will result in a compilation error.
Interface Extension: Interfaces can even extend to use another interface’s properties and methods.
interface Human
{
name: string;
gender: string;
}
interface Student extends Human
{
studentCode: number;
}
let studentObj:Student = {
studentCode: 44156,
name: "Tushar",
gender: "Male"
SF Tech Knowledge
Publicarrans
we
SF Web X.0 (MU) 421 TypeScript
If the Student Interface above is used to
create an object, the Human Interface’s prope
rties and methods must be included.
Not doing so will lead to a compilation error,
Implementing an Interface: Just like any
other object oriented programming language,
TypeScript also allows Classes to
“implement” an interface by using the keyw
ord “implements”,
interface Student
{
studentCode: number;
studentName: string;
studentAge: (studentCode: number) => number;
}
class NewStudent implements Student
{
studentCode: number;
studentName: string;
{
this.studentCode = code;
this.studentName = name;
}
getAge (studentCode:number):number {
return 18;
}
}
let x = new Student(123, "Tushar");
x.getAge(123);
Output
18
Here, the Student Interface is implemented by the Class NewStudent using the “implements” keyword. The implementing
class here is defining all the properties of the Interface in adherence with the contract using the same name and the same
data type. Now doing so would result in a compilation error.
TypeScript by default has global scope. This means that if your code is split into different files and you update a variable by
mistake in one file, it will update that variable in another file (if it exists). This is dangerous.
FF TechKnowledge
Publitations
BF Web X.0 (MU) 2-21 TypeScript
If the Student Interface above is used to create an object, the Human Interface’s properties and methods must be included.
Not doing so willleadtoa compilation error,
Implementing an Interface: Just like any other object oriented programming language, TypeScript also allows Classes to
“implement” an interface by using the keyword “implements”,
interface Student
{
studentCode: number;
studentName: string;
studentAge: (studentCode: number) => number;
}
class NewStudent implements Student
{
studentCode: number;
studentName: string;
{
this.studentCode = code;
this.studentName = name;
}
getAge (studentCode:number):number {
return 18;
}
Jet x = new Student(123, "Tushar");
x.getAge(123);
Output
18
Here, the Student Interface is implemented by the Class NewStudent using the “implements” keyword. The implementing
class here is defining all the properties of the Interface in adherence with the contract using the same name and the same
data type. Now doing so would result in a compilation error.
TypeScript by default has global scope. This means that if your code is split into different files and you update a variable by
mistake in one file, it will update that variable in another file (if it exists), This is dangerous.
Ww TechKnowledge
Publications
WF webxo (MU) 2-22 TypeScript
—=
SourceCodeFile1.ts
var randomVariable: string = “Hello World!";
SourceCodeFile2.ts
console.log (randomVariable);
randomVariable= "Hello Tushar"; // This is acceptable in TypeScript
console.log(randomVariable);
Output
Hello World!
Hello Tushar!
A variable declared in file 1 has been updated by file 2. It is accessible and also open to modifications. Any random
programmer can override variables without intent, opening up the program to unintended errors and bugs. In order to take
care of such an issue, TypeScript has the concept of modules and namespaces.
Modules create a local scope within the file. Now, all methods, variables, functions, etc. in a module are not by default
accessible outside the file. They can be used with the keywords “export” and “import”. One module shares what it has by
exporting itself and the other explicitly uses the exported module by importing it.
Import { resource name } from “file path upto file name without file extension”
Example
SourceCodeFile1.ts
SourceCodeFileZ.ts
console.log (randomVariable);
// Compilation Error
SourceCodeFile3.ts
console.log (randomVariable);
console.log(randomVariable);
Output
Hello World!
Hello Tushar!
Let us look at a little more complicated example to understand the concept. The following is a file that wants to export its
contents:
we TechKnowledge
Publications
—
w .0 (MU TypeScript
ar _Webxo ml) 2-23
StudentFile.ts
{
studentCode: number;
studentName: string;
constructor(sname: string, scode: number)
{
this.studentName = sname:
this.studentCode = scode;
}
printStudent()
{
| console.log ("Student Code: " + this.studentCode + ", StudentName: " + this.studentName )
Output
JavaScript TypeScript
Lightweight with good functions. Missing many Powerful type system and has all JS features
OOP features
Can be converted to TS by changing file extension | Cannot be converted to JS by changing file extension from .ts to .js
from js to .ts
W TechKnowledge
Publications
WF web x0 (MU) 2-24 TypeScript
No Static Typing Enforces Static Typing (value has to be the same as the variable
data type when defined so that type correctness can be checked at
compile time itself)
No support for compile time. JS is an interpreted | Can point out errors in compile time
language (only runtime).
Faster execution Takes time to compile because code is converted into JS upon
compilation
Review Questions
What are the 5 primary features of TypeScript 2? How are JavaScript and TypeScript different ? Explain with 5
differences. (10 Marks)
Q.2 Explain TypeScript's Internal Architecture. (10 Marks)
Q.3 List 10 TypeScript Data Types. How are JavaScript and TypeScript different? Explain with 5 differences. (10 Marks)
Q.4 List 2 TypeScript Data Types with 2 examples each. (5 Marks)
Q.5 What is a variable? List 4 ways a variable can be defined in TS. (5 Marks)
Q.6 Explain Global Scope, Local Scope and Class Scope in TS with a pseudo code. (5 Marks)
Q.7 Explain 5 TS Operators. (10 Marks)
Q.8 List 3 kinds of loops allowed in TS. Draw a flow diagram and write the TS code to loop from 1 to 10 in
TS for any two of
them.
(10 Marks)
ag Explain an arrow function in TS.
(5 Marks)
Q.10 Write the TS pseudo code for Inheritance in TS Classes. List the three kinds of
Inheritance in TS. (10 Marks)
Q. 11 What is Encapsulation. Explain TypeScript's 3 access specifiers.
(5 Marks)
Q. 12 Write a brief on Modules in TS with an example. . (10 Marks)
Q.13 Explain while loop and do while loop with one example of each type
of loop. (10 Marks)
000
Introduction to AngularJS
Overview of AngularJS, Need of AngularJS in real web sites, AngularJS modules, AngularJS built-in directives,
AngularJS custom directives, AngularJS expressions, Angular JS Data Binding, AngularJS filters, AngularJS
controllers, AngularJS scope, AngularJS dependency injection, Angular JS Services, Form Validation, Routing
using ng-Route, ng-Repeat, ng-style, ng-view, Built-in Helper Functions, Using Angular JS with Typescript
Self-learning Topics : MVC model, DOM model, Javascript functions and Error Handling
3.1 Prerequisites
3.1.1. Model-View-Controller
The Model-View-Controller or the MVC is an architectural framework that modularizes an application into three primary
components segregated by the purpose they serve: 1) the model, 2) the view, and 3) the controller.
Each component is built to handle a tailored aspect of development for an application. It is the most widely recognized web
development framework used to create projects that can scale well.
Controller:
Send 4 | Response
ee Request Information
Data Information
f
View Request Model
Respond
to user
User
This component has all the logic and processes that deal with data. It could be as simple as getting data from View via the
Controller and back or processing it first. It fetches data from databases, manipulates it, runs queries, spits out the resujts
and even updates the databases if needed.
2. View
Handles all the UI (User Interface) logic for your application. The text boxes, forms, validations, final results, any tabular
displays, the background, styling, etc. all come under the purview of this component. This is the only component that the
user interacts with and can see.
3. Controller
This component is the interface between the Model and the View. It processes the business logic and contacts the Mode]
based on the needs of the application. It handles the customer input, routes it as needed and controls the overall flow of the
application.
|
Root
Element shits
<heado|
| <body>
Head Element
<h1,h2,h3...> alllkinds
<title> |
; Custom Built-In
Title. Header elements} | elements
Actual Actual \ L. .
Text Text
Attributes] "href"
ww Tech Knowledge
Publicarions
W Web X.0 (MU) 3-3 Introduction to AngularJS
Angular]s is nothing more than a JavaScript framework which can be added to an HTML page using a script tag <script>
</script>..
Knowing the basics of HTML and JavaScript isa prerequisite to understanding AngularJS (just like TypeScript).
Angular]S can extend the attributes allowed by HTML using what are called Directives and can bind data to HTML using
what are called Expressions. We will discuss them in more detail over this chapter.
You can download the required AngularJS software from the library catalogue per your system specifications from
angularjs.org and use any regular IDE that you would use to write JavaScript code.
Let us look at the steps to write a basic Angular]S application.
Below is a simple HTML page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Now, we include angular,js in the head section of the HTML page. The path will be where you saved your file.
<!DOCTYPE html> | -
<html>
<head>
</head>
<body>
</body>
</html>
Let's write a simple application in Angular]S to add 2 numbers:
<!DOCTYPE html>
<html>
<head>
WF TechKnowledge
Publications
WF Web X.0 (MU) . Introduction t
a% asneularls
</head>
= <spana{{x + y}}</span>
</body>
</html>
This is what you see on your browser when this basic code block is executed:
The strange attributes (ng-app, ng-model) and curly braces {{ }} you see
in the code are called Directives and Expressions.
We will discuss them in detail all over the chapter. Here's a brief:
Directives are the attributes that tell AngularJS to attach the
needed and defined behavior to the Document Object Model
(DOM) element. Most Directives in AngularJS begin with ng.
NG stands for Angular. We have used two of them in the code
above: 1) ng-app and 2) ng-model.
The “ng-app” is the origin and it tells the Angular framework
to initialize itself and get ready. The “ng-model” binds HTML
to
AngularJS and assigns the textbox values to the assigned variables
x and y.
The curly braces {{ }} are the Expressions in AngularJS and
as the name clearly states: they compute an expression to
produce a result.
1. Easy to Learn
The view is what the user sees on their browser and the
model is what dictates the functionality behind the view.
With
AngularJS, any changes to the model are seamlessly pushed
to the view with no added change and any change to the
view
percolates to the model in real time. This simplifies the applica
tion's view layer and makes changes to the UI less intrusi
ve.
re TechKnowledge
Pubticatians
BF _Web X0 (MU) 3-5 Introduction to AngularJS
3. Supports Single Page Applications
Angular allows changes to the UI to be made without having to reload the entire page, making a website feel more like a
native application. This is called a Single Page Application. The pages load quicker, the changes seem more fluid, the user
experience is improved significantly, less data is needed for loading and the code is easier to maintain and debug.
4. Declarative UI
AngularJS provides many directives that are ready to use like ng-app, ng-model, ng-repeat etc (all of which will be studied in
this chapter). This makes the UI easy to understand and allows designers and programmers to work together. In the
declarative paradigm, the UI can be designed in any way necessary based on the data in it How would a textbox look when
empty, or filled with invalid or valid data? How would an error be shown? Any such changes can be seamlessly made in
declarative UI without having to throw a popup or reloading the page.
5. Supported by Google
AngularJS gained immense credibility because it is used even by Google for its own pages. This means significant updates
and new functionalities and ready code are often available for the most commonly required use cases. The massive
community of developers is a huge bonus.
7. Real-Time Testing
testing
AngularJS allows end to end unit testing. It has features to oversee the components of the application and has
features to test dependencies. No third party resources are needed for testing with AngularJS.
Note from Author : This chapter covers the entire syllabus, but to ensure better understanding, it does not follow
that a basic
the same flow as given in the official syllabus. The material has been moved around to ensure
through this chapter.
prerequisite understanding is developed in the reader as they move
an AngularJS application.
Ng-app: This is the directive that begins
It begins loading
It defines the root and automatically initializes the application when a webpages using AngularJS is loaded.
all AngularJS modules and components.
<div ng-app = ms
</div>
application data.
Ne-init: This is the directive that initializes the Angular]S
This directive initializes the AngularJS application data. It assigns values to the variables. The code below initializes the data
array.
Within the array and assign the values to the countries
EF TechKnowledge
Publications
| Ww Web X.0 (MU) 3-6 Introduction to Angular]s
</div>
Ng-model: This is the directive that defines the model as a variable. The variable is then used in AngularJS.
</ol>
</div>
Let us look at a piece of code that uses all these directives together:
i . <html>
<head>
<title>Angular[S Directives</title>
</head>
<body>
<h1>Sample Application</h1>
Uae
SF Web X.0 (MU)
3-7 Introduction to AngularJS
{countrycode:'SL',countryname:'Sri Lanka’'},
{countrycode:'PK’,countryname:'Pakistan'}]">
<p>Enter your ID: <input type = "text" hg-model = "id"></p>
<p>Your ID is <span ng-bind = "id"></span></p>
<p>List of Countries with their Coun
try ID:</p>
<ol>
</ol>
</div>
</body>
</html>
Output
Sample Application
Enter your ID:|
Your ID is
As you type your ID in the textbox, the numbers will begin to appear after “Your ID is”.
Expressions in Angular]S can bind data to HTML. They are written using double curly braces {{ }} with the actual expression
inside them. These expressions output the final result of the expression within the braces.
W TechKnowledye
Publications
ee Web X.0 (MU) 3-9 Introduction to Angular]s
SS
j Let us look at an all-encompassing example that uses expressions for numbers, strings, arrays and even objects:
A | <html>
j
<head>
Student Page
Hello Tushar Agarwal!
Student ID is
<script>
function studentInfoController($scope) {
$scope.studentInfo = {
studentFirstName: "Tushar",
studentLastName: "Agarwal",
studentFullName: function() {
var studentInfoObject;
studentInfoObject= $scope.studentInfo;
1h
}
</script>
The “$scope” parameter here points to the application that makes use of the studentInfoController object.
W TechKnowledge
Publications
BF Web x.0 (MU) 3-10 introduction to Angularjs
=—=—S
Let us now look at a full-fledged example with the output
<html>
<head>
</head>
<body>
<h2>Learning Controllers</h2>
</div>
<script>
myApp.controller('studentInfoController’, function($scope) {
$scope.studentInfo = {
studentFirstName: "Tushar",
studentLastName: "Agarwal",
studentFullName: function() {
var studentInfoObject;
studentInfoObject = $scope.studentInfo;
studentInfoObject.studentLastName;
}
ji
));
</script>
</body>
</html>
The output for this program is as shown below. The output changes dynamica
lly if you change the input in the textboxes.
Ww Publications
TechKnowledye
“Z Web X.0 (MU Introduction to AngularJS
3-11
ws
7_We ov)
Learning Controllers
Student's First Name: ‘Tushar
Filters are made use of in Angular]S to modify and twist data as needed. They are usually clubbed with the AngularjS
expressions or directives using a pipe (|) symbol.
Uppercase Filter
in
As the name suggests, the uppercase filter prints text in uppercase. Let us take just a few lines from the code explained
the last section to show the minor change.
<html>
<head>
<title>Angular JS Filters</title>
1.3.14/angular.min.js">
<script src = "https:/ /ajax.googleapis.com/ajax/libs/angular}s/
</script>
Ww TechKnowledge
Publications
SE wep x.0 (MU) Introduction to Angulars
</head>
<body>
</tr>
<tr>
<tr> aia
<td>Enter your subject to filter on: </td>
<td><input type = "text" ng-model = "studentsubjectName"></td>
</tr>
</table>
<br/>
<table border = "0">
<tr>
<tr>
<tr>
Ww TechKnowledge
Peblicatians
SF Web X.0 (MU) 3-13 Introduction to AngularJS
=
<tr>
| orderBy:'subjectMarks'">
{{ subject.subjectName +' Marks: ' + subject.subjectMarks }}
</li>
</ul>
</td>
</tr>
</table>
</div>
<script>
$scope.studentinfo = {
studentFirstName: "Tushar",
studentLastName: "Agarwal", .
fees:500,
subjects:
],
studentFullName: function() {
var studentInfoObject;
studentInfoObject = $scope.studentInfo;
studentinfoObject.studentLastName;
}
};
});
</script>
¥ Tech Knowledge
Publications
WF Web X.0 (MU)
3-14 Introduction to Angularjs
—=—=
</body>
</html>
Output 1: Ifyou type your fees, it dynamically shows up in the format of currency ($)
Output 2 : If you type a subject's name in the textbox, information for only that subject will dynamically
show up below:
AngularJS Sample Application
Modules in AngularJS are just containers for code within the application. Modules
in AngularJS are created with the
AngularJS function “angular.module’”.
Ww TechKnowledge
Publications
¥F Web X.0 (MU)
ais Introduction to Angular)S
We will begin by understanding how to add Controllers to a Module. Let us have a detailed look at how it works:
eiDOCTYPE html>
<html>
<script src="~/angularModules,js"></script>
<body>
<div ng-app="anyName" ng-controller="controllerName">
app.controller("controllerName", function($scope) {
: $scope.studentFirstName ="Tushar”;
S $scope.studentLastName = "Agarwal’;
We
</script>
</body>
hms
Output
Tushar Agarwal
Ee 3 me
In the above code, we added a controller to a module, We can add a built-in directive to modules as well.
SbOGTYPE Kms
shtm>
‘<script src="~,LearningDirectives.js"></script>
‘<body>
<div ng-app="randomApp" learning-directives></div>
<script>
Output
Fchead>
<<title> Learning Modules </title>
<script stc="~LearningModules.js"></script>
</head>
“<body>
: <div ng-controller= “companyNameController’>
Fe - Student First Name: <input type="text" ng-model="studentFirstName"><br>
B Student Last Name: <input type="text" ng-model="studentLastName"><br>
i <br>
| <br>
E Company Name : {{ companyName }}
e}div>
‘<script src="moduleFile.js"></script>
‘<script src="controllersFile,js"></script>
</body>
</html>
Ww Tech Knowledge
Publicarionrs
BF Web X.0 (MU) Introduction to Angular]S
3-17
Output
Learning Modules
Student First Name: | Tushar
|
Student Last Name:| Agarwal |
Student Full Name: Tushar Agarwal
Company Name: Socure
the View:
View is the HTML tags that create the Ul you view. There are various ways to access the Model from
Double brages { yy can be used in the View to access the Model:
Sonos.
epeFirst name: aii mermamette/ ps:
used to achieve the same purpos ] binds the } HTML lement to the Model Property:
The keyword “ng-bind” can be
eg ener
smmermereet nt ~a oy
erm *
<IDOCTY PE html>
<html>
<script src="~LearningTwoWayBinding,js"></script>
‘<body>
<div’ ng-app="randomApp" ng-controller="controller">
_ Name: <input ng-model="textboxName">
___sh1>{{textboxName}}</h1>
sey TechKnowledge
Publications
W Web X0 (MU) 3-18 Introduction to Angular]s
</div>
<script>
</html>...
Output
Name: | Tushar |
Changing the name in the input textbox will automatically update the model and thus, the UI will change without
having to reload the page.
When Directives are named, we use the camelcase (thisIlsCamelCase), but when they are invoked, we
separate the name in
lowercase with dashes (this-is-camel-case).
Example
Ww Tech Knowledge
Publications
ularJS
3-19 Introduction to Ang
1, Element Name
<|DOCTYPE html>
<html>
cri pt>
«script src="~CustomDirectives.js"></s
<body ng-app="randomApp">
cthis-is-a-custom-directive>
</this-is-a-custom-directive>
<scripte
var app * angular.module(*randomApp’, [ ]);
ctiv e’, function() {
app.directive("thislsACustomDire
return {
</body>
</html>
2. Attribute
<!DOCTYPE html>
<html>
<script src="~CustomDirectives.js"></scrip>
<body ng-app="randomApp">
<div this-is-a-custom-directive>
Tech
Papitcations
WF web xo (Muy 3-20 Introduction to Angularjs
—
</div>
<script>
vat app = angular.module(“randomApp", [ ]);
app.directive("thislsACustomDirective’, function() {
return {
template : "<h2>Helo, Tushar Agarwal!</h2>"
}
));
</script>
</body>
</html>
3. Class
<!DOCTYPE html>
“<html>
<script src="~CustomDirectives.js"></script>
<body ng-app="randomApp">
<div class="this-is-a-custom-directive">
</div>
<script>
Yi
</script>
<!"C" must be added to the restrict property to allow invocation of the directive from
a class name>
</body>
</html>
4, Comment
<!DOCTYPE html>
<html>
W TechKnowledga
Publicacians
Pr
ebody ng-app="TandomApp">
ve
<|-- directive: this-is-a-custom-directi -->
escript>
<html> ~
<head> ia 3 bse Oe a
<script sre="~/LearningScope|s"></script>
</head> ~~ cia : : ee
<body ng-app="randomApp"> taal Oy 54s ! Ni + the i ia na “ a
{{message}}<br />
sspan ng-bind="printStatement"></span> <br />
<input type="text" ng-model="printStatement" />
</div>
<script>
var ngApp = angular.module(‘randomApp’, []);
)i
</script>
</body>
</html>
Output
There is also the concept of the $rootScope object in AngularJS. An Angular]S application can have only one root scope. All
other scope objects are child objects for it and will be able to access the root scope’s properties and methods.
<!DOCTYPE html>
<html>
<head>
<script src="~/LearningRootScope.js"></script>
</head>
<body ng-app="randomApplication">
~ <div ng-controller="parentController">
<div ng-controller="childController"> ,
wey Tech Knowledge
Puoticacions
¥F Web X.0 (MU) Introduction to AngularJS
= 3-23 —
> :
Controller Name: {{nameOfController}} <br
Text from Root Scope: {{text}} <br /><br />
</div>
</div>
<div ng-controller="cousinController">
));
ngApp.controller(‘childController’, function ($scope) {
$scope.nameOfController = “childController";
ys;
($scope) {
ngApp.controller(‘cousinController’, function
| ));
</script>
</body>
ie fhtmls ciate ee ees Ste ase
Output
:
Learning AngularJS $rootScope
Controller
What Controller is this?: parent
pe Message!
Text from Root Scope: Root Sco
roller
Controller Name: childCont
Scope Message!
Text from Root Scope: Root
Ww TechKnowledge
Puolicatians
Web X.0 (MU) 3-24 Introduction to AngularJS
WF
3.12 AngularJS Dependency Injection
Dependency Injection Is a built-in functionality for AngularJS which allows you to divide the application you're creating into
multiple kinds of components that can be injected into each other as “dependencies
and makes testing easier.
Dependency Injection modularizes your application and increases reusability, configurability
at an example of them
Let us understand the basic objects and components you will need to know before we look
1. value
2. factory
3 service
4. provider
5. constant
3.12.1 Value
use is to pass values in
Value is a simple object that can be a string or a numeric character or even an object. Its primary
factories, services or controllers.
/ Jdefine a module! in Angular}s. .
var randomModule= angular. miodule(*randomModule’, [);
//create a “Value” object in Angular]S and passing data to it
randomModule.value(“numericValue", 1994);
randomModule.value("stringValue", prushar Agarwal");
Values are defined with the function “value”. This function has two parameters: 1) the name of the value; and 2) the value.
These values can now be invoked using’ the name assigned to them, ‘To “inject” avalue, do the following:
var randomModule = angular. module(“randomModule’”, (D;
randomModule .value("numericValue", 1994);
randomModule.controller("randomController", function($scope, numericValue) {
console.log(numericValue);
});
The above code has successfully injected the value into the controller by assigning it to the function when invoking the
controller.
3.12.2 Factory
Factory is just a function used to return the “Value”. When a service/controller needs the factory to inject a Value, a Value is
created right then and there on demand. The “Factory” function then processes and returns the value.
Let us look at an example.
var randomModule= angular.module("randomModule’, Me
randomModule .factory("randomFactory", function()
UF lechknowtedge
Puvlicacions
w Web X.0 (MU)
3-25 Introduction to AngularJS
—
{
return "My name is Tushar
Agarwal! This is a Valuel":
Vi
randomModule .controller("randomController" , function($scope, randomFactory)
{
console.log(randomFactory);
}):
In the code above, you see a factory created first over a module and then the value created by the factory is injected using a
controller.
3.12.3 Service
In AngularJS, service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by
using the service() function on a module and then vinjected Into controllers.
//define an AngularjS module __
var myApplication= angular. modile("mvabpiccton” [ Fe
» rest of the program ... this is just a section of the code ...
//create an Angular]S service to createa method that returns the square of a numeric input.
myApplication.service('CalculatationService', function(MathematicsService){
- this.square = function(x) { s,
return MathematicsService.multiply(x,x);
}
));
+ ee
$scope.number = defaultInputNumber;
$scope.answer = CalculatationService.square($scope.number);
$scope.square = function() {
$scope.answer = CalculatationService.square($scope.number);
}
);
3.12.4 Provider
A “provider” in AngularJS provides (creates) services and factories. A provider is basically a very simple factory method that
service or factory.
has a “get ()” function that returns the value or
//define an AngularJS module
var myApplication= angular.module("myApplication”, [ ys
~ Test of the program ... this is just a section of the code...
Ww TechKnewledge
Publicacions
WF web xo (MU) 3-26 Introduction to Angularjs
=,
//create an Angular]S service using a “provider” that defines the method “divide"to return the division of two
numbers.
myApplication.config(function($provide) {
$provide,provider('MathematicsService’, function() {
this.$get = function() {
var factory = {};
factory.divide = function(x, y) {
return x / y;
}
return factory;
};
})
Bisa.
3.12.5 Constants
Values cannot be injected into the module.config () function. In such a case, during the config phase, constants are used.
W Tech Knowledge
puntications
‘z Web X.0 (MU)
Introduction to AngularJS
ws
3-27
<script>
randomApplication.config(function($provide) {
$provideprovider('MathematicsService’, functio
n() {
this.$get = function() {
var factory = {};
factory.multiplicationFunction = function(a, b) {
return 2 * b;
}
return factory;
}
});
});
randomApplication.value("defaultInput", 10);
randomApplication.factory('MathematicsService’, function() {
var factory = {};
factorynultiplicationFunction = function(a, b) {
return a * b;
}
return factory;
i
randomApplication.service('CalculationsService'’, function(MathematicsService){
this.squareFunction = function(a) {
return MathematicsService.multiplicationFunction(a,a);
}
);
randomApplication.controller(‘CalculationsController’, function($scope, CalculationsService, defaultInputVariable)
| {
| $scope.number = defaultInputVariable;
$scope.result = CalculationsService.squareFunction($scope.number);
: $scope.squareFunction = function() {
$scope.result = CalculationsService.squareFunction($scope.number);
WF Tech Knowledge
Puvlications
W Web X.0 (MU) 3-28 Introduction toAngularjs
}
)s
</script>
_ </body>
</html>
Output
x2
Result: 36
Services in Angular] are functions or objects that are available to your Angular]S application. Angular]S has many built-in
services but also allows you to create your own customized service.
We will look at a few built-in services first and then build a custom service to help you better understand the concept.
The service “$location” has built-in methods that return information about the location of the current web page.
‘<IDOCTYPE htmi>
fescript src="~LearningLocationService.js"></script>
ebony
‘<div ng-app="randomApp" ng-controller="randomController">
<p>The URL for this web page is as follows:</p>
<h4>({myUrl}}</h4>
jaiv>
<p>H ere, we used the built-in $location service to get the URL for this web page.</p>
‘<script
$scope.myUrl = Slocation.absUr|();
});
</script>
</body>
Soe
</html>
Output
https:/Avww.w3schools.com/angular/tryit.asp? filename=try_ng_services
Here, we used the built-in $location service to get the URL for this web page.
<IDOCTYPEhtmi>
<html> BEST Ses Ol = : 3
<body> | Pate
<div ng-app="randomApp" ng-controller="randomController">
‘<h3>{{myVariable}}</h3>
‘</div> ;
sent back is the
‘<pShttp service has created a request for a page to the tusharagarwal.htm server and the response
Students".</p> 2
value of the variable “myVariable” stored over there which is "Hello Angular]S
scrip
var myApplication = angular.module(‘randomApp', []);
ney YechKnowledga
Publications
WF web x0 (Mv) 3-30 Introduction to Angularjs
=z
Output
$http service has created a request for a page and the response sent back is the value of the variable "my Variable".
This is a built-in service that just after passage of the timeout period in milliseconds, invoked a function specified under
timeout.
<!IDOCTYPE html>
<html>
<script stc="~/LearningTimcouts.js"></script>
<body>
<div ng-app="randomApp" ng-controllcr="randomController">
<p>The header will automatically change after 5 seconds</p>
<hi>{{myHeader}}</h1>
</div>
<p>The $timeout service will invoke a function after the timeout period has passed.</p>
<script>
W Publications
TechKnowledge
—
ee WebX.0 (MU)
e
);
</script>
</body>
‘</html>
Output
1:18:04 PM
Sinterval service updates the current time everyone second. This gives the illusion of an actual clock while in reality,
the time is simply updated every one second using Sinternal service.
Tech Knowledge
Publicacions
ie.
To create and use your custom service, first create a service and connect it to the module. Ater that, add it as a
dependency
when you define the controller.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/li
bs/angularjs/1.6.9/angular.min.js"></scr
<body> ipt>
“<script>
sees
app.controller{'myController’, function($scope, dollarConvert) {
: $scope.dollarAount = dollarConvert.customFunc
tion (15000);
i
</script>
</body> a
</html>
Output
200
We have defined a custom service that coverts INR
to USD.
Ww TechKnowladge
Pubsications
BF Web X.0 (MU) 3-33 Introduction to AngularJS
AngularJS can help monitor the state of the form and the input flelds and then can notify the user if something s wrong. The
state of the form refers to whether the form has been touched/clicked or not, whether it has been modified and whether the
input information matches expectations,
Standards attributes exist built-in for form validation and custom validation can also be performed.
Let us learn two such form validations together. In the next example, the built-in validations will check if an email is valid
and will throw a default value of false because the “required” validation Is also added to it. Let us look at the code first and
then understand them better.
<!DOCTYPE html!>
<html> —
<script src="https:/ /ajax.googleapis.com/ajax/libs/angularjs/ 1.6,9/angular.min,js"></script>
<body ng-app="">
<p>Try writing an E-mail address in the input field:</p>
<form name="learningForms">
<input type="email” name="somelnput" ng-model="somelnput" required>
</form>
<p>The input email address is: (true/false)</p>
<hi>{{learningForms.somelnput.$valid}}</h1>
</body>
</html>
Output without entering any text
false
This is because of the “required” tag used for form validation. If the “required” tag was removed, the default answer above
would be “true”.
true
Ww Tech Knowledge
Publications
OO q
Ww Web X.0 (MU) 3-34 Introduction toAngular]s
=,
7tusharagarwal@ |
false
We have used the state $valid in the example above. Input fields can possess any of the states shown below:
© $untouched - The form field hasn’t been touched by the cursor yet
© $touched - The form field has been touched by the cursor already
o = $pristine - The form field has not been modified/updated/written on yet
© $dirty - The form field has been modified/updated/written on already
© $invalid - The form field’s content entered by the user is invalid
o $valid - The form field’s content entered by the user is valid
Form states are used to pass on meaningful information/error messages to the user. In the code below, ifa field if required
and the user hasn’t entered anything, a warning message is displayed:
<IDOCTY PE html>
‘<html>
‘</body>
</html>
W4 Tech Knowledge
Publicacions
© We b X.0 (MU)
(MU
3-35 Introduction to AngularJS
Output
You will see that the error appears as soon as the cursor touches the name filed and leaves. This same error does not appear
for the address.
Error when the first input field is left blank:
The ng-show directive will display an error message only if the field has been touched by the cursor and it is empty.
Let us now look at a custom form validation. In the example below, the validation will throw a “true” message only if the
entered text has an exclamation mark.
is RITTER
<IDOCTYPE html> be
<html>
ae
4 I
——_ -
ore
AEE RI
i: ~~ return value; =
Ww Tech Knewladge
Puolications
3-36 Introduction to Angularjs
W Web X.0 (MU)
};
}):
</script>
to be considered valid.</p>
<p>The input string must have the exclamation mark "!"
</body>
</html>
Output
[Tushar Agarwal
The input's valid state is:
false
The input string must have the exclamation mark "!” to be considered valid.
true
The input string must have the exclamation mark "!" to be considered valid.
AngularJS has a functionality to navigate to different pages in your application package without having to reload the page.
This is called a Single Page Application. This can be achieved using the “ng-route” module. This module routes your
application during runtime itself to different pages.
To incorporate and allow routing, we must include the AngularJS Route module in our code (second script).
After that, we add ng-route as a dependency. The $routeprovider now configured different routes within the application.
<!DOCTYPE html> ESS peer Sena tea ge : zs
<html>
‘<script src="~/angular.min.js"></script>
<script src="~/angular-route.js"></script>
<body ng-app="randomApplication">
<p><a href="#/!">Main</a></p>
<a href="#!red">Red Text Highlighting </br></a>
<a href="#!green">Green Text Highlighting </br></a>
UF Techknouieist
Publicacions
w Web X.0 (MU)
3.37 Introduction to AngularJS
==
when("/", {
templateUrl : "main.htm" _
})
when("/red", {
templateUrl : "red.htm"
})
when("/green", {
templateUrl:"green.htm"
: :
when("/blue",{_
~ templateUrl :"bluehtm” : eee
5)
be.
</script>
take you to their pages:</br>
<p>Clicking the hyperlinks with color names will
a
Main
Red Text Highlighting
Green Text Highlighting
Blue Text Highlighting
Main
Clicking the hyperlinks with color names will take you to their pages:
"red.htm" from "Red" link
"green.htm" from "Green" link
"blue.htm" from "Blue" link
UF TechKnowledge
Publications
x
Output when Red/Blue/Green Text Highlighting Is Clicked (the text fs highlighted in the color mentioned):
Main
Red Text Wighbebting
Groen Text Highlighting
Blue Text Liiehlighting
CS ke Se OE
Clicking the hyperlinks with color names will take you to their pages:
“red. htm" from "Red" link
"green. htm" from "Green" link
"blue.htm" from "Blue" link
I The Directive “ng-style” is a style attribute for the HTML elements in your page and they are basically an object or an
expression that returns an object.
The object contains the style or speaking in terms of web programming, the CSS properties and values that dictate the style
cf of the web page (front end of your application that the user interacts with). The CSS properties and values are all key value
pairs.
<!DOCTYPE html>
<html>
<script src="https:/ /ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="randomApplication” ng-controller="myController">
<hi ng-style="styleObject">Tushar Agarwal</h1>
<script>
}
Di;
</script>
</body>
</html>
Wser Punticacians
Tech Knowledge
Ss SS
Tushar Agarwal
3.17.1 angular.copy
creates a deep copy of it. Deep copy means that the
The copy function in Angular]S takes any object, or array or variable and
will not update the original. Ina soft copy, updates to
new copy is assigned its own space in memory and changing the copy
the copy will also update the original because they share the same memory block.
3.17.2 angular.equals
on of the two and returns a true if atleast one of
This function compares two objects or values and performs a deep comparis
the following conditions is mat:
determines if 2 objects or values are equal,
The angular.equals function [ angular.equals(value1, value2) ] compares and
least 1 of the following conditions is met.
angular.equals performs a deep comparison and returns true if and only if at
ison).
1. The objects or values must clear the === (deep compar
ties are also equal.
2. Both the objects or values belong to the same data type and their proper
3. Values of both the objects are programmatically NaN.
4, Values of both the objects are equal to the result of the same regular expression.
Ww Tech Knowledge
Publications
3-40 Introduction to Angularjs
id Web X.0 (MU)
Examples
angular.equals({}, { }) // true
angular.equals({x: 1}, {x: 1}) // true
3.17.3 angular.isArray
This function returns a boolean True if and only if the object that is passed to it as a parameter is an array. It is written as:
angular.isArray(parameter)
Examples
saree =
angular.isArray([ ]) // true eee Sn iy ee oe eae fae
angular.isArray([1994, 1995]) // true
angular.isArray({}) // false
angular.isArray(1994) // false”
3.17.4 angular.isDate
This function returns a boolean True if and only if the object passed to it as parameter is of the data type “Date”. It is written
as: angular.isDate(value)
Examples
This function merges the source object by extending the destination object. It is written as: angular.merge(destination,
source)
Examples
angular.merge({}, {}) |
//{}
angular.merge({name: "Tushar"}, {password: "Agarwal"})
//{name: "Tushar", password: "Agarwal"}
angular.merge({x: 1}, {y: {z: {w: 2}}})
PLURAL yea et ws 2} hh
W Pubticacions
TechKnowledge
¥F_Web X.0 (MU) 3-41 Introduction to AngularJS
3.17.6 angular.isDefined and angular.isUndefined
The isDefined function checks if the passed parameter to it has been defined. If it has been, it returns a boolean True, elie
false. The isUndefined function is the exact Opposite. It checks if the passed parameter to It has been defined. If it has been,
itreturns a boolean False, else Truex
They are written as:
angular.isDefined (parameter)
angular.isUndefined(parameter)
Examples
angularisDefined(1994) // true
angular.isDefined([1994, 1995]) // true
angular.isDefined(undefined) // false
angular.isDefined (null) // true
angular.isUndefined(1994) // false
angular.isUndefined(undefined) II true e ;
3.17.7 angular.toJson
This function serializes an object and converts it into the JSON format. Any parameter that begins with $$ will be removed
because $$ indicates internal Angular]S properties. It is written as: angular.toJson(object passed as parameter)
Examples
isNumber})
angulartojson({name: "Tushar", job: "Product Manager’, $SrandomProperty:
/ i : (‘name":"Tushar","job":"Product Manager"}" 3
angular.toJson(1994) :
//"1994"
angular.toJson([1994, "1", 1995, "0"])
// " (1994,"1",1995,"0"] ”
var someFunction= function(value) { return value }
angular.toJson(someFunction)
//undefined, functions have no representation in JSON
Creating Interfaces
eae
codeamodularized,
Angular]S in our application will communicatete w with the backend to get the
tr ack list. To keep theen we wil]
module angular]SWithTypeScript.Interfaces {
export interface myPlaylistService {
getPlaylist: () => Array < myTrack >;
}
export interface myTrack {
songTitle: string;
songArtist: string;
songRating: number;
}
The above code will create a new TypeScript module called “angularJSWithTypeScript”. Two interface definitions have been
added here.
1. myPlaylistService - it has a method called “getPlaylist” and the method shows that it accepts no parameter and
returns an array “myTrack“. This interface just ensures that no random objects get passed to the code and
prevents bugs.
2. myTrack - defines the structure of the actual data for your playlist of songs.
Implementing Interfaces
After having defined the interfaces, now we must implement them. We will create another folder inside the “myApplication”
folder and name this new folder “services”. Here, we add a new TypeScript file called “myPlaylistService.ts” and to it, we add
this code:
httpService: ng.[HttpService ;
static $inject = ["$http"];
constructor($http: ng.JHttpService) {
this.httpService = $http;
}
getPlaylist = () => {
// To make life easy, this code has hardcoded values.
// Inthe real world, GET service would be used with REST APIs to get the
data.
vay TechKnowledge
Publicacions
“7 Web X.0 (MU)
—
WF 3-43 Introduction to Angular]S
var result: Array<angular}SWithTypeScript.Inter
faces .myTrack> =[
{songTitle: "Leave Out All The Rest", songArtist: "LP",
songRating: 5 },
{ songTitle: "Baby", songArtist: "JB", songRating
: 1.2 },
{ songTitle: "Scientist", songArtist: "CP", songRating
: 3.9 },
{ songTitle: "Airplanes", songArtist: "B.0,B.", songRating: 3.0
}
|
return result;
}
angular.module("angularJSWithTypeScript").service("angularJ|SWithTypeScript.Services.PlaylistService”,
PlaylistService);
As can be seen in the code above, our service has been encapsulated within “angularJSWithTypeScript-Services”. The
keyword “export” here allows the service to be called from outside this module using the name of the service
“angularJSWithTypeScript. Services”.
The service we've created must be able to interact with backend APIs and hence, it has “$http”.
You will also see the following line in the code above:
angular.module("angularJSWithTypeScript").service("angularJSWithTypeScript Services.PlaylistService", PlaylistService);
This is the standard Angular]S code which adds the created class to the AngularJS module as a service. But, we have not yet
created the ANgularJS module, so let’s do that next.
Creating the AngularJS Module
We will now create a new TypeScript file called “myApplication.module.ts” in the “myApplication” folder and use the code
below:
(O:void=>{ mee e
yar myApplication = angular.module("angularJSWithTypeScript’, ['ngRoute']);
myApplication.config(angularJSWithTypeScript.Routes.configureRoutes) ;
EC Se ees eet
In the code above, we first created a module with the “ng-route” dependency and then we configured our application with
the routing information by using a reference to a Class (angular]SWithTypeScript.Routes) that has not yet been created. We
will do that next.
Defining the Routes
Let us now add another file to the “myApplication” folder called “myApplication.routes.ts” and add the following code to it:
module angularJSWithTypeScript {
export class Routes {
static $inject = ["$routeProvider"]; _
static configureRoutes($routeProvider: ng.route.|JRouteProvider) {
W Tech Knowledge
Publications
W Web X.0 (MU) 3-44 Introduction to Angular]s
==
3
The "controllerAs” parameter you see for the first route shows that the value will be accessible with the “playlist” alias. We
can access the controller's properties and methods using this alias.
The controller "angularJSWithTypeScript.controllers.typescriptDemoController" has been mapped to the route we will
create next.
Creating the Controller
The controller will be created by adding a new folder to the “myApplication” folder called “controllers” and adding a new
file called “typescriptDemoController.ts” to it.
module angular]SWithTypeScript.controllers {
export class TypeScriptDemoController {
playListService: angularJSWithTypeScript.Interfaces.[PlaylistService;
}
favorites: Array<angular]SWithTypeScript.Interfaces.lITrack>;
}
}
angular.module(“angularWithTypeScript").controller{"angularWithTypeScript.controllers.typeScriptDemoController
", TypeScriptDemoController);
}
A new class is created above called “TypeScriptDemoController” with a dependency service called
“angular]SWithTypeScript.Services.PlaylistService",
We also have a property called “favorites” with an array:
“Array<angularJSWithTypeScript.Interfaces.ITrack>”
We will use this property to bind to the View. The “getFavourites” function populates the “favorites” property with the
result of the call. This will be the click-event handler,
The next step is the View.
Ww TechKnowledge
Publicarions
€F Web X.0 (MU)
3-45 Introduction to AngularJS
creating the View
</ul>
Now, let's bring it all together by adding an “index.html’ file to the “myApplication” folder. and ensure that all CSS files are
added as well to the content folder in your project folder.
w Psi ppolbas met te.me
</div>
</div>
</div>
</div>
~ <script src="scripts/angular.js'></script>
<script src="scripts/angular-route.js"></script>
<script src="app/app.routes.js"></script>
<script src="app/app.module.js"></script>
Ww TechKnowledge
Puolications
Introduction to Angularjs
WF web x.0 (MU) 3-6 SSS
<script src="app/services/playlistService.js"></script>
<script src="app/controllers/tsDemoController.js”></script>
</body>
</html>
Output
When you click the button, the table appears. I have kept the CSS files empty, but you can add any styles you'd like for the
User Interface,
Review Questions
Q.2 Write a simple AngularJS application to add 3 numbers. Draw a mock UI of the output. (10 Marks)
Q.3 State the built-in directives of AngularJS. State without explanation 7 advantages of AngularJS. (5 Marks)
Q.4 What is an AngularJS dependency injection? State 6 examples of AngularJS built-in helper function. (5 Marks)
Q.5 Explain the isDefined and isUndefined functions in AngularJS. (5 Marks)
Q.6 True or False? (5 Marks)
(a) angular.equals( { }, {})
(b) angular.isArray( (1994, 1995] )
(c) angular.isArray( { })
(d) angular.isDate( 1994-12-29 )
(e) angular.isDate( new Date( )
000
Pr
MongoDB: Understanding MongoDB, MongoDB Data Types, Administering User Accounts, Configuring Access Control,
Adding the MongoDB Driver to Node.js, Connecting to MongoDB from Node.js, Accessing and Manipulating Databases,
Manipulating MongoDB Documents from Node.js, Accessing MongoDB from Node.js, Using Mongoose for Structured
Schema and Validation.
REST API: Examining the rules of REST APIs, Evaluating API pattems, Handling typical CRUD functions (create, read,
update, delete), Using Express and Mongoose to interact with MongoDB, Testing API endpoints
MongoDB is a document-database designed for the development of modern applications that require fast scaling. The
architecture allows the program to scale rapidly by adding new nodes to share the responsibilities (computational load).
We will understand what that means over the course of the chapter.
It is essentially an open source & document-oriented DB that can be classified as a NoSQL database, NoSQL tool means that
it doesn’t utilize the usual rows and columns.
MongoDB Documents: These are the documents in a Document Database. MongoDB stores data in the form of JSON
documents.
The Document Data Model allows for natural object-oriented nature in the code, making it simple to use and maintain.
The fields in the JSON document can vary and are not as straightforward as using a relational database, where adding more
data means adding to a new row for all existing columns or adding a column to every existing row.
Documents can be nested for hierarchies to store data in arrays.
JSON structure
{
“car”: “mercedes”
“year”: “2016”
WF Web X.0 (MU) 4-2 MongoDB and Building REST API using MongoDg
“Style”: {
"convertable”
“red”
"leather"
}
“engine”: {
“power”: “12 ohp
”
“liters”: 78"
E}
The document model and the supported hierarchies provide programmers with the flexibility to scale and work on complex
and ever-changing data sources and quickly adapt with growing needs.
MangoDB can even convert documents into Binary JSON or BSON for quicker access and more data type support. MongoDB
however, on the front end, still remains a JSON database.
MongoDB Collections: A group of documents in MongoDB is called a collection. Think of a collection in MongoDB as a table.
Collections, however, can be more flexible. They don’t enforce any schema on the programmer to comply with and
documents part of one collection can have different fields too. Every collection is associated with one MongoDB database.
MongoDB Replica Sets: To ensure high availability, duplicates of the data are stored in MongoDB. Having more than one
copy ensures that data is always available and not lost if something happens to one copy. The system automatically creates
two copies of your data and this is the replica set. This offers redundancy protection and offers availability in times of
maintenance or failure.
MongoDB Sharding: Sharding refers to distributing data across machines to ensure queries can be handled faster using
copies on the closest machines.
MongoDB shards or breaks down the data and then distributes it across the cluster of machines and the result is a highly
scalable architecture.
MongoDB Indexes: MongoDB supports indexing strategies to offer faster execution. This is because queries can scan indexes
first before going through the entire data and reading every document to speed up execution.
MongoDB Aggregation Pipelines: MongoDB has a framework for creating and utilizing data pipelines called aggregation of
pipelines. It enables programmers to process, transform and analyze data at scale using >150 operators and expressions.
2 Not suited to nested data storage Suited for nested data storage
W Tech Knowledge
Publicacions
eF‘g webX.0(
web X.0 (MU) 4-3 MongoDB and Building REST API using MongoDB
Sr. No, RDBMS , ‘MongoDB
4 Predefined schema Dynamic schema
5 Primary Properties : Atomicity, Primary Properties : Consistency,
Consistency, Isolation, and Durability | Availability, and Partition tolerance
“id: Objectld(12axsbt26xbn) Seana seis ence nseae ate eee ee = f Laie rcelaerecorsaranemocien ts ems
{ =
user: ‘user123',
message: Hello World’
user:'user456',
message: ‘Some comment’ ‘
} 3 oe
Ja
De
4.1.5 MongoDB Data Types
W Tech Knowledge
Publicacions
WF webxo (MU) 4-4 MongoDB and Building REST API using Mongopp
=,
* Min/Max Keys: Used to compare the largest and the smallest Binary JSON elements.
User management in database management is of utmost importance to ensure security and understand who is accessing the
database and whether they have the requisite permissions for it. User access can get messy in the absence of proper user
accounts and access control.
MongoDB makes use of RBAC or Role-Based Access Control to implement the required controls and credentials.
So, what is Role Based Access Control ? Role Based Access Control or RBAC is an approach that restricts the use of resources
(system) to only those authorized to use it.
Managing an individual's rights and permissions is as simple in MongoDB as assigning an appropriate role for a task and
placing that role in the user’s account.
3. Permission Authorization : Commands are executed only if permission is authorized on the active role.
MongoDB User Roles
MongoDB has a few different kinds of roles that we will now discuss:
A) Built-in Roles
Role based authorization is enforced via built-in roles that give you several levels of access to the database. Roles can give
several privileges to perform tasks for a resource that is available. They are of several categories:
e User Database : Thai role offers simple read or read and write permissions for the database.
¢ Database Administration : This role offers admin privileges like updating the schema and objects within it.
¢ Cluster Administration : This role can monitor the whole MongoDB system, including the replica sets and the shards
spread all over the cluster.
e Backup and Restoration : This role is responsible for all backup and maintenance activities and has access to cache
data for restoration.
W Tech Knowledge
Puaticacions
¥ Web X.0 (MU)
4-5 MongoDB and Building REST API using MongoDB
All-Database Roles : This role h as access to all the
databases within the schema. Does not have access
to config files.
. supe ruser :; Can grant any level of access to any user
and for any database. This (s root access.
g) User Defined Roles
oDB allows us to creat
of the roles who would use the data
eh the database. db coats Own roles according to our needs and the needs
w eves. db.dro Roled ole() is the function within Mongo that can create new roles and assign them names and
privileges. eb-crop removes a role and db.getRole() gives us information on all existing roles.
What Enind . of action! S come under the purview of Access Control? All actions performed by a user on a resource. They are
called privilege actions.
They are of many kinds :
o Database Management Actions: Changing passwords, creating new collections, creating indexes, etc.
o Querying Actions: Data manipulation like inserts, deletes and all updates.
o Deployment Management Actions: Allow changes to all DB configurations.
o Replication Actions: Set, execute and manage replica sets in MongoDB.
o Server Administration Actions: Maintain the operating system and the logs and ensure that all systems in the
cluster are working.
o _ Sharding Actions: Ability to add and delete shards.
o Session Actions: Create, maintain and kill user sessions.
o Diagnostic Actions: Diagnose stats to know the health of the database for stability and latency issues.
o Free Monitoring Actions: Monitor the database for any untoward events and track live metrics.
Once installed, the following command will give you the version number:
i npm list mongodb sy oe aps eth Hise xi ivan iiuny athe Serer Ih ieee ee en
The next step is getting the Mongo database. We will use a MongoDB-managed database service called Atlas.
You can visit mongodb.com/atlas/database to create a new free tier cluster. A cluster is the set of nodes where all copies of
your data are stored.
UF leciknowtedge
Publications
WF Web x.0 (MU) 4-6 MongoDBan d Building REST API using Mongo goDp
ples of your
Head over to Atlas and create a new cluster in the free tler. At a high level, a cluster Is a set of nodes where copies
database will be stored. Once your tler Is created, load the sample data.
After that, sample data will be loaded. To load some sample data Into the cluster, do the following: i
1, Go to "Database Deployments” view in Atlas and then, in the left navigation pane in Atlas, click on “Database”.
2. Open the dialog titled, “Load Sample Dataset” and now find the cluster you just cr eated to load Atlas’ sample
datasets
in it, Click on the triple dot ellipsis button (... ) to find your cluster.
3. In the dialog that will then appear, click on “Load Sample Dataset”, Atlas will now load some sample datasets into the
Selected cluster.
4. Tosee the sample data, just click your cluster's “Browse Collections” button. You will see multiple sample databases jn
your cluster like mflix, airbnb, geospattal, etc.
The next step is to prepare the newly created cluster to establish the connection.
Go to your cluster just created in Atlas and click on “Connect”. A wizard will now appear. It will ask you to enter your IP
Address to the access list to whitelist it and create a MongoDB user. Note down/remember your username and password.
Next, this Wizard will ask for a connection method. Choose “Connect your Application” and then after entering the node,js
version you have, copy the connection string the Wizard gives you.
Everything is now set up and it’s time to write a piece of code to make sure the connection is working correctly and as
expected. We will write a simple script now in node,js that connects to the database and lists what you have in your cluster.
There are few steps here that we must follows to achieve the desired result:
peers
Import MongoClient : MongoDB exports MongoClient, to be more clear, an instance of MongoClient and thai will assist us
in connecting to the MongoDB database.
=~
ses ees
cluster, call the functions that query into ouredatabase.
async function main) Sees et fags
=
_-//code willbe writtenheresoon = = Srey :
===
Inside the main () function, we have to first create a constant for our connection URI. This is the string I asked
you to copy
early on in the installation procedure. Here, we will also update the username and password for the user we
created earlier.
The connection string also has a dbname placeholder. We will use Atlas’ AirBNB database as a sample here, so dbname
will
be replaced with the name “sample _ airbnb”.
const uri = "mongodb+srv:// / <username>: <password> @ <your-cluster-url> /test?
ec
W Tech Knowledge
Puoticacions
ro
4-7 MongoDB and Building REST API using MongoDB
© web X.0 (MU)
d earlier.
tet us now build a function. This function will print the names of all of Atlas’ inbuilt databases that we importe
Let’s call this function "listDatabases”,
await listDatabases(client);
Let us also go ahead and add a try and catch block to catch any unwanted errors and notify us of them.
try {
await client.connect ();
await listDatabases ( client);
} catch ( exception err) {
consoleerror( err );
}
finally {
await clientclose();
} same
the cluster. We never want concurre nt updates to the
The “finally” statement at the end will close the connection to
cluster by multiple connections.
Now, we call the main function:
ences aie eet Rua a
TOSI) Catch (Console erTOr);Seeu nae
Written all together, it now would look like this :
. Eig mas ee a
async function main () {
> @ <your-cluster-url> /test ?
const uri = “ mongodb+srv:// <username>:<password
retryWrites = true & w = majority ‘
const client = new MongoClient ( uri );
try {
await client.connect( ); //connect to the cluster
call (function will be implemented later)
await listDatabases( client ); //make the needed
} catch ( exception err) {
es
~ console.error(err);
ee
} finally {
await clientclose( );
ee
}
} bent
fw
main().catch( console,error );
s in the cluster and print it on the console:
Let us now write the listDatabases() function to get the list of database
async function listDatabases( client) {
databasesList = await client.db( ).admin( ).listDatabases( );
console.log("List of Databases:");
databasesList.databases.forEach (db => console.log (‘ - ${db.name}} ) );
W Tech Knowledge
Pudlicarions
W Web X.0 (MU) 4-8 MongoDB and Building REST API using Mongopg
Let us now save the file with the name “listdata js” and then Invoke the query from the command line :
node listdatajs
Output :
List of Databases :
~Sample_airbnb
+ sample_geospatial
+ sample_mflix
~Sample_supplies
=admin
“local
W TechKnowledga
Punticacions
<9 web X.0 (MU) MongoDB and Building REST API using MongoDB
= 4-9
if (error) throw err;
console.log( "Your collection has been created |!" );
database.close();
});
);
Once the code has been saved in a file (say "demo_collection_creation. js) and run:
C:\Users\Computer_ Name>node demo collection_creation. js
Output :
collection !!" );
console.log( "Document successfully inserted into
/ database.close();
});
);
the n ame and the value of each field in the document that we aim to insert
Parameter one for the function is an object with
can handle any errors that may arise.
into the collection. The callback function is where we
run it:
Now, save this code ina file say “insert_record.js "andt
C: \Users\Computer. Name>node insert_ record js.
Output :
Document successfully inserted into collection HI
W TechKnewladga
Publications
WF Web X.0 (MU) AAO MongoDB and Building REST API using MongaDB
<==
C:\Users\Computer_Name>node queryjs
Output :
[
-{Jd; 63hd7u8nnd8n3xun3icn394 , name: 'ABC Company’, address; '123 Main Street!}
W Tech Knowledge
Publicacions
€F Web X.0 (MU) 4-11 MongoDB and Building REST API using MongoDB
4.2.3(F) Delete a Record/Collection
The deleteOne
sefining () method
lintinede is used to del ete a record or document from a collection. The first parameter is the query object
toibwcislaedt
Output :
Specified document has been deleted M!
‘Your collection has been successfully deleted !!
To limit the results in the output, we use the limit () method, which has just one parameter: defining the documents to be
returned,
W Tech Knowledge
Punticacians
Sipe -_
Output :
bt |
(id: 4237r23nfd2394bu42324cn, name: Tushar, address: '123 Main Street'},
Prime Avenue’}
{ id: jd242i42nc49242f7234249d, name: Ram, address: ‘123
]
4.2.3(I) Join Collections
“$lookup”. It lets
though MongoDB is not a relational database using
A left outer join can be performed in MongoDB even
collection and what field(s) have to be matched.
you decide which collection you want to join with the current
s”
Assume that you have two collections: “myorders” and “myorderitem
Collection 1: “myorders”
[
{ id: 111, itemname: 'Tootsie Rolls’ },
- {-id: 222, itemname: ‘Cacao Nibs' },
ih
{ id: 222, itemname: ‘Headphones’ praca
ie
rders” collection:
; Now, let’s join the “myorderitems’ to the “myo
).MongoClient;
' var MongoClient = require( ‘mongodb’
12/";
var my_url = "mongodb://128.0.0.1:122
( error, database) {
MongoClient.connect(my_url, function
if ( error) throw error;
var db1 = database.db("mydb");
db1.collection( ‘orders’ ).aggregate (
~ { $lookup:
{
from: myorderitems,
wy TechKnowledge
Pubticacions
WF Web X.0 (MU) 4-14 MongoDB and Building REST API using MongoDR
—=
localField: "product.id’,
foreignField: ‘id’,
as: 'myorderdetails'
}
}
]).toArray(function(error, res) {
if (error) throw error;
console.log(JSON.stringify(res));
database.close();
);
D3
Now, save this code in a file say “join.js” and run it:
C:\Users\Computer_Name>node joinjs = ae
Output :
[
{"_id": 1,"product_id”: 111, "status": 1, "myorderdetails”: [
- {"_id": 111, "name": "Tootsie Rolls" }],
~“id": 1, “product_id": 222, "status": 1, "myorderdetails”: [
i {" id": 222, "name": "Cacao Nibs” },
f Cid": 222, "name": "Headphones" } ]
J
4.3. Using Mongoose for Structured Schema and Validation
Having understood the native node.js driver, we will now make the jump top Mongoose. Mongoose is an Object Document
Model that pipes additional functionality onto the native driver. It simply applies a more structured schema to a collection
and allows for additional validation and type casting of variables.
" The builder object that Mongoose lets you create allows you to pipe commands for finding, updating, saving, removing,
Mn aggregating and many other functionalities. Mongoose won't replace the native nodes driver. It will only enhance this
driver with greater functionalities.
} es See
Defining A Schema
for us the fields and the field
Mongoose is the pre: sence of a Schema. It will define
The main requirement for making use of objects to match
e and typecast any
of in a collection. This comes in handy to validat
data types for the documents made use
We define a data type for
ma is defined for every document type in a collection.
the needs of the predefined schema. A sche
each field in a schema.
WF web x0 (MU) 4-16 MongoDB and Building REST API using MongoDB
=
Understanding Mongoose Path
s
Paths define access to fields in the document hierarchy. If a document has a field name, which
has subdocuments called
firstname, lastname and age, then the paths to the subdocum
ents are as follows:
® name firstname
® name.lastname
¢ name.age
Creating a Mongoose Schema
To create a schema, we need a new instance of the Schema object. It accepts an object describing the schema as the first
parameter and the second parameter are the options available when defining a schema as shown in Table 4.3.1.
Table 4.3.1
Option Description
BufferCommands Boolean - When true, commands cannot be completed due to buffering server is sum. Default
is true.
id Boolean - when true documents will have in id greater than the id value default is true
Read Specify replica read preferences like primary, primary preferred secondary preferred or
nearest
Safe Boolean - when true mongoose applies write concern to request that update to data base.
Default is true.
Strick Boolean - when true any attributes passed that are not parts of the schema are not saved.
Let us create a schema called students, which has a name field (string), a gpa field (number) and a
marks field (array of
numbers).
marks: [ Number] },
b{
collection: ‘students’
3);
Adding Index to a Schema
Indices can be added to a field that is frequently used to speed up execution time of queries. We can add an
index to a
schema object when defining the schema or we can use the index command.
Ww TechKnowledge
Publications
WF Web X.0 (MU)
4-17 MongoDB and Building REST API using MongoDB
Let s have a look at bot h:
Aeron
Fi re
Y eye PRT yee sen
‘Schema ( t
varmyschema = new
Pte TRY TSE RT
Am gy me eNNr mers
CS an ete
index:
1}
})
]/ OR ee
: i sei
var myschema = new Schema ( { a e ede
SP
pa
‘name: String
yi :
hema erent
To get the list of all indexed fields, we can use the method schema.indexes( )
Implementing Unique Flelds
we can us e the
For validation that includes specifying that the value of some field must always be unique in the collection,
“unin ” property in the Schema definition.
d schema.requiredPaths()
To get the list of all required fields, we can use the metho
Adding Methods to the Schema
available to the Document objects within it. They can
In Mongoose, we can add methods to the Schema object that become
ty
object by assigning a function to the Schema.methods proper
now calle these methods. Methods are added to the Schema
of the Schema object.
nt object and this Document object is accessed
The function is just a basic JavaScript function that belongs to the Docume
using the “this“ keyword.
to provide the full name:
The example below ts a function that will combine the first and bast names
Es SRAM ITNT SRST
L ATE fy
PSE Un eos seo TARTS a
‘var myschema =new Sche ema t
WF lecklaowiedys
Peplicacions
~
W Web X.0 (MU) 4-18 MongoDB and Building REST API using MongoDB
=
first: String,
last: String
});
‘schema.methods.fullName = function ()
{
return this.first + "" + this.last;
3
Mongoose Validators
Mongoose gives us some excellent builtin Schema validators and properties that we will now discover in this section.
Validators are used to validate the values provided before they are committed to the database.
Table 4.3.2
Property | Description see irke
match Regular Expression - it creates a validator that examines the provided value with the expression.
enum Array - it creates a validator to test if the provided value is present in the array.
minlength Number - it creates a validator to check if the value length is less than the provided number in the
property.
maxlength Number - it creates a validator to check if the value length is greater than the provided number in the
property.
ee true,
“Uyuppercase: true,
" maxLength: 20
Property’ | Description ia) ERR Paige eres oat cen cer rea oe pode aia
min Number - it creates a validator to check if the value is greater than the provided minimum in the
property. |
max Number - it creates a validator to check if the value is less than the provided maximum in the
property.
s ——
W Tech Knowledge
Pubticacioans
WF Web X.0 (MU) 4-19 MongoDB and Building REST API using MongoDB_
— ; ve
myname: { 2
type: String,
_ required: true,
“uppercase: true,
. trim: true,
7 minLength: [10, 'Your name fs far too short I!'],..-5 3
"-.maxLength: [20, ‘Your name is far too long!!']. ---
‘ = :
email:{
type: String,
required: true,
uppercase; true
type: Number,
peanlres [true, ‘Enter your mobile number please: "
eo ww ’
We have not only used validators here, but also thrown alerts if the validation fails. As you see in theeuminkength aand
maxLength properties, if the validation is not a match, an alert is displayed to the user.
The last statement: the model () function is a part of the Mongoose model. The function uses the syntax - model ( name, ‘
[schema] ). The first parameter is a string that is used to find the model and the second parameter is the Schema object.
Tech
Publications
Wr Web X.0 (MU) MongoDB and Building REST AP] using MongoDB
4-20 ee
We will start with understanding the rules of the REST API before evaluating API patterns and the actual CRUD tasks. As we
some node.Js programming.
move forward, we will learn a whole lot more about Mongoose and
REST stands for REpresentational State Transfer, an architectural style which Is stateless, meaning it has no idea of any
current user or their history of interactions.
each other.
API stands for Application Program Interface, which allows applications to “talk” or Interact with
REST APIs have
The REST AP] is the stateless interface to the database and allows a far for applications to work on the data.
support and doing
a set of standards. They are not mandatory but are highly recommended. It is always best to have online
it the right way ensures that if you are stuck, there is always help available.
an HTTP response.
The REST API takes an incoming HTTP request, performs {ts processing and always sends back
Fig. 4.4.1
Request URLs for a REST API have a simple standard. Following this standard will make your API easy to maintain in case of
issues.
Think about the collections in your database. You may have a set of URLs for each collection and for the subdocuments
within the collection. Each URL will have the same base path and then a bunch of other parameters.
Within these URLs, you want to cover and maintain a number of actions (usually CRUD). The common actions you’d want to
cover are the creation of new items, reading one ora list of items, updating an item or deleting an item.
From the URLs above, you will see that multiple jobs can have the same URL. On a specific location, to read, update or
delete, they have the same parameter (123location). How is this possible? The answer lies in the request methods.
OF Techineniedye
a
Publications
———
W Web X.0 (MU) 4-21 MongoDB and Building REST API using MongoDB
eS
4.4.2(B) Request Methods
HTTP requests can have different methods that notify the server of what action needs to be taken. The most widely used
one is the GET request, used to enter the URL from the address bar in the browser. Another Is the POST, used to submit
data. Let’s look at the methods that use the API and their most common use cases.
Table 4.4.1
RequestMethod, | Use ~*~ Response
POST To create data In the database The new data object created
GET To read data from the database Data object that answered the request
The first column you see is that a different method is used for each of the CRUD operations. A well designed API should have
as the same URL for different actions. Here, it’s the method that tells the server what to do.
Let us again look at the request URLs. Below, you saw earlier that the URLs are the same for different actions. These actions
are mapped to different request methods shown above and that’s how the server knows what to do.
A good API does not leave you hanging. If you go in for a handshake and the other person refuses to acknowledge it, that’s
_ not a good colleague. If you make a request, a good, well-designed API will always respond.
Fig. 4.4.2
Standardizing the API response is just as important as the API request format. The response has two parts - the returned
: _data and the HTTP status codes. To move forward after the user gets the API response, they need the Information gleaned
from both parts of the response.
VF Technomtodge
Publications
API using Mongopg
4-22 MongoDB and Building REST
WF web X.0 (MU)
and JSON
are XMLa better because they
It is important that the API returns d ata XML formats
in a consistent format and the typical1 data and is usually format for faster
tecture. JSON Is more compact tha
naturally fit in with the MEAN stack archi
responses.
The response will have one of the three things:
o Error data, or
o =Anull response
status codes. The mos t famous
one that we all know
The other thing a good, well-desig ned API should send back are HTTP
be found by the server.
is “404” - Page Not Found. This happens when the server has been requested for a page that can't
w back like “400” -
there are many more the API can thro
404 may be the most prevalent code kno wn on the internet, but
- Internal Server Error.
Bad Request or “401” - User Not Authorized (to make the request) or “500”
A list of such known codes :
o. 200: Successful Request
o 201: Successful Request after Create
o 403: Forbidden
o 404: Not Found
o 410: Gone, existed earlier but no longer
Understanding API patterns is all about keeping score of things that make an API easy to design, understand, build and
maintain.
W TochKnomtedg®
Pubticaclons
Ww Web X.0 (MU) 4-23 MongoDB and Building REST API using MongoDB
ee
When the API is being designed, we want to make use of the HTTP methods to showcase the main reason for any call. It is
because of this that we do not want to use POST only to retrieve data. The same way, you do not want to use GET to create
or delete any data. The use case of the call should determine what is to be used. Many other factors will also make this
decision for you:
1. GET requests may be cached
GET requests can be called any number of times to get the same result
wWoN
The URLs describe resources and the HTTP verbs describe what actions can be performed. So, the URLs must always
contain nouns and never verbs. The nouns will describe the domain model and always pay attention to the below points:
1. The nouns should not be unnecessarily long or complicated.
If nouns are two different words, separate them with a hyphen.
won
To access specific resources, add the identifier in the path itself and not the query.
For ex: use “/phone/numberlist/9819767506” instead of “/phone/numberlist?n0=9819767506"
6. Try to use nouns in plurals to take care of any added resources in the future.
7, Avoid more than two levels of nesting to ensure enforcement of best-practice API natienns
8. URLs should not give away the APIs implementation.
Sb}
‘4.6. CRUD
“CRUD is a very common acronym that comes from database management. Each letter in CRUD is a different type of action -
Create, Read, Update and Delete. If compared to relational databases, they are the equivalent of Insert, Select, Update and
Delete.
Every URL points to a set of data and the data can be accessed with different HTTP verbs like GET, POST, PUT and DELETE.
How do you decide whether to use CRUD or not for your API? Take your resource (file/document/etc) and put it in this
sentence: “Using this API, | want users to create, read, update and delete x”, where x is the resource. If the sentence fits your
purpose, then CRUD is a good option for your API.
Let us look at the HTTP verbs that are at the core of CRUD:
4.6.1: POST
POST is the verb used to create new data (resources). It can create a parent resource or even a subordinate resource within
a parent resource. POST can assign a new ID (Uniform Resource Identifier) to the newly added resource.
ey Tech Knowledge
Publicacions
Wr web Xo (MU) 4-24 MongoDB and Building REST API using Mongopp
a
If a resource gets created successfully, the HTTP status 201 Js returned to signify success and a location header with a link
to the resource newly created.
The POST method {s neither safe nor idempotent. Not being idempotent means that every time POST Is run, the same
response Is not guaranteed. Multiple calls will result in duplicates.
Examples :
e POST http://www.abc.com/employees
° POST http://www,abc.com/employees/tushar/names
46.2 GET
The GET method, as we will now learn about, Is used to read or retrieve a resource. If it works error-free, {t returns an XML
or a JSON representation of the data and an HTTP status code 200, which means “OK”. If the call results in an error, it
returns the status code 404 which stands for "Not Found” or 400, which means “Bad Request”.
GET requests are used only to read data and never to change it. When used this way, they are considered to be very safe
since there Is no risk of modification or corruption to data. Calllng GET 1000 times is the same as calling it once, as long as
nothing changes between the calls. And so, GET is considered idempotent. Each request will return the same value as if they
come from the same request.
Examples :
e GET http://www.abc.com/employees/tushar
¢ GET http://www.abc.com/employees/tushar/names
46.3 PUT
This HTTP method is used for updating resource values. The request will contain the new value for the original resource to
be updated.
PUT can however, create a resource on a limited basis. This happens when the identifier is chosen by the client instead of
the server. This means that the request contains an identifier that doesn’t exist. Because of this confusion, this certain way
of using PUT should be avoided as far as possible.
If the PUT request goes through successfully, status code 200 (Successful Request) is returned. If there
is no content to be
returned, then a code 204 (Successful Request with no Content Returned) is sent back.
The PUT method Is not a safe operation. This is because it makes updates to the data and
thus the state of the server side.
The PUT request however, is idempotent. If you make the same PUT call again to create
or update a resource, the resource
is still there on the server side and it still has the same state, so there is no change.
But if you increment or decrement a
counter using PUT, the call won’t be Idempotent.
Examples :
° — PUT http://www.abc.com/employees/tushar
© PUT http://www.abc.com/employees/tushar/names/suraj
4.6.4 DELETE
This is a simple HTTP method to understand. It Is used to delete a resource
identifier by the identifier.
If a resource has been deleted successfully as a result of the DELETE operatio
n, the HTTP status code 200 (OK) is returned
with the response body If needed. The response body may have the new represe
ntation of the data after deletion of the
requested resource, but we avoid sending a response back because it could take up too much
bandwidth. The status code
204 (Successful Request with no Content Returned) can also be returned
If there is nothing to return.
Tech!
Pabdlicacions
WF Web X.0 (MU) 4-25 MongoDB and Building REST API using MongoDB
SSS SSS
DELETE requests are idempotent because once a resource has been deleted, It has been deleted and cannot be undone.
Calling the same DELETE request on the same resource over and over again will not provide a different response. However,
in special cases, if the DELETE request Is used to decrement some counter to check the number of resources left after the
current call, then the request is no longer idempotent because the counter value goes down with each call. Using DELETE
for such work is not recommended.
There is a caveat to the idempotence of DELETE however. If a resource has been deleted by one DELETE request, a second
request would return 404 status, which means “Not Found”.
This leads some people to say that the responses are different and this makes DELETE non-idempotent. However, the state
of the resource in question stays the same (deleted), and thus, It can be called idempotent.
Examples :
ee
e DELETE http://www.abc.com/employees/tushar
eee
e DELETE http://www.abc.com/employees/tushar/names
Any project that runs with Express as a Web Application will eventually come to require a database. Initially, one may make
do with some sample data where data can be manipulated without a database, but for scaling an application, at some point,
a database will have to be created.
In this section, we will discuss connecting an Express application to MongoDB using Mongoose. Mongoose can be
downloaded and installed using easily available download guides online, after which this section can be started.
MongoDB With Mongoose In Express Installation
To connect Express applications to MongoDB, we will make use of an ORM to seamlessly convert data from the database to
aJS application without the need of any SQL.
What is ORM? ORM is an acronym for Object Related Mapping, which is a technique used by coders to convert information
between incompatible data types. ORMs basically just mimic a database to the programmer's preference, so that they can
operate using their own preferred language without using the database’s querying language/ The flipside to doing this is
additional code abstraction, which is why many people don’t like it. But if you have complex querying needs and don’t know
the language, this becomes essential.
Here, Mongoose will be the ORM. Mongoose gives us an easy-to-use API to deal with the MongoDB all the way to execution
ill therefore, first install Mongoose using the command line interface of the node.js application.
eu Wu ac art ee aed
Fig. 4.7.1
User and Message above are the entities in our database. They both have their own fields and are joined by a relationship. In
your application, the src/models/ folder will contain all the files for the model.
Every model has a schema that defines for the programmer the fields and the relationships. Let us say that we have two
models here in the src/models/ folder with the file name model_name,js
The firstis
i the User Model with the pam late ha js
import mongoose from’ mongoose’; ; f
“String,
nique: true,
Tequired: true,
ee MEow Taine
Sot CEAeamdAER aes NSP RELL
RE,Te eat
egoere witha
eb ed
et
YF lechtnwwiodge
Poebticacions
¥ Web X.0 (MU) 4-27 MongoDB and P\ ilding REST API using MongoDB
{
username: {
type: _— String,
| unique: true,
} required: true,
| h
}
| { timestamps ; true },
}
});
_if(! requestingUser ) {
_.| -requestingUser = await this.findOne({ emailAddress: login });
eeporrsdefault User; ie :
The © message model. will te very silat. We will not add any custom niettiods and the fields will be very straightforward.
userMessageSchema);
{ const userMessage = : mongoose. model('User’s Message’,
‘export ‘default userMessage;.
WwW TechKnowledge
Y Pubticacians
_,
WF Web X.0 (MU) 4-28 MongoDB and Building REST API using Mongopp
==
ob
user: { type : mongoose.Schema.Types.Objectld, ref: 'User’ },
i}
_{ timestamps: true },
pi
‘const userMessage == mongooseemodel( Message, userMessageSchema): =
export default userMessage;_ hea ae
Let's say a user was deleted. We want to delete all of the messages of this user. To do this, we extend a schema with what is
called a hook. We add a hook to the schema and remove all messages of a deleted user.
oa)
import mongoose from’ mongoose’ Seer ae
_username:“hy
;2
© { timestamps: true}, -
Dee
userSchema. statics.findByLogin= async function (login) {
let requestingUser = await this.findOne{ {
‘username: login,
Fa
bre
f
“if( ! requestingUser ) {
f ;
k
Peer
I awaltthisfindOne(( enemail; login Mi esas ays
Tech!
Pablicacions
WF Web X.0 (MU) 4-29 MongoDB and Building REST API using MongoDB
return requestingUser ;
}
‘userMessageSchema.pre('remove’, function(next) {
| this.model(‘User’s Message').deleteMany( { requestingUser : this._id }, next);
} esas
‘const requestingUser= mongoose.model(‘User’ eae aes
A connection function is also passed to the database with a mandatory URL parameter. We can use the environment
variable over here. You will see the database URL on the command line when you start MongoDB.
Tech Knowledge
Publications
WF Web X.0 (MU) 4-30 MongoDB and Building REST API using MongoDB
That's all! The database models have been defined for the Express application and to connect to the MongoDB when the
application starts.
The API is the most important part of the application and must be thoroughly tested to determine functional and non-
functional performance. To avoid any issues at the end of the project, we test early to ensure that the API endpoints are
Stable, safe and display expected behavior.
Functional testing is aimed at verifying that the request, state and response of the endpoint is working as expected as per
feature specifications.
Test HTTP Status Codes: verify if the correct status codes are being returned in response to different types of requests.
Test Response Objects: verify that the response objects in the JSON body are all correct and appear as expected. This
involves the name & value paris, field names, error responses and so on.
Test Response Headers: verify the HTTP server headers to ensure that security and protocol level requirements are being
met.
Test Happy Paths: verify that the API responses are correct for valid requests. This means checking the response for
correctness.
Negative Testing: verify that the endpoint is handling invlid scenarios the right way. The input could be valid, but not
acceptable, like repeat email addresses.
Destructive Testing: try to break the API and check how it reacts. Send a large amount of data or upload a massive file or
work on a supremely slow internet connection to see what happens.
Combine API with UI Testing: verify if the UI can handle all kinds of unusual responses received from unusual requests.
Test Security and Authorization: verify role-based accesses, data leaks and other security protocols to ensure that they
are working as intended.
Non-Functional testing of an API endpoint focuses on the speed, stability and scalability of the AP]. Benchmarks like
response time, CPU usage, etc. are measured against.
Load testing is used to measure how well the API works when a massive number of API requests hit the server together.
Will the API be able to process all of them simultaneously? Or will it crash and burn? Will some of those requests get
satisfied and the rest be thrown out? Load testing answers all of these questions before they become a reality, The following
are its advantages:
Wm
a
WF Web X.0 (MU) 4-31 MongoDB and Building REST API using MongoDB
Performance-ready API : load testing will give you the needed control over website performance under extreme traffic
conditions to ensure it can handle them when the time comes.
Evaluate Specific Servers : load testing can direct the load to specific servers to see if each server in the network is
working as expected and none of them is becoming a bottleneck.
Cost and Time Effectiveness : any identified issue in load testing and save performance and maintenance efforts in the
long run. And since load testing is not resource intensive, it gives you more bang for your buck!
For basic MongoDB commands that may come in handy during lab work, Please visit:.
Review Questions.
Briefly explain the essential MongoDB features. (5 Marks)
_ Differentiate between MongoDB and RDBMS. State 5 MongoDB data types (10 Marks)
Write a sample MongoDB document with no explanation and self-explanatory variable names that uses one array,
textual information, numeric information and a nested block. Create your own example. (10 Marks)
Q.4 — Whatare the built-in roles in MongoDB for access privileges? a! Es (5 Marks)
Q. 5. . What are the pros and cons of MongoDB? How do _MongoDB and RDBMS differ? (10 Marks)
Q.6 What does REST stand for? Explain REST API with a basic flow diagram. (10 Marks)
Q.7 Explain the following: a) Request URLs in REST; b) Request Methods in REST. (10 Marks)
Q.8 -.. What are response and status codes? What are the three things they can have? List a few examples of status
codes. (10 Marks)
Q.9 Whatare some best practices for API URLs? (5 Marks)
Introduction, Flask Environment Sn App Pou, URL Buleng, Flask HTTP Methods, Flask Request Object, Flask
Flask is a lightweight, micro web framework which provides programmers with the libraries to build and maintain web
applications in Python. It is based on the WSGI (Web Server Gateway Interface) toolkit. Flask also makes use of a web
template engine that makes use of data to render dynamic web pages.
y So what is WSGI? The Web Server Gateway Interface is a standard for Python application development which is the
_ universal specification for interfacing between the web server and the application.
What is a Web Framework? A web application framework or a web framework Is a collection of libraries and modules
within a programming language that allow programmers to write applications without having to take care of intricacies like
protocol handling, security management, threading, etc. Flask is one such web application framework. Flask is a Python
module that allows us to create web applications with relative ease. Flask has a small and easily extensible core: it does not
have an ORM (Object Relational Manager) or any such complicated features.
Another such framework is Django, but unlike Django, Flask is very “Pythonic” and thus, has a very shallow learning curve.
¢ nbe written: with afew lines of code.
Asimple “Hello World’ program can
WF web x.0 (MU) 5-2 Flask
<=
Flask js also very explicit and easy to read, Django Is not part of the syllabus, but It Is deemed important In the syllabus to
understand how Flask is different from Django. Flask was basically created a few years after Django when programmers
started asking for more flexibility than Django was willing to provide. Django doesn’t allow for as. much
alteration to ity
modules as Flask does,
Table 5.1.1
- Sr.No. Flask Django
1 Suitable for single application development More suitable for large scale application
development
2 Uses WSGI (Web Server Gateway Interface) for | Full stack development framework that
less structured implementation . works off of the Model-View-Controller
paradigm
And the above reasons are why the syllabus covers Flask in some detail but not Django.
Python 2. 7 or higher isaprerequisite to installing Flask on your system, The first step is to choose and install your Python
version. How you install Python depends on your Operating system. For Windows, the simplest way is to install it using the
official installer from the Python Software Foundation. Python x86 (32-bit version) is usually the better choice here because
it has better compatibility with third- -party packages. Since we'll be importing Flask, Flask isi basically
that third-party
package.
The next step is having a text editor ready to write code in. If you already have one,that’ s great and
if Not, here’s a few
options to consider from: Sublime Text, Pycharm, Virtual Studio Code and Vim.
Installing the virtual environment is the next step in the process. Before you begin
with any Python project, you will need to
make a virtual environment for it. Virtual environments or “virtualenv” separate Python’s
dependencies from the actual
operating system and ensure that any changes you make don’t break some
part of the OS. If you have Python 3.3 or above,
you won't have to install anything more - the standard library provides virtualen
v under a module named “venv’”. If not, you
can install it sionthe command given below,
Ww TechKnemledge
Publications
BF Web X.0 (MU
== 5-3 Flask
i fa pase ate
teeWesAX tanene Pipe
KN ei lulcte bare ettctetaee Peele
Once the installation is done, we can pick up a simple code from the Flask website given below and run it to check if all is
pores as expected:
p = Flask (_name_)
you now open the localhost in your browser, you will see the “Hello World !” response over there. On my machine, the link
for localhost is “http://localhost:5200”, but for most machines, it is “http://localhost:5000”. Try both to see what works and
use that.
We will build a very basic Python website using the Flask framework in this section. We can work on any text editor for this
tutorial. Write the following code and save the file as basic_scriptpy
Ww Tech Knowledge
Publications
Wr web x.0 (MU) 5.4 Flask
from flask ae Ess
yee c.
SANE ly gated ¢ j
rf ‘ Hye i ' 4
@app route) oa
re home():
rr
F return "Weleomes to so case Tutorial”;
Execute this file on the command line and the result looks like this on the Web Page:
This is confusing, yes, but it will become clear as you move through this chapter and understand Flask better. In the above
code, to build a Python application, we need to import the Flask module and create an object of it. We pass the name of the
current module (__name__) as a parameter to the Flask constructor. The route ( ) method defines the URL mapping of the
function with the following syntax:
Gpproute
ise { rule Se ON
le, options:) wus;
Rule : represents the URL binding with the function.
Options: represents the parameters that are associated with the rule object above.
The “/” URL is bound to the main function and it returns the server's response. Here, the output is a string to be printed on
the browser. Lastly, the run method of Flask runs the application on the local server.
Table 5.3.1
UF ledinceletes
Publications
a
WF Web X.0 (MU) 5-5 Flask
eS
inh en fra ven ae off with understanding what It means to serve required content at any URL. Routes are the
URL pa pplication like say “tusharapplication.com/home" or “tusharapplication.com/about”. View, as we have
learned in earlier chapters already, stands for the content that must be provided by these URLs and this could be a
webpage, some string, an API response, a file, or anything else.
A simple application in Flask to display "Hello world" shows a route that Is listening at the root of the application and
executing a view function: “home i ):
pats EEA RTA
YE
@app.route (" /") isa Python “decorator” which is used by the web framework Flask to assign a URL in the application to a
domain
function. This decorator is directing our @app (application) that if a visitor to our application hits the home
(tusharapplication.com) at the .route (), the home( ) function must be executed. Decorators are basically just logic that
“wraps” around functions.
as a
Flask even allows programmers to add variables to the URL. Programmers can reuse these variables by utilizing them
parameter in the View.
Assuming that I already have a function ready at the URL which returns my name (Tushar) as a response, the following
result will be printed on the browser:
Hello, Tushar
data type.
The URL can be used to display variables and a converter can be used to convert the variable into the required
Let’s have a look at the following example:
Fe siey pacreuaiger
ear ae pe
oat fask cimport Flask 0)
Uf Techinewiedge
Publications
BF Web X.0 (MU) 5-6 Flask
@app.route ('/home/<int:myage>' )
def home ( myage ):
return" My Age is %d" Ymyage ;
if_name_ =="_main_":
app.run(debug = True)
The output is the variable converted and displayed as an integer.
My Age is 50
The following are the converters available to us for use. They can be used to convert the default variable data type, which Is
string into the needed data type.
Applications these days are not so static. What we have seen so far is only status rote creation. A dynamic URL with a
variable can be used for dynamic routing. The variable influences the output from the URL. Consider an applicacion for
social media users that has user profiles. You want to show a user's profile based on their unique ID and if you have
thousands of users, thousands of static URLs may not be the best idea. How fast would you scale? So, we create a route for
each user using variables in the URL.
The dynamic parts of the URL will be marked using a < variable_name >. This will then be passed on as an argument to the
view function. .
The “id” placeholder that you see in the code above will map anything that comes after the URL “/user/”. If you want to visit
the profile with user 123, this is the response you'll get:
This function accepts the endpoint and as output, returns the URL as a string. The endpoint refers to the unique name the
programmer gave the URL. Usually, It’s the same name as the function.
W TechKnewledge
Pubticatlans
WF Web X.0 (MU) 5-7 Flask
Hn eee
@app.route ('/")
def index ():
return render_template (' index.html’, name =’ Tushar’ )
#..
To get back the root URL from the urlfor ( ) function, invoke the function as url_for (‘index’). The output now would be
“ye
#..
from filename import app Pia. tis
from flask import url_for 2 Rae in See ae et St Senay ara
with app.test_request_context ('/api’ ): :
_urlfor (‘index’) — i
4. ae
Let’s look at a bit more complicated Flaskk script to understand howw building URLsLs dynamically works:
@app.route( '/student')
def student ():
~ return 'The current user is a saat
@app.route ("/user/<nmame>") © 2°) 0 OF es Catert Beihai TAS ATE esi wedl fee aba ae
def user (name):
if name == ‘admin’: i Eh OB e Fe ENON Sea e EAE SISO OR uty
. _ return redirect
( url_ for (‘admin' )) .
- fname == ‘teacher’: ee viel porwr diet eee ig fe ret as
hi
~~ tetutn red(url
ire ct n
for ('stude :
at
The code above is a simulation of a very simple library management system. It accepts three kinds of aie admins,
teachers and students. A function “user ( )” recognizes the kind of user and redirects them to the exact function which
contains the implementation for that user.
If you the the user is localhost:5200 and you call “http://localhost:5200/user/admin”, the word “admin” would be value of
the variable “name” in the URL, you would be redirected to “http://localhost:5200/admin” and the output on the browser
would now be:
Hypertext Transfer Protocol or HTTP is the base from which all other transfer protocols rise up on the world wide web.
Flask, like all other frameworks, provides several HTTP methods for data transfer.
The supported HTTP methods in Flask are as shown in Table 5.6.1.
GET Most common method used to send unencrypted data to the server
POST Used to send form data to server. Server does not cache data received via this method
By default, all requests in Flask are handled by the GET () method. If you want to utilize another, you must specify it.
To understand how the HTTP POST method works, let us first create a form to get some kind of data from it at the client
side (using the browser) and we will then access that data on the server side using the POST method.
The following Is the code for a sample form page saved as “login_form.html”
RY ips ropes Pes settatg a ANE
———e
Tey Tectkacolede:
Publications
Wr web X.0 (MU)
tr> <td> Username </tds ‘
<td> <input type= "text" name ="username”>"5 </td> ae
<tr> <td> Password </td> yee “|
bes <td> <input type= "password" name= “password"> </td> </tr> : She ae
<tr> < <td> <input type= Lup >.</td> </tr> el
</table> Pomc
+ </form> : |
Username | tushar
Password | seseeee
Now, we'llmakem use of the data from this form in the next python file saved as “learning postpy”
Once you start the server by running the Flask script and then open the HTML page to run it, clicking the “Submit” button
now will generate for you the following text:
We can look at the same example again to understand the HTTP GET method. There are just a few changes in the data
retrieval code on the server side. The following is the code for the sample form page as was shown above saved as
“login_form.html”
YF lechtnewiodge
Publications
¥F Web X.0 (MU) 5-10 Flask
<html>
' <body>
<form action = "http://localhost:5200/login” method = "GET">
<table>
<tr> <td> Username </td>
<td> <input type = "text” name ="username"> </td> </tr>
<tr> <td> Password </td>
<td> <input type = "password" name = "password"> </td> </tr>
<tr> <td> <input type = "submit"> </td> </tr> . .
</table>
_ </form>
</body> 3 4
Notice the different HTTP method used here. Keeping that aside, it'll generate the same form as the earlier one.
Username | tushar
Password | ssesess
Submit
Now, we create the python script and save it as “learning getpy"
if_—name__. == '_main_';
app.run ( debug= True } ni ec lo ; i OEM TAR OTT eas
Now, once the server code is run and the HTML page Is opened and the submit button is clicked, the username and
password will be verified and the following text will be generated :
W TechKnowledge
Publications
a
‘ % FS
Cran a © localhost:5200/login?username=tushar&ipagsword=agarv
|
b
username_get = request.args.get (‘username’)
“Args” in this line is a dictionary object that contains a list of all the pairs of parameters and values present in the HTML
form.
The one major difference between GET and POST Is that in POST, the data sent to the server is not shown. The URL when
you click on the submit button in POST does not show what you entered in the form while the URL in GET does show the
information. This is a very simplified example of showing you how it works.
On the client side of the architecture, a request object stores all the data that needs to be sent from the client side to the
server side. On the server side then, as we have already seen, the data can then be retrieved using HTTP methods.
Here, we will discuss in brief what the request object looks like and how it works. First, let's look at what the request
object’s most important attributes are in the Table 5.7.1.
Table §.7.1
me
From Dictionary object with key-value pairs of from parameters and values
Avgs Parsed from URL. It is the part in the URL after the question mark
Cookies Dictionary object with cookie names and values. Saved at client side to track after session
An HTML file called “customer_form.html” which has a form for the customer to enter all their information. The data that is
input here is POSTed to the /success URL that triggers the print_my_data () in the next Flask file.
An HTML file by the name “print_results.html” to output the final results onto a browser.
TechKnowledge
Publications
Wr web X.0 (MU) 5-12 Fl
=
File 1: customer. form. html
<html>
<body>
_sh4>Please fill this form for the customer I</h4>
ai zs ;
Seas
=
action = "http://localhost:5200/success" method = “POST">
|
|
~ ep>Customer Email <input type= "email" name = “customeremail" /></p>
|
: ue<p>Customer Contact Number <input type = "text" name = "customercontact” /></p>
|
|
File 2 : learning_request_object.py
OEY ESET ET EET
m flask import
|
|
|
|
|
Ree ay
pr Tecttnentedye
Publications
WW Web X.0 (MU) Baa
Flask
{% endfor %} :
| </table> e :
:
:
:
</html> ~ e
The input form looks like this:
(Cana ‘localhost
‘submit
Once the submit button is clicked and there are no errors, the output is generated as follows:
localhost
The customer has been registered with the details listed below:
Tech Knowledge
Publications
Flask
WF web xo (MU) 5-14 Ses
5.8 Flask Cookles
0
The pages we have created and seen up to this point have been quite simplistic.
THe anane reer ATT? has
and the server responds to it. Hypertext Transfer Protocol {s a stateless protocol and that means «requested eae
the same
let the server know if two requests have come in from the same user. So, the server doesn’t know if yo i q senmmendatle
page for the first or the millionth time. How then do e-commerce and other websites give you tailored rec >
based on browsing history when you visit after the first time? The answer here lies with cookies.
What is a cookie? A cookie is essentially data about the user/requestor which the server maintains on the client machine.
How does it work ?
Syria: :
— yee popeessrcomsermvenn
The cookies are set to the Request object using the setCookie ( ) function on the Request object. The response object is
created using the make_response () function in the View function.
We can read the cookies using the get 0 function of the cookies artribiite which As associated with the Request object.
‘request.cookies, get (
We will now see a simple example below.
\oapproute(’ /cookie’ ) i
‘def cookie ():
Ww Tech Knowledge
Pudlications
return res
if_name_, == '_main_':
The script above will set up a cookie on the local machine (client) with the name “tusharCookie” and the content
“pittandyork” for the localhost:5200 (my machine).
A Youand Google
1
— & localhost locally stored data Remove Ail
6 Autotil :
| wsharCookle
g Privacy end securty
. 3 i Name
@ Appearance | tusharCookte
Oe edeaee ¥ : a] ceils ;
Advanced wi
: Iocaitiont
: 2
‘secseemmeeressteoeanasinanessnyyecianrseereessssseeemesingeuenstecectuecsescatiapee
= Extensions B fi
|
Adout Chrome
c }
eo E
Let us look at a more detailed example to see how cookies in Flask work:
Example : Flask Login Application
We will create a new login application with a few different files:
An HTML file called “login_page.html” where the user is prompted to input their username and password. If the password is
“Agarwal”, the application will redirect the user to a success page (another HTML file). If not, the user will be directed to an
error page.
The controller for this application is a Flask script saved as “learning_cookies.py” which handles the application’s behavior.
The has the View functions for the different cases to be handled. The username will be stored on the client side in the
browser in the form of a cookie. If the correct password (“Agarwal”) is entered, the application stores the username as a
cookie and then reads it later on to display a message on the browser.
File 1: login_page.html
Se
"title> Login Page </title> Reset ott
3
Stine Re gag
ney TechKnewledge
Publications
We web xo ony 5-16
Sart ri
action
Pare nie
= Se
eae
toy [iibcess >
. '
ie
re
tory
WY leaioweeors
SE Web X.0 (MU) 5-19
Flask
else:
} return redirect ( url_for ('error' ))
@app.route ('/viewprofile' )
def profile ():
username = request.cookies.get (' username' )
resp = make_response ( render_template (' profi le_pa
ge.html ', name = username ))
7 return resp
if_name_=="_main_":
app.run(debug = True)
The code above handles both scenarios: when the password is incorrec
t and an error message needs to be displayed and
when the password is correct and a success Page must be displayed on the browser with information from
the cookie.
File 3: success_page.html
File 4 : profile_page.html
This is the page you'll be redirected to if you click on the profile link in the success scenario.
<html>
<head>
i <title> User Profile </title>
</head>
<body>
<h2> This profile belongs to {{name}} </h2>
</body>
</html>
To start the server, we execute the python script first using the command “python login_page.py” and then go to
“localhost:5200” (for my machine, yours may be different) on the browser as given in the next snapshot. The login page will
Tech Knowledge
Publications
BF web X.0 (MU) 5-18 Flask
ey) ove oe
Username | 7tusharagarwal
Password | +++ _|
| Submit |
Let’s assume that the right credentials were filled in and are a match. This is what you'll see next when you click on
“Submit”: _
When you click on the link “View User Profile At This Link”, youl see the next page:
How do you explicitly delete cookies ? We call the set_cookie ( ) method with the name and value of the cookie and set a
max_age parameter inside it to “0”. Let’s look at the code to delete the cookie we created earlier:
Han
@app.route (‘ /delete-cookie/ ')
def delete_cookie():
result = make_response("Cookie Deletion Successful !!")
result.set_cookie(‘tusharCookie’, 'pittandyork', max_age=0)
return res
#..,
1. Cookies are not a secure way to store data : The data is visible to anyone, so using it to store any sensitive data or Pll
(personally identifiable information) is not advisable.
2. Cookies can be easily disabled ; Most browsers today give their users the option to simply disable cookies. If they are
disabled, the client gets no warnings or errors and any cookie sent by the server is simply discarded. Writing a
JavaScript program to force it is possible, but is often not liked by the users. Who likes those pesky pop ups, right?
wy TechKnawledge
Publications
>
3. Data storage Issues : Cookies can store only up to 4 KB of data, The browser can also impose a limit on how many
i cookies a server (website) can send. This limits how much cookies can achieve,
Flask has an easy way to handle uploading any files. It only needs an HTML form where the programmer must set the
enctype attribute to “multipart/form-data”, This allows posting the file to a URL and the URL handler can then get the file
witha “request files[ ]" object and save said file to the required
directory.
Every file that is uploaded is saved first to a temporary location on the server before being diverted to its real location /
directory.
We can define the default path for the upload folder and the maximum size of the file that can be uploaded in the
configuration settings for the Flask object.
Itis possible to define the path of default upload folder and maximum sizeof uploaded file in config settings of Flask object.
app.config |‘ UPLOAD_FOLDER ’]
// This defines the path
app.config [‘ MAX_CONTENT_PATH ’]
__// This defines the max size of the file
Let's understand the concept in more detail by looking first at an HTML file titled “uploadingfiles.html” :
<html>
<body>
& <form action = "http://localhost:5200/uploadingfiles" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = “submit"/>
</form>
</body>
</html>
‘uploadingfiles.html’ here has a file chooser button and a submit button. In the output below, you'll see an input type HTML
option (file chooser) to upload a file, to which I’ve attached my resume. If you click the “Submit” button after choosing a file,
the HTML form’s HTTP POST method will call the ‘ /upload_file ' URL which will be managed in the Flask code we will soon
see.
We will now see the Flask code that has an ‘ /upload ‘ rule which displays the “uploadingfile.html” page above and another ‘
/upload-file’ rule which invoked an upload function () to handle the process after the submit button has been clicked.
W Tech Knawledga
Publications
Flask
SF webxo (MU) 5-20 ae
from flask import Flask, render_template, request
import secure_filename
if_name_ == '_main_':
app.run (debug = True)
If the file has been uploaded successfully, the function will return an HTML page titled “successful_message.html” which will
deliver the message to the user on the browser screen. The code for that final page is as follows:
<html>
<head>
<title>Successful Message</title>
</head>
<body>
<p> The attached file has been uploaded successfully! </p>
<p> File Name: { { name } } </p>
</body>
</html>
W Tech Knowledge
ee
Publications
Te Oe
EF Web X.0 (MU) 5-21 Flask
Review Questions
Q.1 Write a brief on Flask and how it differs from Django. (10 Marks)
Q.2 Explain the following: (10 Marks)
a) App Routing in Flask
Q.4 Explain cookies in Flask. How are they lacking? (10 Marks)
Q.5 How many parameters does the route method have in Flask? Write one line about each parameter. How many data
types does Flask have? State them. (5 Marks)
Q.6 Write a small program in Flask to send Username and Password from an HTML page to flask server using GET or
POST. Avoid writing incidental code. (10 Marks)
Q.7 Whatis the Flask Request Object? Explain in brief. (10 marks)
Q.8 Whatis Flask URL Building? (5 marks)
000
Rich Internet Application
) Syllabus
HTTP Request,
AJAX : Introduction and Working, Developing RIA using AJAX Techniques : CSS, HTML, DOM, XML
JavaScript, PHP, AJAX as REST Client Introduction to Open Source Frameworks and CMS for RIA: Django, Drupal,
Joomla
Process
returned data |.
|
Update
Page
Fig. 6.1.1
AJAX uses certain well-known internet standards to accomplish all of this ;
XMLHTTP Request Object to deliver and receive data from the server,
PF
it.
JavaScript/ Document Object Model ( DOM ) to display information and interact with
WN
The code below will make use of AJAX on the front end with HTML and a PHP function in the back end to show you how
AJAX dynamically updates web pages ;
W Tech Knowledge
Publications
_
</body>
</html>
File 2 : PHP Server Program
This server contains recommendations
<?php
// Anarray of names
$namesArray [] =" Arpit”;
$namesArray [] = "Babita";
$namesArray [] =" Chakra";
$namesArray [] =" Dhruv";
$namesArray [] =" Ekshit";
$namesArray [] =" Falguni";
$namesArray [] =" Gaurav";
$namesArray [] =" Hardik” ;
$q = $.REQUEST ["q"];
$userInput ="";
if ($q !=="") {
$q = strtolower ($q);
$len = strlen ( $q);
foreach ( $namesArray as $name) {
if (stristr ($q, substr ($name, 0, $len))) {
if ($userInput =="") {
$userInput = $name;
}else {
$userInput .=", $name";
// Send back" No Name Found! " if no name was found in the array for the input
echo $userInput === "" 7" No Name Found! " ; $userInput;
I>
Please note that I have only added a few names from A to H here to keep the code short. You can add as many as you would
like,
W Tech Knowledge
Publications
YF Web X.0 (MU) 6-4 Rich Internet Application
—
This program first checks if the input field given to the user has been filled or if it is empty. If it is empty, the suggesteq
name placeholder will be cleared.
If the field is not empty and the user has entered something :
Output:
Since the array in the PHP code only has name recommendation from A to H, if you enter any character from A to H, you will
see the following:
If you change the H to A in the text box, the name recommendation will automatically change without having to reload the
page. The output will be as shown:
If you type a character other than A to H, you will see the following output:
A Rich Internet application (RIA) is a kind of Web application that is created to produce the same features
and
functionalities that are seen in regular high-powered desktop applications. RIAs conquer and divide
by splitting the
computing across the entire network by rendering the user interface and all other related work and computation
s on the
client machine, and the information manipulation and other calculations on the server machine.
W TechKaowledge
Publicacions
aeer Web X.0 (MU) 6-5 i
Rich Internet Application
An RIA normally can execute inside a Web browser and in most cases, does not need additional software installation on the
specific browsers. To ensure proper
client machine to execute flawlessly. In some cases though, RIAs may work only with
security, RIAs run the client side of the code within an isolated separate area of the client machine called a sandbox to limit
visibility to the actual data on the server,
2. Keep in tune with rising expectations of your website's user's expectations. Everyone wants the best all the time.
Amazon isn't the king of the market because of low prices, it's the king because it is fun to shop on Amazon.
3. Higher retention and loyalty rates as compared to old and slow applications.
4, Supports very computationally heavy data visualizations like dynamic charts and tables.
In this section, we want to understand the creation of a front end AJAX Client that uses HTML, CSS, DOM, XML, HTTP
Request and Response, JavaScript and PHP
Since a lot of technologies are in play here, we will start understanding them and before you know it, you will realize that a
simple application can make use of almost all of these technologies.
The AJAX client will make use of JavaScript to send HTTP requests using GET. The server (PHP) will load and access an XML
document using a user value selected from a dropdown in the client HTML page. This XML will be sorted to get an answer
based on user selection and return the HTTP response back to the client web page. CSS is just a styler for the page and can
be used or removed as needed.
Interactive communication with the server can be performed using an XML file for data transport. The next example will
show us how an XML file can be used to display data from the server on to the web pages. The server in this case is also
PHP.
When you pick an artist, their musical record will be listed here!
When you click the on the drop down list, this is what you see :
When you pick an artist, their musical record will be listed here!
W Tech Knowledge
Publications
BE@ webxo (MU) 6-6
: 1”
Rich Internet Application
—==
NAME:Prayer
SINGER:Lata Mangeshkar
COUNTRY: India
PRODUCER:Prayer Company
YEAR:1990
Let us now look at all the files needed to create this functionality.
<form>
Pick your favourite artist !!!
<select name = " music " onchange = " displayMusicalRecord ( this.value ) “>
<option value=">Choose your favourite artist to get their musical record!</option>
<option value="Taylor Swift">Taylor Swift</option>
<option value="Lata Mangeshkar">Lata Mangeshkar</option>
<option value="BTS">BTS</option>
Ww TechKnowledge
Publications
6-7 Rich Internet Application
RF Web X.0 (MU)
</select>
</form>
<br><br>
<div id =" textForUser ">
<b>
When you pick an artist, their musical record will be listed here!
</b>
</div>
</body>
</html>
The displayMusicalRecord created above does the following :
1. Creates an XML HTTP request object.
2. Creates a function that is invoked when an option is selected from the drop down list.
3. Send the request to the server. This is done using a query parameter just like the last example.
Before we look at the PHP server, let’s see what the XML file looks like which the server will load to get the musical records.
The file can have any number of records. To keep it short, I've shown you below the three records we need for the selections
above:
<LIST>
<RECORD>
<NAME>Some Love Song</NAME>
<SINGER>Taylor Swift</SINGER>
<COUNTRY>United States of America</COUNTRY>
<PRODUCER>Romantic Song Company</PRODUCER>
<YEAR>2015</YEAR>
</RECORD>
<RECORD>
<NAME>Prayer</NAME>
<SINGER>Lata Mangeshkar</SINGER>
<COUNTRY>India</COUNTRY>
<PRODUCER>Prayer Company</PRODUCER>
<YEAR>1990</YEAR>
</RECORD>
<RECORD>
<NAME>Some Hip Hop Song</NAME>
<SINGER>BTS</SINGER>
W Tech Knowledge
Publications
SE weoxo (Mur) 6-8 Rich Internet Application
—=—=—=
<COUNTRY>South Koreae/COUNTRY>
<PRODUCER>Some Pop Company</PRODUCER>
<YEAR=2020</YEAR>
</RECORD>
<RECORD>
</RECORD>
<RECORD>
</RECORD>
</LIST>
The script above has invoked a PHP server file called “getmusicalrecord.php”. The server (PHP) will load an XML document
titled “musical_records.xml" that contains information about musical records of the artists above and return that result :
<?php
$q=$_GET["q"];
for
( $x = 0; $x <= $x -> length - 1; $x++){
When the query ts sent from the client script over to the server (PHP), the following steps take place in order:
You will see that the files above cover all of the technologies outlined for the creation of a rich internet application except
css. CSS, as a styling tool, does not add any functionality and so, adding it from the beginning itself would increase the
Jength of the code and create further confusion. Assuming that you know how CSS works, this book will not be detailing and
teaching you how CSS works, but simply explain what an added CSS style block would do and make a very, very simple style
block just to showcase how CSS can be combined with the above application.
Let us take the File 1 (HTML Client page) and add a simple style block with a header ina specific color and a new paragraph
with some text. Any and all modifications to this block can be made. Tables with padding, formatting, colors, highlights and
text, forms with more complicated styling features, borders, etc. can all be added to this block.
However, the syllabus does not cover the details of CSS. It simply covers a student's understanding of how CSS can be added
| __ toan application.
_. <head>
<style>
“div{
- border: 2px green
~ padding: 4px;
yo
h1{
text-align: left
text-transform: uppercase;
color; #4DBF60;
p{
letter-spacing: 5px;
}
a{
text-decoration: none;
W TechKnowledge
Publications
WE web xo
co 6-10 Reh mernet Application |
color: #O19ACR;
)
</style>
<script>
function displayMusicalRecord ( userString ) {
if( userString ==") {
document.getElementRyld (" formOption * ).innerHTML =" ";
return;
<form>
Pick your favourite artist !!!
<select name =" music” onchange =“ displayMusicalRecord ( this.value ) ">
<option value=">Choose your favourite artist to get their musical record!</option>
<option value="Taylor Swift">Taylor Swift</option>
<option value="Lata Mangeshkar">Lata Mangeshkar</option>
<option value="BTS">BTS</option>
</select>
</form>
<br><br>
<div id =" textForUser ">
<b>
When you pick an artist, their musical record will be listed here!
</b>
</div>
</body>
</html>
Tech
Publications
/
;
SF Web X.0 (MU) 6-11 Rich Internet Application
The new output now upon selecting Lata Mangeshkar will be as shown below:
Record Finder!!
NAME:Prayer
SINGER:Lata Mangeshkar
COUNTRY: India
PRODUCER:Prayer Company
YEAR:1990
| reiterate once again that the syllabus does not cover details of CSS, just a rudimentary understanding of what CSS is and
how it can be added to the AJAX Client side and used in conjunction with other AJAX techniques.
6.4 Introduction to Open Source Frameworks and CMS for a Rich Internet Application
Under this section, we'll be studying the basics of a few different technologies that help developers create richer and more
_ dynamic web applications. The syllabus covers the basics of these technologies only and not an in-depth study, so being
able to create and run basic applications & answering fundamental questions about them is part of the syllabus, but the
nitty-gritties of these technologies are not.
A CMS or a content management system, is a tool or software that assists the users of a website in making, managing, and
updating any content on the website without having to know advanced technical know-how. Basically, you can create a
website using CMS even if you don't know the code from scratch. The CMS will handle all basic infrastructure and the
backend for a website so you can focus on what the website needs to look like,
So how is it different from a framework like Flask or Django? A framework gives us an easy way to create and deploy
applications by providing the common pieces of code and allowing software developers to modify and customize according
to their needs. Frameworks help improve code reusability, but need a basic amount of technical expertise to create from
scratch.
Table 6.4.1 : Difference between CMS and Framework
1 Can create and modify digital content seamlessly. ‘A generic set of functionality that can be modified as}
per needs.
2 | Easy to learn with little to no technical know-how. Needs more time to learn with some prerequisite
technical know-how.
W Tech Knowledge
Publications
Rich Internet Application
BF Web x.0 (MU) 6-12
Sr.No. CMs Framework
————}
ble.
|Makes the backend more flexible
Makes the frontend more Nexible by handling backend
w
with widgets,
4 | Offers less customizability as compared to raw coding, [Offers more customizability than too Is and widgets.
gets
6 | Examples are Drupal and Joomla Examples are Django and Flask
6.4.1 Django
Introduction
based on the MVT
Django is a Web Application Framework (WAF) written in Python and used to develop web applications
or Model-View-Template Model. Django has the following features :
to focus on development.
1. Quick Development ;: automatically takes care of configuration settings and allows you
request forgery, etc.
2. Secure: helps you avoid mistakes that can lead to SQL injections, cross site scripting,
3. Scalable : easy context switching makes Django great at scaling from small to large applications.
4, Feature Heavy : a large collection of libraries to handle everything from authentication to content administration and
everything in between.
To install Django, just go to the official Django website (www.djangoproject.com) and download the Django executable file.
After that, Django needs “pip” to initiate installation. “Pip” is a system that manages data packages and is used to install,
configure and manage data packages written in python. “Pip3” is the newer version, so use the latest that is compatible with
your Python version.
The installation command on the command line for my Django version is as follows :
print ( django.get_version () )
First Project
We can create a project in the /home directory using the following command:
cd tusharsProject
W Tech Knowledge
Pudticacions
SF Web X.0 (MU)
os
6-13 Rich Internet Application
To go through all the files and folders in a Dj ango project, use the tree command to see the structure. If you don't have it,
install it with this:
me aecae
Sen)
Gane») ae
FC Las9) ale
“urls.py ay
ety ee
i MEU E Se oe
o manage.py: command line utility to interact with and manage the application.
o tusharsProject: this is the module we will import. It is the actual application package.
o __ init__.py: empty file to tell Python to consider this directory as a Python package.
o settings.py: configure application settings like database connections and static linking.
o _urls.py: contains all listed URLs in the application. We write the URLs here with the corresponding action.
W Tech Knowledge
Publications
WE web x0 (MU) 6-14 Rich Internet pplication
Ap licat
—=—
TOS dat
Pi eas
yp
iia
mela i) ve
foes)
arr
ce
views , py.
Right above is the directory structure for the app. Initially, all these files are empty. Let's write some code for it to see how
execution works.
File 1: “views.py”
from django.shortcuts import render
# We make our views here in this file
from django.http import HttpResponse
def printsomething ( request) :
return HttpResponse (" <h1> Hi, my name is Tushar! </h1>" )
File 2 : “urls.py”
]
Now, we run the server with the following command
python manage.py runserver
Now, you open your port on the browser and navigate to the link “localhost:8200/printsomething /” to see the following
output:
CQ @ localhost:8200/printsomething/
The MVT in Django is a software design pattern where the model handles access to the data, the template is a presentation
layer to look after the UI and the View is used to perform business logic operations as needed and get data from the model
and render a template for the user. Control is handled by Django itself, The end user sends a request to Django, which works
as a controller to check for what is needed in the URL. If the URL maps successfully, a View is called that gets the data from
the Model and then renders the Template. Django then responds back to the user and sends the template as a response.
Request
——>| DJANGO
User Model
Success | _|
URL View a
Template
Fig. 6.4.1
Django Model
The Model in Django is a Class that hosts the fields and methods, Each Model maps to one table in the database. Each field of
a delete via
the Model's class is a column in the table. Django gives us the ability to create, interact with, retrieve, update and
the Model. Models are defined in the “models.py” file. This one file holds all needed models.
Let’s create a model called “Employee” in the “models.py” file with the following code:
Let me now create a sample View in “tusharsApp” to say “ Hi, my name is Tushar! “
File 1: “views.py”
Django supports the MVT model however, so it should Ideally be like this where “printsomething.html” is the
Template ;
With Django, HTML and Python can be split, where Python covers the Views and HTML covers the Templates. Django relies
on “render” to connect the two languages. It sends the request, the path to the Template and a dictionary of parameters that
has all the needed variables for the Model.
A variable is written between double curly braces { { variable } }. The model replaces the variable in the third parameter of
the render function with the variable sent by the View. Let’s write two simple files to see how Templates work:
File 1: “views.py”
from django.shortcuts import render
def renderFunction ( request):
today = datetime.datetime.now () . date( )
return render (request, " printsomething.htm |", {" today" : today} )
File 2 : “printsomething.html”
<html>
<body>
Hi, my name is Tushar!! <p>The date today is { { today } }. </p>
</body>
</html>
Output :
> © Q @ localhos
8200 /prinvese
t
Note from Author : This section is insufficient to teach you the details of
how Django works, but has been deemed
sufficient as per University syllabus and thus, this section will not go into further
detail and confuse you. A rudimentary
understanding of Django Is sufficient as per syllabus.
6.4.2 Drupal
Drupal is an open source CMS or Content Management System that helps programmers
organize and publish content on the
world wide web. It is built on PHP and requires an understanding of HTML and
CSS before you proceed. Both are
considered prerequisites before studying this subject as per syllabus.
W Tech Knowledge
Punticatians
ke
6-17 Rich Internet Application
BF
= Web XM)
ACMS isa piece of software that stores data of all types (text, images, audio, video, documents. etc.) and makes It available
and accessible to a website for use.
Advantages of Drupal
1. Flexible in allowing all kinds of content to be stored and used, irrespective of whether the content is structured or
unstructured,
2. Not compatible with a lot of software out there because it is relatively new.
management systems.
3. Lower performance compared to other content
Download Drupal
Step 1: Download Drupal’s latest version of the available zip files from the official website as per your computer's
specifications and run the executable file: www.drupal.org/project/drupal
fc Step 2: Drupal requires a MySQL database. Have an SQL database ready for connection. Let’s say that the username is
“root” and so is the password.
login Provide
Permissions
run code
*| DRUPAL
Database
Fig. 6.4.2
expect a response - the client side.
© Users: The actual users of Drupal who send a request and
for monitoring content,
* Administrator : Provides access and authorization by managing privileges
and complex websites,
° Drupal; The free open source CMS that works on a PHP environment to create powerful
database.
© PHP: The scripting language used to fetch data from the server, Le.
A Techtncwiedys
Pugticatiqans
Rich Internet Application
BF Web X.0 (MU) 6-18 al
* Web Server : Processes requests via HTTP and serves as the comm unication p Jatform between the client ang the
server,
* — Database: Stores all the information and allows modification, updates and deletion.
Drupal Menus
4 Backs
RSF
ES Content types
:
Manage content tyees, induding def aut status, hat pages prdmmoare
front lg come
risent settings, et
Add New mrnus To yout Zit, ee DuLetiNG MaamUs, and renee aad reorganize Met babs
i* we “
J axoramy
Manage tlggng, categorizabon, and cassHficauan of your content
Menus &
Lath mer has a cerrespseciing Biaik that 1 managed On the Boch: adenooatraton page
@ Adet ener
a pod OPERATIONS
Maas mens
bes ecA4 add
Tha Sgr phased If Weed GL emgeiy SaleE be E Rize tnd taotd BmCE ort Of thet ge, OFEF iY bog Rig inon Bar aw Mary bee
es
way TechKnowledge
FF eicatiors
A
SF Web X.0 (MU) a Rich Internet Application
Morree e A dreuncey
& Admuncetr ee» Uitte ee Mente Menut
Title *
Meany! huts Mra Peter then !
Oescription
Thos 18 fny fist mary oy deepal
C swe) Delete
Fill the title and description for the menu and click on “Save”. Once you click on “Save”, the following screen will be shown
to you. Now, define the path link to the new menu page. Click on “Add link” as shown below:
@ Fd tink
howe $0 etts
Pac *
netele
EM Dir ee me he inet NHL ba a Rey oe ae op Geter Pdete tee be Ue O eet page
PAck cam be en renter nes Cy pea? path ce 6h RU
Ne put foe thee uetae Bek,
eteanwe
Brene Nees thet pee Sot Onekin ee mut tx hate me pony meme
Show pr erpereed
ete ot aloort ateyar ¢ eon
Dob ton 204 ites seaed Rah Bap iRyliren, te,
Pesens fend
.
eMenat?
wecred Nhed Mined
fone nts oor ad Be vps le 04 pareit Fla Aibany Hone ened
the arene oF pi ter 9 lid god 4h Oy richdromur Beadot B Lame
Whe mgs
ee
tog tne hgsiar hele ot Ot pep kcmnd tegiey the tap
jeune Yo tm mate (0 hewses linet inat Sat
GD
W TechKnowledga
Pudlications
We Web X.0 (MU) 6-26 Rich Internet Application
Hares
© BAM iret & Dates
Memes
@ ROS ne
how on meaers
serps > nog anerei 5 cenave™ rs , - Onin :
. Bove configuration
Net Te
@ £665 manu
gerarese rr "Gee ba
THLE ( OPERATIONS
Mag mucus ber ean aia
Tha Alawe mails it what ov mimey Hnrt be Gham
Bi miaecy ter bcvic af Dt p46 ORE one top Rasgando bene ers nee
Manazecrenr : oa eat ao
Tie Mara ptone a penny Comat Oks for Adrrutweo atten fhe Boke fe Oe Ren
Thee page Broedes 4 drag-and-drop inmertace for ateqpung a block ty miegiin and lov Soekrading the onder of Dlorh6 wthin reyone See
FEA BNE IeG HNCH EIR Toe salem Fevons, bt display FODAds v1 Me Saree way, Locks are geomontd ono Herre Dass, Remember chat
rer charges wal ras be saved unl pow uch the Sure Slacds bution at the bomoin of the page CHCA the comer bunk meat to each Slack te
senfayare te tguetdn tale and wuilsdity settings
: W Tech Knowledge
Pupiicartions
BF Web X.0 (MU) 6-21 Rich Internet Application
<=
Bia citte
Block deseription *
Block bady+
REGION SETTINGS
Spennfy an which thems and regions this block i5 dosplayert.
« None - ’
Visibility settings
Pages
dee besynteg Show block on specific pages
= & Ad pages except tose kia
Content types
fear reatreted oF Only the hated pages
Roles
we femrmted
Users
Not tustoneradie
Spacily pages by cig Wien parks Erter sm path par hee Tne * cbaracue
voldcatd Ex ariote pais are Mog tor tho blog Page ant oa
Bey foe parry ea cwONa bisD
Chrgate it Vive tront page
+ ASS content
UPDATE OPTIONS
Go to “Publishing Optio ns” after that and click on “Promoted to Front Page”.
Menu settings 2
Notin menu ‘W) Published
Comment settings
Closed
Authoring information
By adrnin on 2015-09-07 16:45:46
+0530
Publishing options
Published, Promoted to frant page,
Sticky at ton of lists
Tech Knowledge
Publications
SF Web X.0 (MU) 6-23 Rich Internet Application
Available options :
o Published - makes the article live
oO Promoted to front page - attaches the article to the front page.
o Sticky at top of lists - attaches your article to the top of the front page.
Ifyou check all three options, the article will now be listed on the front page at the top:
Drupal Blogs
Blogs help get content to the site visitors. They can be public or private and can have roles depending on who is allowed to
access them.
To create one, click on “Modules” in the top ribbon of Drupal. Now, check the box that says “Blog” next to it to install the
module and then click on “Save configuration”.
Now, click on “Content” in the ribbon bar at the top again and click on “Add content” followed by “Blog entry”. You can now
add a title and the body for your blog. After that, go to “Publishing options” just like front pages and choose whether to
make it live and whether to attach it to the front page. Then, click on “Save”.
Drupal Articles
Articles help site visitors know more about the website. To create one, go to “Content” on the ribbon bar at the top and click
on “Add content”. You will see the following screen with settings and options below.
Create Article «
Hise
BA contest
Tete ©
Toos
Poth) 4 Carts
- Se puie bed Pak Gf esedy to deginte goin 4 Selene
You can add the title, any relevant tags, the body of the article, the format for it (which decides what kind of text goes in -
normal text or HTML if you want to design the text yourself) and any image if you want one. After that, go to “Publishing
options” at the bottom just like front pages and choose whether to make it live and whether to attach it to the front page.
Then, click on “Save”.
W TechKnowledge
Publications
UE Web X.0 (MU) 6-24 Rich Internet Application
==
Drupal Content Creation
When you click on “Content” in the ribbon tab at the top, you get the following choices:
Add tontent «
In Drupal, creating a basic page is just like creating any article or a blog and it equates to creating content.
You enter the title, body, text format and choose your publishing options and finally click on “Save” and create content for
your website.
First, click on “Content” in the top ribbon tab to see a list of all articles, blogs and basic pages created yet. You also have an
option to search using filters if you have created a lot of content for complicated websites.
Table 6.3.1
Click on “Edit” under “Operations” to go to the modification popup that lets you edit any part of your content or their
settings and publication options. Make your changes and click on “Save”.
First, click on “Content” in the top ribbon tab to see a list of all articles, blogs and basic pages created
yet. You also have an
option to search using filters if you have created a lot of content for complicated websites.
Table 6.4.2
Note from Author : This section is insufficient to teach you the details of how Drupal works, but has been deemed
sufficient as per University syllabus and thus, this section will not go into further detail and confuse you. A rudimentary
understanding of Drupal is sufficient as per syllabus.
6.4.3 Joomla
Joomla is an open-source, content management system that can build complex websites and online applications. It is built
on an MVC or Model-View-Controller framework. It is based on PHP and MySQL, and the templates can support HTML and
CSS, so knowledge of these as prerequisites will make understanding Joomla easier.
Advantages of Joomla
e Free and openly sourced.
e Simple to install and set up.
e Uses the What-You-See-Is-What-You-Get (WYSIWYG) Editor, so content editing is easier.
e Has almost universal browser support.
e Provides free and easy to use templates for quick deadlines.
e Can work with almost any database.
Disadvantages of Joomla
e Has internal stability and compatibility issues when multiple modules and plugins are installed and run together.
e Complex designs are difficult to make without development experience.
e Not very SEO-friendly (SEO = Search Engine Optimization).
¢ Websites made by Joomla are heavy and can take a little more time to load.
Joomla Architecture
The Fig. 6.4.3 shows the structural architecture of Joomla with all components that make up its framework. They will be
explained briefly in this section.
: Web Server
Database ft
Templates
! I I
Components Modules Playing
f ! I
JOOMLA
Fig. 6.4.3
¢ Database: Uses MySQL to store, manipulate and process data.. Images and documents cannot be stored. Also handles
administration and authorization.
¢ Joomla Framework: Collection of software libraries and packages that are all open sourced and make up the Joomla
CMS,
e Components: When a page needs to be loaded, a component is invoked to render the page's body, It has two parts: 1)
administrator components, which manage the many aspects of the component and 2) site components, which render
a page when a request is made.
W Tech Knowledge
Publications
¥F Web X.0 (MU) 6-26 Rich Internet Application
© Modules: Lightweight extensions of Joomla to extend capabilities of web page rendering. Managed by components.
* Plugin: Used to extend Joomal’s existing framework that triggers in specific events. Usually used to format the output
from components or modules,
° Templates : Used to manage the look of the web page. It is
of two types: 1) front-end templates, which manage what
the user sees, and 2) back-end templates, which manage what the administrator sees.
Web Server : It communicates with the database to get what Is needed using HTTP methods.
Joomla Installation
We will start with a server stack package called XAMPP. Install XAMPP from a iend index. and then
install the executable file just like any regular software. You can activate it by launching it after installation and starting the
server by clicking on “Start” next to “MySQL”, After you click on “Start”, the button name changes to “Stop”. I have started all
servers simultaneously here:
To install Joomla in localhost, download the zipped file from downloads.joomla.org/ and extract it and copy all files into the
“htdocs” folder available in the XAMPP directory. I've created another subdirectory inside it for better management:
Databases
16 Create database 4)
[Employed J ‘| | uti8_unicode_ci oo
Ww Tech Knowledge
Puolications
BF Web X.0 (MU) 6-27 Rich Internet Application
To get a live server ready, go to the Control Panel and then Databases > MySQL Databases section. Add the database name,
user id and password. The name will be needed later for Joomla.
On your browser, search for http://localhost or http://localhost/abc where abc {s the subdirectory inside the “htdocs”
folder.
Once you get to the Joomla web installer page, you must add your basic information to get to the next step - information like
language, site name, description, admin email, username and password, etc, After that, click the “Next” button for Database
configuration.
£S Joomla!’
Joomiat is free software released under the GNU General Fudiic License,
Main Configuration
c Username *
Enter a descrphon cf ihe overa? website —t
thal 10 De used by search engines. Set ihe usemame for your Super User
Generally, a maximum of 2)) wards is. account
best
Password *
The next page will ask for your database details like database type & name, hostname (localhost), username (root) and
password (leave blank). Once entered, will move you along to the next page for Overview where you go through all the
entered information and click on “Install”. At the end of the wizard, click on “Remove Installation Folder” to finish the
installation process.
You can click on “Open Site” at the end to be routed to your main page. Here’s mine:
Tushars_ Joomla_Application
Login Form
L Useruine
Bh assnord
)_, Remember Me
‘ W Tech Knowledge
Publications
BF wedXxo (mu) 6-28 Richich Internet
Int Application
_
Joomla Menus
, or Joomla:
Menus are essential to a website. They help you navigate the entire site. Heres the steps to create one for J
Click on “Menus” on the admin side of Joomla in a ribbon on the Control Panel and go to "Menu Manager” followed by “Add
New Menu”,
STRUCTURE
The “Add Menu” page will be displayed, where the Menu Name and Description are to be added.
Menu Details
Title *
Menu type *
Besenption
After that, click on “Save & Close”. After successful addition, you will be routed to the Menu Manager, which will show all the
content you have created, including the new Menu:
nD Aadho Meoy
Noes Tyee sotureos
C fee Mars
dorms
Ppoe .
larga
#8 -
bd
The Details tab will need you to select the item type from the following:
Articles
c ‘Coneguritin Manager
Contacts
Newsfeeds
Search
Smart Search
System Links
Tags
Userssaitiagir
Weblinks
Wrapper
Following are the kinds of Articles available. You can browse through all of them on discretion.
faticiegs
Laat RIE Cate goried free a ih tat al he Urtok Cire ore y wy BCU yey
WwW TechKnowledge
Publications
Rich Internet Application
SF Web X.0 (MU) 6-30 ==,
More terre”
mene CED oo
vee anne? mane i tees Pant vem
arerg tree Bnet
Orenans
tayeergant
te erptetin sor seer
fete
The link specified the link reference for the “Menu Item”.
Template Styles are the default or custom templates with which you design the Menu Item. The Target WIndow tells you if
the item will need a new window for display or not. The Menu location will tell Joomla where to add the item. Fill in all
other information and move to the Options tab. After selecting Menu Item Type it will generate an Options tab
automatically. Choose appropriate options as per needs. This tab will also have an option to choose the page location of the
article, any custom CSS design for it, page title, headers, etc. After all is done, click on “Save and Close”.
You can edit menu items by going to the Menu Manager, selecting the checkbox next to the Menu Item and clicking on “Edit”:
a crea ee Cann)
Tent 3 Public as
Joomla Modules
Modules are a lightweight extension of Joomla which are useful to render web pages.
To create a Module in Joomla, go to “Extensions” on the top ribbon in the taskbar and click on “Modules”.
See a aed You Joomi S om 2 -
Giz) Pood Cc = +s
weivis: Ad a Publ, ae 105
Tech Knowledge
Publications
SF Web X.0 (MU) 6-31 Rich Internet Application
Click on the green “New” button at the top left in the Joomla toolbar, which will take you toa list of all available module
types. You can select the one you need:
Articles . Categories this modite displays a tet of categnrins from one parent category
Articles - Category thes medute cesplaya a list of arieios from one or mere categories
Articles - Latest Thes module shows a kit of the most recently published and current Arncles
Articles « Most Read This motte shows a Est of thir publinhad Artictes which fave the highest number of page .
Articles - Newsflash the newsfiash Modise will dinplay a fared number of artictes from a specific category
Articles - Related Ths module displays other Articles that are refated$y the coe beng viewed. These
Banners the Banner Module displays the active Banners from the Component
Custom This module aftows you to create your own Module using a WYSIWYG editor
Language Switcher This module displays a ist of available Coment Languages (as delined andl publshed im.
Lagin thes module daplays 2 username and password logat farm. # also displays a fink 10,,
i Modules: Login
Login
ca
Ths module givpliys a useminie and passwort login torte, i aiso displays a link to rcineve
forgotien password. It user registration ts enabled (in Users > Manage > Options), another tink wit
be shown ta goabh sel-reget anon jor users.
Pre-teat
Post-teat
Tech Knowledge
Publications
WF web x0 (Mu) 6-32 Rich Internet Applicat;
pplication
=;
Fill in the mandatory details in the “Module” tab here and move forward to " “Menu Assignm ent” where y you can choose
which pages to display the Login module on from the following options:
On all pages
On|) elt id
No pages
Layout Default *
Bootstrap Size 0 -
Header Tag ha .
Header Class a
These options allow you to use HTML and CSS to customize the look and feel of the Login module. The last Module
Permissions tab lets you choose who (which roles) can and cannot see the module. Finally, you click on “Save*. Module
information can be edited the same way as Menus and Menu Items.
° Joomla Templates Joomla offers the capability to change the design of your website without having to
code. A
template is an extension that can change the view of the website. Joomla uses two kinds of templates:
° Front-End Templates: They control the look of the website - the part is seen by the users.
Most available
templates are for the front-end. They are good for basic sites. Joomla can assign different templates to different
Menu Items, Using one template for all however, makes customization easy and increases
uniformity.
o Back-End Templates: Control's the administrative tasks, seen only by the Joomla administrator. These
templates change what the admin sees, so they are most often not changed much.
A Template Manager is used to preview and edit any pre-existing or new templates in Joomla. To access the
Template
Manager, go to:
W Tech Knowtedge
Pustitcacions
BF Web X.0 (MU) 6-33 Rich Internet Application
Once you click on “Templates”, you will be taken to the Template Manager's style tab. You will see a list of all pre-installed
templates here. Beez3 is one such default, pre-installed template:
©
Site -
Teriplates | Clear |
Style
® Beez3 - Default
Message
Style saved
beez3
ES
Accessible site temptate tor Joomla! 3.x. Beez3, the HTMLS5 version.
If you click on the Templates tab on the left (under Styles), you will see the following screen:
¢
<?php
Site hy
* ®barkage Joomla
* Sauhpareage Tevplates protostar
Matters
Copyright {C4 2805 - 2019 Goer Smirce
igkts reserved 2 ar later
a & GNU General Public License version
gee LICENSE.txt
Review Questions
Q.1 What does AJAX stand for ? Give a brief explanation with the 4 standards used by AJAX. (5 Marks)
the 4
Q.2 What does AJAX stand for ? Explain how AJAX works with a flow diagram ? Give a brief explanation with
standards used by AJAX. (10 Marks)
Q.3 What does MVT stand for? Explain Django’s MVT with a diagram. (10 Marks)
Q.5 Whatis a CMS? Explain Drupal’s architecture. What are Menus used for in Drupal? (10 Marks)
Q.6 Drupal allows you to create three kinds of contents: state them. What is a Menu in Drupal? (5 Marks)
Q.7 What are Templates in Joomla? Briefly explain what the two kinds of Templates in Joomla are, (5 Marks)
Q.8 Explain Joomla’s architecture with all 7 components. Drupal allows you to create three kinds of contents: state them.
(10 Marks)
gga
Multiple Choice Questions (MCQs) |
|
%F Web X.0 (MU) MCQs with Answers
M-2
EE
(c) Sunk Costs
(d) Data Segmentation
a
Q.4 What is the strategy to choose between vendors called?
(a) Sensitivity Analysis
(b) Legal Brief Incorporation
(c) Lawful Comparison
(d) Three Bucket Strategy
Q.5 Which of the following is not a KPI?
(a) Percentage of Total Exits
(b) Share of Search
(c) | Abandonment
(d) RSS Subscribers
Q.6 Which of these is not a component of Semantic Web?
(a) XML
(b) URL
(c) RDF
(d) Hyperlinks
ng?
Q.7 Middle layer of Semantic Web Stack contains which of the followi
(a) AngularJS
(b) XML Namespace
(c) | Web Ontology Language
(d) Global Description Schema
Say Tech Knowledya
Publications
nied
Q.8 Pick the right components of a Simple Triple in the right order?
(a) (Subject, Predicate , Object) |
(b) (Subject , Object, Predicate)
(a) — <http://abe.org/#suresh>
<http:/Wwww.abc.net/relationship/man>
<http://examabeple.org/#suraj> .
(b) <http://abc.org/#suresh>
<http:/Avww.abe.net/relationship/brotherOf>
<http://examabcple.org/#suraj>
(c) <httpy/abc.org/#suresh>
<http:/Avww.abe.net/relationship/id=1 1342>
<http://examabcple.org/#suraj> .
—— (d) <http://abc.org/#suresh>
<http:/Avww.abc.net/relationship/twinOf>
<http://examabcple.org/#suraj> . }
W Tech Knowledge
Puoticarians
RF Web X.0 (MU)
M-4 MCQs with Answers
Q.14 Which of these is not a reasoning service supported by the OWL reasoner?
(a) Ontology Satisfiability
(b) | Subsumption
(d) Classification
Which of these is not an OWL profile?
(a) OWLEL
(b) OWLQL
(c) OWLFULL
(d) OWLXL
Q. 16 When the database is too large to display, the following SPARQL technique cuts down the number of rows:
(a) | Ordering
(b) — Pivoting
(c) Dicing
(d) — Slicing
(a) distinct
(b) dedup
(c) _ slice
(d) deuplicate
(a) count
(b) avg
(c) group_sample
(d) group_concat
Q.19 The following keyword is used to return the RDF graph in SPARQL:
(a) rdf_return
(b) describe
(c) display
(d) ask
4. (0) 2 (bt) 3 (c) 4 (0) 5 (a) & Gd) 7. (c) 8. (a) 9. (d) 10. (b)
41.(a) 12.(a) 13.(c) 14.(d) 15.(d) 16.(a) 17. (c) 18. (b) 49. (b)
UF Tecaknomtedys
Publications
W Web X.0 (MU) sss MCQs with Answers
| Chapter 2 : TypeScript |
Q.25 Which example here is the wrong way to define a variable and will throw an error?
}
addTwoThings ("1", 0");
(a) 1
(b) 140
(c) 10
(d) None of the above
¥ Tech Knowledge
Publicatians
WF Web X.0 (MU) MCQs with Answers
__ M-7 NOT inherit from a parent Class?
Q.32 In TypeScript Inheritance, which of the following does a child Clas
s
(a) static methods
(b) public methods
(c) private methods
(d) class variables
Q.33 Which of these is NOT a TypeScript Access Specifier?
(a) public
(b) parent
(c) protected
(d) private
Q.34 Interface extension and implementation use the following keywords
:
(a) extends and implements
(b) extend and implement
(c) extends and implement
UF Pyaticacieny
Techtneniety!
WF Web X.0 (MU) wa
MCQs with Answers
Q.3 The Document Object Mode! can
be of X types. What Is X?
(a) 1
(b) 2
(c) 3
(d) 4
Q.4 — AngularJS uses the following to bind data to HTML:
(a) Directives
(b) Expressions
(c) Controls
(d) JavaScript
Q.10 The following part of TypeScript packages the source program into smaller chunks:
(a) Module
(b) Controller
(c) View
(a) PUT
(b) POST
(c) DELETE
(d) GET
In AngularJS, | can build my own custom services.
(b) True
(c) False
(a) seconds
(b) —_ milliseconds
(c) minutes
(d) microseconds
(a) $clean
(b) — $dirty
(c) $valid
(d) $invalid
This TypeScript Directive contains the CSS code for web pages.
(a) ng-design
(b) —ng-styling
(c) _ ng-stylize
(d) —ng-style
vay TechKnewledga
Puulications
GF Web X.0 (MU) MCQs with Answers
M-10
Q.17 AngularJS allows users to update web pages without reloading them.
(a) True
(b) False
(c) True, but needs to connect to TypeScript
(d) True, but needs to connect to Python
Q.18 Any hanes to Model percolate to the View and any changes to View percolate to the Model. What is this called in
AngularJS?
PEA Ey
1. (a) 2. (a) 3. (c) 4 (b) 5. (a) 6. (Cc) - 7. (a) 8. (d) 96 (b) 22 510. (a) ©
41.(a) 12.() 13.(0) 14.() 15.(a) 16.(d) 17.(@) 18. (b) "49. (b).
(a) True
(b) False
(d) False
Q.5 — Which of the following is not a data type in MongoDB?
(a) Min Key
(b) Object
(c) Empty
(d) Regular Expression
Q.6 — Role-Based Access Control in MongoDB does NOT have the following rule:
a (a) | Superuser
sib (b) “Database Admin
(c) Restoration Admin
Q.8 — This MongoDB method is used to find any documents already inserted into the collection.
(a) _ findltem 7 |
(b) — fineOne
(c) — findDocument
(d) — findCollection
Q.10 Which of the following HTTP request methods cannot provide a response for a request?
(a) GET
(b) PUT
(c) DELETE
| (d) POST
WY TechKnowledge
Publications
SF Web X.0 (MU) M-13 MCQs with Answers
Chapter 5 : Flask
(a) True
(b) False
(d) Notsure
Q.3 The app.run function in Flask does NOT have this parameter:
(a) host
(b) port
(c) debug
(d) checks
W Tech Knowledge
Publications
YF Web X.0 (MU) MCQs with Answers
M-14
Q.7 The function urlFor () can create a new URL.
(a) True
(b) False
(c) True but it should not be used due to security concerns
(d) — Incomplete information
(c) Acts as intermediary between server and database to fulfill client request
(d) — Stores data to send from client to server
(a) True
(b) False
(c) Only if connected to a web browser
(d) _ Insufficient information
Flask needs the following information to consider a cookie valid.
(a) expiration date, path and domain of the website cookie is meant for
(b) expiration date, request object and path
(c) expiration date, request object and domain of the website cookie is meant for
You can see the name and content of a cookie in your browser.
(a) True
(b) False
(c) True, but you have to click on “Accept All Cookies”
(a) True
(b) False
(c) True, but they must be encrypted
ization
(d) True, but only with role access and author
var Tech Knowledge
Publications
SF Web X.0 (MU) M-15 MCQs with Answers
(a) 16kb
(b) 8kb
(c) 2kb
(d) 4kb
(a) True
(d) False
Answers
(a) True
(b) False
AJAX uses well-known internet standards. Which of the following is not one of them?
(a) XML
(b) CSS
(d) JSON
(a) AJAX
(b) Python
(c) Flask
(d) TypeScript
¥ Tech Knowledge
Publications
YF Web X.0 (MU) M-16 MCQs with Answers
Q.6 The following command is used in Django to start an application called “appName”:
(a) $django manage.py startapp appName
Q. 10 The following component of the framework Django is based on receives response objects from the server:
(a) Model
(b) View
(c) Controller
(d) Template
TechKnowledge
Publications
SF Web X.0 (MU) M-17 MCQs with Answers
(c) Render
(d) View
Drupalis built using.
(a) Python
(b) JavaScript
(c) PHP
(d) Flask
Q. 13 Drupal allows all kinds of data to be stored.
(a) True
(d) False
9.(d) 10.(b) 11.(c) 12.(c) 19.(a) 14.(d) 15. (b) 16. (a)
O00