0% found this document useful (0 votes)
34 views211 pages

WT Unit 5 NOTES

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views211 pages

WT Unit 5 NOTES

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 211

Introduction to PHP

PHP Introduction

PHP is a recursive acronym for “PHP: Hypertext


Pre-processor” -- It is a widely-used open source
general-purpose scripting language that is
especially suited for web development and can
be embedded into HTML.
PHP Introduction

> PHP is a server-side scripting language


> PHP scripts are executed on the server
> PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
> PHP is open source software
> PHP is free to download and use
Client/Server on the WWW

Standard web sites operate on a
request/response basis

A user requests a resource E.g. HTML
document

Server responds by delivering the document to
the client

The client processes the document and
displays it to user
Server Side Programming

Provides web site developers to utilise resources on
the web server

Non-public resources do not require direct access
from the clients

Allows web sites to be client agnostic (unless
JavaScript is used also)

Most server side programming script is embedded
within markup (although does not have to be,
sometimes better not to)
PHP - What is it / does it do?
PHP: PHP Hypertext Pre-processor

Programming language that is interpreted and
executed on the server

Execution is done before delivering content to
the client

Contains a vast library of functionality that
programmers can harness

Executes entirely on the server, requiring no
specific features from the client
PHP - What is it / does it do?

Static resources such as regular HTML are simply output to the
client from the server

Dynamic resources such as PHP scripts are processed on the
server prior to being output to the client

PHP has the capability of connecting to many database
systems making the entire process transparent to the client

Web Page Request Load PHP File

PHP Engine –
Run Script

HTML Response PHP Results


User Web Server
https://www.youtube.com/watch?
v=KBT2gmAfav4
PHP Summary
PHP: PHP Hypertext Pre-processor

Interpreted and executed by the server on page
request

Returns simple output to the client

Provides a tremendous amount of functionality
to programmers

Can connect transparently to many database
systems
PHP Features

> PHP runs on different platforms (Windows,


Linux, Unix, etc.)
> PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
> PHP is FREE to download from the official PHP
resource: www.php.net
> PHP is easy to learn and runs efficiently on the
server side
PHP Introduction

Instead of lots of commands to output HTML (as


seen in C or Perl), PHP pages contain HTML with
embedded code that does "something" (like in the
next slide, it outputs "Hi, I'm a PHP script!").

The PHP code is enclosed in special start and


end processing instructions <?php and ?> that
allow you to jump into and out of "PHP mode."
PHP Introduction
PHP Introduction

PHP code is executed on the server, generating


HTML which is then sent to the client. The client
would receive the results of running that script, but
would not know what the underlying code was.

A visual, if you please...


PHP Introduction
General Syntactic Characteristics

PHP code can be specified in an XHTML document internally or externally:
myphp.php
 Internally: <?php ...

?>
 Can appear almost everywhere
 Externally: include ("myScript.inc")
 The included file can have both PHP and XHTML, if the file has PHP, the PHP must be in
<?php .. ?>, even if the include is already in <?php .. ?>

Variable conflict


PHP mode of operation
 Copy mode
 Interpret mode

Every variable name begin with a $
 Case sensitive
 A letter or an underscore followed by any number of letters, digits, or underscores.
General Syntactic Characteristics
• Comments - three different kinds (Java and Perl)
// ...
# ...
/* ... */
• Statements are terminated with semicolons
• Compound statements are formed with braces
• Unless used as the body of a function definition, compound
statements cannot be blocks (cannot define locally scoped
variables)
Output

Output from a PHP script is HTML that is sent to the browser

HTML is sent to the browser through standard output

There are three ways to produce output: echo, print, and printf
 echo and print take a string, but will coerce other values to strings
$name=“John”; $age=20;
 echo “$name“, “$age”; (any number of parameters)
 echo(“my name: $name, my age: $age”); (only one)
 print “$name and $age";
 print (“my name: $name, my age: $age”);
 printf(“my name: %s, my age: %s”, $name, $age);

Echo does not return a value; print return 1 or 0; printf returns
the length of the outputted string
PHP Getting Started

SET UP - Will be covered in Lab session


https://youtu.be/ueWpNe0PG34
Assignment No -07
PHP Hello World

Above is the PHP source code.


PHP Hello World

It renders as HTML that looks like this:


PHP Hello World

This program is extremely simple and you really


did not need to use PHP to create a page like this.
All it does is display: Hello World using the PHP
echo() statement.

Think of this as a normal HTML file which


happens to have a set of special tags available to
you that do a lot of interesting things.
PHP Comments
In PHP, we use // to
make a single-line
comment or /* and */ to
make a large comment
block.
PHP Variables
> Variables are used for storing values, like text
strings, numbers or arrays.
> When a variable is declared, it can be used over
and over again in your script.
> All variables in PHP start with a $ sign symbol.
> The correct way of declaring a variable in PHP:
PHP Variables

> In PHP, a variable does not need to be declared


before adding a value to it.
> In the example above, you see that you do not
have to tell PHP which data type the variable is.
> PHP automatically converts the variable to the
correct data type, depending on its value.
PHP Variables

> A variable name must start with a letter or an


underscore "_" -- not a number
> A variable name can only contain alpha-numeric
characters, underscores (a-z, A-Z, 0-9, and _ )
> A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with an underscore ($my_string) or with
capitalization ($myString)
Primitives, Operations, and Expressions

Variables
 No type declarations
 An unassigned (unbound) variable has the value: NULL
 The unset function sets a variable to NULL
 The IsSet function is used to determine whether a variable is
NULL
 error_reporting(15); - prevents PHP from using unbound variables

PHP has many predefined variables, including the
environment variables of the host operating system
 You can get a list of the predefined variables by calling phpinfo() in
a script
Primitives, Operations, and Expressions

There are eight primitive types:
 Four scalar types: Boolean, integer, double, and string
 Two compound types: array and object
 Two special types: resource and NULL

PHP 1-27
Primitives, Operations, and Expressions

Strings
 Characters are single bytes
 The length of a string is limited only by the available memory
 String literals use single or double quotes

Single-quoted string literals
 Embedded variables are NOT interpolated
 Embedded escape sequences are NOT recognized

Double-quoted string literals
 Embedded variables ARE interpolated
 If there is a variable name in a double quoted string but you don’t want it
interpolated, it must be backslashed
 Embedded escape sequences ARE recognized
 For both single- and double-quoted literal strings, embedded delimiters
must be backslashed
 String character access

$str=“Apple”

$str{2}=“p”
Primitives, Operations, and Expressions

Boolean
 values are true and false (case insensitive)
 0 and "" and "0" are false; others are true

But “0.0” is true

Arithmetic Operators and Expressions
 Usual operators
 If the result of integer division is not an integer, a double is returned
 Any integer operation that results in overflow produces a double
 The modulus operator coerces its operands to integer, if necessary

Arithmetic functions
 floor, ceil, round, abs, min, max, rand, etc.

Round($val, x);
Primitives, Operations, and Expressions

Scalar Type Conversions conversion.php
 String to numeric

If the string contains an e or an E, it is converted to double; otherwise to
integer

If the string does not begin with a sign or a digit, zero is used

Explicit conversions – casts
 e.g., (int)$total or intval($total) or settype($total, "integer")

Intval($total), doubleval($total), strval($total);

The type of a variable can be determined with gettype or
is_type
 gettype($total) - it may return "unknown"
 is_integer($total) – a predicate function

is_double(), is_bool(), is_string()
PHP
PHP Concatenation
> The concatenation operator (.) is used to put
two string values together.
> To concatenate two string variables together,
use the concatenation operator:
PHP Concatenation

The output of the code on the last slide will be:

If we look at the code you see that we used the


concatenation operator two times. This is because
we had to insert a third string (a space character),
to separate the two strings.
PHP Operators

Operators are used to operate on values. There


are four classifications of operators:

> Arithmetic
> Assignment
> Comparison
> Logical
PHP Operators
PHP Operators
PHP Operators
PHP Operators
Expressions

• Completely normal like other languages ( + - / * )

• More aggressive implicit type conversion

<?php
$x = "15" + 27;
echo($x);
echo("\n");
?>
PHP Conditional Statements

> Very often when you write code, you want to


perform different actions for different decisions.
> You can use conditional statements in your
code to do this.
> In PHP we have the following conditional
statements...
PHP Conditional Statements
> if statement - use this statement to execute
some code only if a specified condition is true
> if...else statement - use this statement to
execute some code if a condition is true and
another code if the condition is false
> if...elseif....else statement - use this statement
to select one of several blocks of code to be
executed
> switch statement - use this statement to select
one of many blocks of code to be executed
PHP Conditional Statements
The following example will output "Have a nice
weekend!" if the current day is Friday:
PHP Conditional Statements
Use the if....else statement to execute some code
if a condition is true and another code if a
condition is false.
PHP Conditional Statements

If more than one line


should be executed if a
condition is true/false,
the lines should be
enclosed within curly
braces { }
PHP Conditional Statements

The following example


will output "Have a nice
weekend!" if the current
day is Friday, and "Have
a nice Sunday!" if the
current day is Sunday.
Otherwise it will output
"Have a nice day!":
PHP Conditional Statements
Use the switch statement to select one of many
blocks of code to be executed.
PHP Conditional Statements
For switches, first we have a single expression n
(most often a variable), that is evaluated once.

The value of the expression is then compared with


the values for each case in the structure. If there
is a match, the block of code associated with that
case is executed.

Use break to prevent the code from running into


the next case automatically. The default statement
is used if no match is found.
PHP Conditional Statements
PHP Loops

> while - loops through a block of code while a


specified condition is true
> do...while - loops through a block of code once,
and then repeats the loop as long as a specified
condition is true
> for - loops through a block of code a specified
number of times
> foreach - loops through a block of code for each
element in an array
PHP Loops - While
The while loop executes a block of code while a
condition is true. The example below defines a
loop that starts with
i=1. The loop will
continue to run as
long as i is less
than, or equal to 5.
i will increase by 1
each time the loop
runs:
PHP Loops - While
PHP Loops – Do ... While

The do...while statement will always execute the


block of code once, it will then check the
condition, and repeat the loop while the condition
is true.

The next example defines a loop that starts with


i=1. It will then increment i with 1, and write some
output. Then the condition is checked, and the
loop will continue to run as long as i is less than,
or equal to 5:
PHP Loops – Do ... While
PHP Loops – Do ... While
PHP Loops - For
PHP Loops - For
Parameters:
> init: Mostly used to set a counter (but can be
any code to be executed once at the beginning
of the loop)
> condition: Evaluated for each loop iteration. If
it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
> increment: Mostly used to increment a counter
(but can be any code to be executed at the end
of the loop)
PHP Loops - For
The example below defines a loop that starts with
i=1. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each
time the loop runs:
PHP Loops - For
PHP Loops - Foreach

For every loop iteration, the value of the current


array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop
iteration, you'll be looking at the next array value.
PHP Loops - Foreach

The following example demonstrates a loop that


will print the values of the given array:
PHP Loops - Foreach

Winner of the most impressive slide award


PHP Arrays

> An array variable is a storage area holding a


number or text. The problem is, a variable will hold
only one value.
> An array is a special variable, which can store
multiple values in one single variable.
PHP Arrays

If you have a list of items (a list of car names, for


example), storing the cars in single variables
could look like this:
PHP Arrays
> However, what if you want to loop through the
cars and find a specific one? And what if you had
not 3 cars, but 300?
> The best solution here is to use an array.
> An array can hold all your variable values under
a single name. And you can access the values by
referring to the array name.
> Each element in the array has its own index so
that it can be easily accessed.
PHP Arrays
In PHP, there are three kind of arrays:
> Numeric array - An array with a numeric index
> Associative array - An array where each ID
key is associated with a value
> Multidimensional array - An array containing
one or more arrays
PHP Numeric Arrays

> A numeric array stores each array element with


a numeric index.
> There are two methods to create a numeric
array.
PHP Numeric Arrays
In the following example the index is automatically
assigned (the index starts at 0):

In the following example we assign the index


manually:
PHP Numeric Arrays
In the following example you access the variable
values by referring to the array name and index:

The code above will output:


PHP Associative Arrays

> With an associative array, each ID key is


associated with a value.
> When storing data about specific named values,
a numerical array is not always the best way to do
it.
> With associative arrays we can use the values
as keys and assign values to them.
PHP Associative Arrays
In this example we use an array to assign ages to
the different persons:

This example is the same as the one above, but


shows a different way of creating the array:
PHP Associative Arrays
PHP Multidimensional Arrays

In a multidimensional array, each element in the


main array can also be an array.

And each element in the sub-array can be an


array, and so on.
Functions on Array

print_r() –Prints all elements of an array in standard format

extract()-Converts array into variables

compact()-Converts group of variables into array

is_array() –to check weather a particular elements is an array or not.

sort() - sort arrays in ascending order

rsort() - sort arrays in descending order,

asort()-sorts associative arrays in ascending order, on values

ksort()-sorts associative arrays in ascending order,on keys

arsort()- sorts associative arrays in descending order,on values

krsort()-sorts associative arrays in descending order,on keys
PHP Multidimensional Arrays
PHP Multidimensional Arrays
PHP Multidimensional Arrays
PHP Loops

> Often when you write code, you want the same
block of code to run over and over again in a row.
Instead of adding several almost equal lines in a
script we can use loops to perform a task like this.
> In PHP, we have the following looping
statements:
PHP Functions
> We will now explore how to create your own
functions.
> To keep the script from being executed when
the page loads, you can put it into a function.
> A function will be executed by a call to the
function.
> You may call a function from anywhere within a
page.
PHP Functions

A function will be executed by a call to the


function.

> Give the function a name that reflects what the


function does
> The function name can start with a letter or
underscore (not a number)
PHP Functions
A simple function that writes a name when it is
called:
PHP Functions - Parameters

Adding parameters...
> To add more functionality to a function, we can
add parameters. A parameter is just like a
variable.
> Parameters are specified after the function
name, inside the parentheses.
PHP Functions - Parameters
PHP Functions - Parameters
PHP Functions - Parameters

This example adds


different punctuation.
PHP Functions - Parameters
FORM HANDING IN PHP

What is Form?

When you login into a website or into your mail box, you are
interacting with a form.

Forms are used to get input from the user and submit it to the
web server for processing.

The diagram below illustrates the form handling process.
PHP Forms - $_GET Function

> The built-in $_GET function is used to collect


values from a form sent with method="get".
> Information sent from a form with the GET
method is visible to everyone (it will be displayed
in the browser's address bar) and has limits on the
amount of information to send (max. 100
characters).
PHP Forms - $_GET Function

Notice how the URL carries the information after the file name.
PHP Forms - $_GET Function

The "welcome.php" file can now use the $_GET


function to collect form data (the names of the
form fields will automatically be the keys in the
$_GET array)
PHP Forms - $_GET Function
> When using method="get" in HTML forms, all
variable names and values are displayed in the URL.
> This method should not be used when sending
passwords or other sensitive information!
> However, because the variables are displayed in
the URL, it is possible to bookmark the page. This
can be useful in some cases.
> The get method is not suitable for large variable
values; the value cannot exceed 100 chars.
PHP Forms - $_POST Function
> The built-in $_POST function is used to collect
values from a form sent with method="post".
> Information sent from a form with the POST
method is invisible to others and has no limits on
the amount of information to send.
> Note: However, there is an 8 Mb max size for
the POST method, by default (can be changed by
setting the post_max_size in the php.ini file).
PHP Forms - $_POST Function

And here is what the code of action.php might look like:


PHP Forms - $_POST Function
Apart from htmlspecialchars() and (int), it should
be obvious what this does. htmlspecialchars()
makes sure any characters that are special in html
are properly encoded so people can't inject HTML
tags or Javascript into your page.

For the age field, since we know it is a number,


we can just convert it to an integer which will
automatically get rid of any stray characters. The
$_POST['name'] and $_POST['age'] variables
are automatically set for you by PHP.
Dealing with forms


HTML Forms (GET and POST)
 form is submitted to a PHP script
 information from that form is
automatically made available to the script
 forms.php
<form action="foo.php" method="POST">
Name: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit
me!">
</form>
Forms – foo.php

<?php // Available since PHP 4.1.0


print $_POST['username'];
print $_REQUEST['username'];
import_request_variables('p', 'p_');
print $p_username;
print $HTTP_POST_VARS['username'];
print $username; ?> (see result here)
Another forms example

info_form.php
<form action=“show_answers.php” method="POST">
Your name: <input type="text" name="name" />
Your age: <input type="text" name="age" />
<input type="submit">
</form>

show_answers.php
Hi
<?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old.

(see results here)


PHP Forms - $_POST Function
When to use method="post"?
> Information sent from a form with the POST
method is invisible to others and has no limits
on the amount of information to send.
> However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
using MySQL with PHP
Create (Insert)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (name, email) VALUES (‘Ram',
[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Read (Select)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Update
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Delete
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
PHP - Dealing with the Client
All very nice but …
… How is it useful in your web site?
PHP allows you to use HTML forms
Forms require technology at the server to
process them
PHP is a feasible and good choice for the
processing of HTML forms
PHP - Dealing with the client

Quick re-cap on forms


Implemented with a <form> element in HTML
Contains other input, text area, list controls and
options
Has some method of submitting
PHP - Dealing with the client
Text fields
Checkbox
Radio button
List boxes
Hidden form fields
Password box
Submit and reset buttons
PHP - Dealing with the client
<form method=“post” action=“file.php” name=“frmid” >
Method specifies how the data will be sent
Action specifies the file to go to. E.g. file.php
id gives the form a unique name
Post method sends all contents of a form with basically
hidden headers (not easily visible to users)
Get method sends all form input in the URL requested
using name=value pairs separated by ampersands (&)
E.g. process.php?name=trevor&number=345
Is visible in the URL shown in the browser
PHP - Dealing with the client
All form values are placed into an array
Assume a form contains one textbox called “txtName”
and the form is submitted using the post method,
invoking process.php
process.php could access the form data using:
$_POST[‘txtName’]
If the form used the get method, the form data would
be available as:
$_GET[‘txtName’]
PHP - Dealing with the client
For example, an HTML form:
<form id=“showmsg” action=“show.php”
method=“post”>
<input type=“text” id=“txtMsg” value=“Hello World” />
<input type=“submit” id=“submit” value=“Submit”>
</form>
PHP - Dealing with the client
A file called show.php would receive the
submitted data
It could output the message, for example:
<html>
<head><title>Show Message</title></head>
<body>
<h1><?php echo $_POST[“txtMsg”]; ?></h1>
</body>
</html>
PHP - Dealing with the client
Summary
Form elements contain input elements
Each input element has an id
If a form is posted, the file stated as the action can
use:
$_POST[“inputid”]
If a form uses the get method:
$_GET[“inputid”]
Ensure you set all id attributes for form elements
and their contents
PHP Introduction - Summary
Topics covered
 Server side architecture brief overview
 Basic PHP language topics

Syntax

Variables, Constants and Operators

Decision making, IF and Switch statements

Dealing with the client
PHP: Files

Deal with any file on the server
$fptr = fopen(filename, use_indicator)

Use indicators:
 “r”read only, from the beginning
 “r+”read and write, from the beginning
 “w”write only, from the beginning (also creates the file, if necessary)
 “w+”read and write, from the beginning (also creates the file, if necessary)
 “a”write only, at the end, if it exists (creates the file, if necessary)
 “a+”read and write, read at the beginning, write at the end
 “b”binary file: on systems which differentiate between binary and text files
$fptr1=fopen(“test1.php”, “w+”);files.phpfiles.php
$fptr2=fopen(“test1.php”, “r+”);
PHP: Files

fopen could fail
 it will return “false”
 Use file_exists(filename) to determine
whether file exists before trying to open it
 Use fopen with “die”
 Always use fclose(file_var) to close a file,
after your reading/writing
PHP: Write to Files

$bytes_written = fwrite(file_var, string)
 fwrite returns the number of bytes it wrote
 Return “false” on error

6
PHP: Reading Files

Read all or part of the file into a string variable
 $str = fread(file_var, #bytes)
 To read the whole file, use filesize(file_name) as the second parameter

Read one line from the file
 $line = fgets(file_var[, #bytes])
 Reads characters until eoln, eof, or #bytes characters have been read

Read one character from the file
 $ch = fgetc(file_var)

Control reading lines or characters with eof detection using feof (TRUE for
eof; FALSE otherwise)
while(!feof($file_var)) {
$ch = fgetc($file_var);
}
PHP file access

Read the lines of the file into an array
 array file ( string filename)

file() returns the file in an array

Each element of the array corresponds to a line in the
file, with the newline still attached

Upon failure, file() returns FALSE
Cookie

What is a cookie?
 An message given to a web browser by a web server, then send back to the server each time the browser requests
a page from the server.

What can cookie do for us?
 Identify users and store client side information
 Authenticate or identify a registered user

No need to sign in again every time they access a website

Where is the cookie located? How does it look like?
 C:\Documents and Settings\YourLoginID\Local Settings\Temporary Internet Files

Will browser return all cookies to each server?
 No, only those matched domains
 Malicious cookies setting

Are cookies dangerous to my computer?
 No

Is this a major privacy issue?
 You could lose identify information
 You have choices of not using any cookie
Cookie

Create a cookie with setcookie
 setcookie(cookie_name, cookie_value, lifetime)

setcookie("voted", "true", time() + 86400);

setcookie("voted", "true", time() + 60*60*24);
 Is “lifetime” important?

Without this value, cookie expires right after you close the current web browser window.

Expired cookies will be deleted without sending back to the server
 Cookies must be created before any other HTML is created by the script

Before <html><body>…were sent
 How to access the cookie value

Using the $_COOKIE array
 setcookie("visits“, $visitcount, time()+3600);
 $visitcount = $_COOKIE["visits"];

Check whether a cookie has been set before
 Isset($_COOKIE[“visits”])
Cookies from HTTP

Client (e.g. Firefox) it026945

GET /*.html HTTP/1.1


Host: it026954.domain
HTTP/1.1 200 OK
Content-type:
text/html
Set-Cookie:
name=value
GET /*.html HTTP/1.1
Host: it026945.domain (content of page)
Cookie: name=value
Accept: */*
Reading cookies
To access a cookie received from a client, use the PHP
$_COOKIE superglobal array

<?php

foreach ($_COOKIE as $key=>$val) {


print $key . " => " . $val . "<br/>";
}

?>

Each key in the array represents a cookie - the key


name is the cookie name.
Using headers (correct approach)
<?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>

<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1" />
</head>
<body>
<?php
echo “<p> A cookie has been set. </p>”;
?>
</body>
</html>

This is the correct approach!


Deleting a cookie

Set the cookie with its name only:

setcookie(“mycookie”);
PHP Sessions

You can store user information (e.g. username,


items selected, etc.) in the server side for later
use using PHP session.

Sessions work by creating a unique id (UID)


for each visitor and storing variables based on
this UID.

The UID is either stored in a cookie or is


propagated in the URL.
When should you use sessions?

Need for data to stored on the server

Unique session information for each user

Transient data, only relevant for short time

Data does not contain secret information

Similar to Cookies, but it is stored on the server

More secure, once established, no data is sent
back and forth between the machines

Works even if cookies are disabled

Example: we want to count the number of
“hits” on our web page.
Before you can store user information in your PHP
session, you must first start up the session.

session_start() function must appear BEFORE the <html> tag.

<?php session_start(); ?>

<html>
<body>

</body>
</html>
Session variables

$_SESSION

e.g., $_SESSION[“intVar”] = 10;


Testing if a session variable has been set:
session_start();
if(!$_SESSION['intVar']) {...} //intVar is set or not
Registering session variables

Instead of setting superglobals, one can register one’s own
session variables

<?php
$barney = “A big purple dinosaur.”;
$myvar_name = “barney”;
session_register($myvar_name);
?>


$barney can now be accessed “globally” from session to
session

This only works if the register_globals directive is
enabled in php.ini - nowadays this is turned off by default

Use of session_register() is deprecated!


Make your own session variables


With session_start() a default session
variable is created - the name extracted
from the page name

To create your own session variable just
add a new key to the $_SESSION
superglobal

$_SESSION[‘dug’]
$_SESSION = “a talking dog.”;

Use of $_SESSION is preferred, as of PHP 4.1.0.


Session Example 1
<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have accessed this
page " . $_SESSION["intVar"] . "times.</p>";
?>
Session Example 2
?php session_start();?>
?php
thisPage = $_SERVER['PHP_SELF'];

pageNameArray = explode('/', $thisPage);


pageName = $pageNameArray[count($pageNameArray) - 1];
rint "The name of this page is: $pageName<br/>";

nameItems = explode(‘.', $pageName);


sessionName = $nameItems[0];
rint "The session name is $sessionName<br/>";

(!isset($_SESSION[$sessionName])) {
$_SESSION[$sessionName] = 0;
print "This is the first time you have visited this page<br/>";

se {
$_SESSION[$sessionName]++;

rint "<h1>You have visited this page " . $_SESSION[$sessionName] .


" times</h1>";
>
PosgreSQL with PHP

Assume the following database table and data:
CREATE TABLE employees
( id tinyint(4) DEFAULT '0' NOT NULL AUTO_INCREMENT,
first varchar(20),
last varchar(20),
address varchar(255),
position varchar(50),
PRIMARY KEY (id),
UNIQUE id (id));
INSERT INTO employees VALUES
(1,'Bob','Smith','128 Here St, Cityname', 'Marketing
Manager');
INSERT INTO employees VALUES
(2,'John','Roberts','45 There St ,Townville', 'Telephonist');
INSERT INTO employees VALUES
(3,'Brad','Johnson','1/34 Nowhere Blvd, Snowston','Doorman');
PostgreSQL Example (cont)
<html>

<body>

<?php

$db = pg_connect(“dbname=sam user=sam password=iam")

or die(“Couldn’t Connect: “.pg_last_error($db));

$query=“SELECT * FROM employees”;

$result = pg_query($db,$query)

or

die(“Error in query: $query.”.pg_last_error($db));

$rows = pg_num_rows($result);
PostgreSQL Example (cont)
if ($rows > 0) {

for ($i=0; $i<$rows; $i++){

$my_row = pg_fetch_array($result, $i, PGSQL_ASSOC);

printf("First Name: %s",$my_row[“first”]);

printf("Last Name: %s", $my_row[“last“]);

printf("Address: %s", $my_row[“address“]);

printf("Position: %s",$my_row["position“]);

printf(“\n”);

pg_close($db);

?>

</body>

</html>
Wireless Application Protocol

The basic aim of WAP is to provide a web-like
experience on small portable devices - like
mobile phones and PDAs
WAP-Introduction

Purpose of WAP

To enable easy, fast delivery of relevant information
and services to mobile users.

Type of devices that use WAP

Handheld digital wireless devices such as mobile
phones, pagers, two-way radios, smart phones and
communicators -- from low-end to high-end.

Type of OS that use WAP

It can be built on any operating system including Palm
OS, EPOC 32, Windows CE, FLEXOS, OS/9, Java O
Working of Wireless Application
Protocol or WAP Model
WAP Architecture
Wireless MarkupLanguage (WML)

WML is the markup language defined in the WAP
specification. WAP sites are written in WML, while web
sites are written in HTML.

WML is very similar to HTML. Both of them use tags
and are written in plain text format.

WML (Wireless Markup Language), formerly called
HDML (Handheld Devices Markup Languages), is a
language that allows the text portions of Web pages to
be presented on cellular telephones and personal
digital assistants (PDAs) via wireless access
Wireless Markup Language

WML follows a deck and card
 A WML document is made up of multiple cards
 Cards can be grouped together into a deck

A WML deck is similar to an HTML page
 A user navigates with the WML browser through a
series of WML cards.
WMLStructure
< ? xml version=“1.0” ? >
<!DOCTYPE wml …>
<wml>
<card>
<p>
Text….
</p>
<p>
Text……
</p>
</card>
<card>
...
</card>
</wml>
Introduction to ASP.NET

What is ASP.NET and how is different from ASP
 ASP: server side technology for creating dynamic web pages
using scripting languages eg vb script.
 ASP.NET: server side technology for creating dynamic web
pages using Fully Fledged programming languages
supported by .NET
 VB.NET: our chosen language for writing ASP.NET pages
What is .NET?
 A Microsoft strategy and new technology for delivering software services
to the desktop and to the web
 Components include:
 MS Intermediate Language; all code is complied into a more abstract, trimmed
version before execution. All .NET languages are compiled to MSIL – the
common language of .NET
 The CLR- common language runtime; responsible for executing MSIL code;
interfaces to Windows and IIS
 A rich set of libraries (Framework Class Libraries) available to all .NET
languages
 The .NET languages such as C#, VB.NET etc that conform to CLR
 ASP.NET is how the Framework is exposed to the web, using IIS to manage
simple pages of code so that they can be complied into full .NET programs.
These generate HTML for the browser.
 Built on open protocols (XML, SOAP)

 Future for development of MS & non-MS based systems.

 Also heading towards the “Internet Operating System”


Common Language Runtime
Type System
Compilers use the runtime type system to produce
type compatible components

Components

C# VB C++ Compilers

Runtime Environment
Common Type System
Robust And Secure
 Native code compilation
 MSIL
 No interpreter
 Install-time or run-time IL to native compilation

 Code correctness and type-safety


 IL can be verified to guarantee type-safety
 No unsafe casts, no uninitialized variables, no out-of-bounds array
indexing

 Evidence-based security
 Policy grants permissions based on evidence (signatures, origin)
.NET Execution Model
VB VC ... Script

Native
IL
Code

Common Language Runtime

Standard JIT
Compiler

Native
Code
Common Language Runtime

Lightweight Just-in-time compiler:
 MSIL to Native machine language; Can be ported to numerous platforms

The compiled code is transformed into an intermediate
language called the Microsoft Intermediate Language (MSIL or
IL)

An integer in Visual Basic .NET or an int in C# are converted to
the same .NET data type, which is Int32

The IL that is created is the same for all languages

The assembly is the compiled .NET program

The assembly contains the IL along with additional information
called metadata

Metadata contains information about the assembly

Use the IL Disassembler (ildasm.exe) to view the IL within an
assembly
Framework Overview

VB C++ C# JScript …

Common Language Specification

Visual Studio.NET
Web Forms
Win Forms
(ASP.NET)

Data and XML

Base Class Library

Common Language Runtime


.NET Framework Architecture

System.Web System.WinForms
Web Services Web Forms Controls Drawing

ASP.NET Application Services Windows Application Services

System Base Framework

ADO.NET XML SQL Threading

IO Net Security ServiceProcess

Common Language Runtime


Type System Metadata Execution
Namespace

The base class libraries are organized into logical
groupings of code called namespaces

A namespace is a hierarchical way to identify
resources in .NET

The System object is at the top of the namespace
hierarchy, and all objects inherit from it
 ASP.NET: System.Web namespace
 WebForms: System.Web.UI namespace
 HTML Server Controls:
System.Web.UI.Control.HTMLControl
 ASP.NET Server Controls:
System.Web.UI.Control.WebControl
Importing Namespaces

Visual Studio .NET adds references to your
projects’ commonly used namespaces by default

You can import the namespaces into your page
using the @Import directive

The following is the syntax for importing a .NET
namespace
<%@ Import NamespaceName %>

Below is a sample of how you would import the
ASP.NET Page class
<%@ Imports System.Web.UI.Page %>
Some ASP.NET namespaces
System Defines fundamental data types eg
system.string
System.Collections Definitions and classes for creating
various collections
System.IO File reading & writing operations

System.Web Support browser/server


communication
System.Web.UI Creates the Page object whenever
an .aspx page is requested
System.Web.UI.web Classes and definitions to create
controls server controls
ASP.NET – class browser

ASP.NET provides a means of exposing the .NET
Framework and its functionality to the WWW

Contains a number of pre-built types that take input
from .NET types and represents them in a form for
the web (such as HTML)

Class browser (over 9000 classes; lists the
namespaces):
ASP.NET

The latest version of ASP is known as ASP.NET

Visual Studio .NET is a developer application used
to create ASP.NET Web applications

There are two main types of Web resources
created with ASP.NET applications
 WebForms are ASP.NET pages within an ASP.NET
application
 Web Services are ASP.NET Web pages that contain
publicly exposed code so that other applications can
interact with them
 Web Services are identified with the file extension .asmx
WebForms

The ASP.NET WebForm is separated into two
logical areas:
 The HTML template
 A collection of code behind the WebForm

The HTML template
 Contains the design layout, content, and the controls
 Creates the user interface, or presentation layer
 Instructs the browser how to format the Web page
 Is created using a combination of HTML controls, HTML
Server controls, Mobile Controls, and ASP.NET controls
Server Controls

HTML Server controls are similar to the HTML
controls, except they are processed by the server

Add runat = "server" to the HTML control to transform
it into an HTML Server control

HTML control: <input type="text">

HTML Server control:
<input type="text" runat="server"/>
<input type=”radio” runat=”server” value=”Yes”/> Yes

Server-side programs can interact with the control
before it is rendered as a plain HTML control and
sent to the browser
ASP.NET Controls

ASP.NET form controls will create the HTML code

ASP.NET Server controls are organized as:
 ASP.NET Form Controls
 Data Validation Controls
 User Controls
 Mobile Controls

ASP.NET controls are usually identified with the prefix
asp: followed by the name of the control

ASP.NET button:
<asp:Button id="ShowBtn" runat="server"
Text="Show the message." />
HTML Server Vs
ASP.NET Server, Controls

ASP.NET form controls can interact with client-side
events such as when the user clicks on a button
 When the event occurs, ASP.NET can trigger a script to
run on the server

ASP.NET form controls also have different
properties than their HTML server control
counterparts
 HTML Server label control

Message1.InnerHTML = "Product 1"
 ASP server label control

Message2.Text = "Product 2"
User Controls

User controls are external files that can be included
within another WebForm

User controls allow you to reuse code across multiple
files

For example, you can create a user control that
displays the a navigation bar

You can use this control on the home page; they are
often used for creating self-contained code, headers,
menus, and footers

User controls replace the functionality of ASP server-
side include pages

They are identified with the file extension .asmx
Other ASP.NET Server Controls

Data validation controls

 A series of controls that validate form data without extensive


JavaScript programming


Mobile controls

 A series of controls that provide form functionality within wireless


and mobile devices


Literal controls

 Page content that is not assigned to a specific HTML control such


as a combination of HTML tags and text to the browser
Server Controls within
Visual Studio .NET

In Visual
Studio .NET most
of the ASP.NET
Server controls are
located on the Web
Forms tab in the
toolbox

Server controls with Visual Studio.NET


The Code Behind

Server programs are written in a separate file known as
the code behind the page

By separating the programming logic and presentation
layer, the application becomes easier to maintain

Only Server controls can interact with the code behind the
page
 Written in any ASP.NET compatible language such as Visual
Basic .NET, C#, Perl, or Java
 Filename is the same as the WebForm filename
 Add a file extension that identifies the language

Visual Basic .NET use .vb (mypage.aspx.vb)

C# use .cs (mypage.aspx.cs)
Code Behind file

The location of the code behind the page is determined
via a property that is set on the first line in the page using
the @Page directive
<%@ Page Language="vb" Codebehind="WebForm1.vb"
Inherits=“MyFirstApp.WebForm1"%>

The @Page directive allows you to set the default
properties for the entire page such as the default
language

The CodeBehind property identifies the path and
filename of the code behind file

The Inherits property indicates that the code behind the
page inherits the page class

This page class contains the compiled code for this page
Compiling the Page Class

The compiled code behind the page is the class
definition for the page
 A class is a named logical grouping of code
 The class definition contains the functions, methods,
and properties that belong to that class

In Visual Studio .NET the process of compiling a
class is called building
 When you build the application, you compile the code
into an executable file
 Visual Studio .NET compiles the code behind the page
into an executable file and places the file in the bin
directory
Page Class Events

The Page Class consists of a variety of
methods, functions, and properties that can be
accessed within the code behind the page

The first time a page is requested by a client, a
series of page events occurs

The first page event is the Page_Init event
which initializes the page control hierarchy

The Page_Load event loads any server
controls into memory and occurs every time
the page is executed
Page class events

Page_init

Page_load

Server_Controls

Page_prerender

Page_Unload
Web Services

Web Services also provide a means to
expose .NET functionality on the web but Web
Services expose functionality via XML and
SOAP (cf: function calls over the web)
Web Services

If your business partner is Course Technology and
you want to query that company’s product catalog
from your Web site, you could:
 Post a link
 Scrape a Web site (use a program to view a Web site and
capture the source code)
 Provide a Web Service to their catalog application

Web Services are used to create business-to-
business applications
 Web Services allow you to expose part or all of your programs
over the Internet. The Web Service source file has the
extension .asmx
 A public registry known as UDDI contains registered public Web
Services. Third party Web Services are available at
http://www.xmethods.com
What is a Web Service?
Small, reusable applications written in XML

Client to Client
- Clients can use XML Web Services to
communicate data

Client to Server
- Clients can send data to and receive
data from servers.

Server to Server
- Servers can share data with each
other.

Service to Service
- web services can work together.
What are the Components of .NET?
.NET Experience

.NET Experiences are XML web services that
allow you to access information across the
internet in an integrated way

Products transitioning into the .NET
experiences are:
 MSN Website
 Visual Studio .NET Website
 Passport Website
.NET Clients

Clients are PCs, handheld computers, Tablet PCs,


game consoles (Xbox), smart phones …

All of them use XML Web Services

.NET client software includes


Windows CE
Windows XP
Windows Embedded
Windows 2000
.NET Services

XML Web Services

Offer a direct means for applications to interact


with other applications

First set of XML Web Services developed are


called .NET My Services (“HailStorm”)
.NET Servers

.NET Enterprise servers are Microsoft's


comprehensive family of server applications for
building, deploying, and managing scalable,
integrated, Web Services and applications

Designed with machine critical performance

Examples of .NET Servers:


MS Commerce Server 2000
MS Exchange Server 2000
.NET Tools

Microsoft Visual Studio .NET and


Microsoft .NET Framework supplies complete
solution for developers to build, deploy and run
XML services

Visual Studio .NET is the next generation of


Microsoft’s popular multi-language development
tool built especially for .NET

Enhances existing languages like Visual Basic


with new OO features

Introduces C#
Web Services Revisited

Web services are platform independent
 Encompasses Windows, Unix, Mac, Linux, even PalmOS

Web services are agnostic of the object model being used
 Compatible with RPC, DCOM, CORBA, and Sun RMI

Web services are loosely coupled
 Unlike tightly-coupled RPC and distributed object systems, which require all the
pieces of an application be deployed at once, you can add clients and servers to
Web-based systems as needed

Web services are built on open standards
 XML, SOAP, WSDL, UDDI, HTTP, RPC

Web services are compatible with existing object models
 Replaces internal "plumbing" of the network RPC wire format transparently to user

Web services permit secure transmission
 HTTPS, SSL
Web Services vs. Traditional Web
Applications

Web services use SOAP messages instead of
MIME messages
 Browsers just need to render web pages; web services
need to do more

Web services are not HTTP-specific
 SOAP messages can be sent using SMTP, raw TCP or
an instant messaging protocol like Jabber

Web services provide metadata describing the
messages they produce and consume.
 XML Schema (XSD) is used to describe various
message structures
Extensible Markup Language
(XML)

XML is the glue that holds .NET together

XML is the defacto standard for data
interoperability.

XML provides a way to put structured data into
a form that can be easily and quickly
transmitted and then interpreted at the other
end

XML looks like HTML, and like HTML, it is
readable and text-based

XML is license-free, platform-independent,
and well supported
Simple Object Access Protocol
(SOAP)

“SOAP provides a simple and lightweight


mechanism for exchanging structured and typed
information between peers in a decentralized,
distributed environment using XML “

A SOAP message is based on XML and contains


the following parts:


The Envelope is the top-level container representing
the message.


The Header is a generic container for added
features to a SOAP message. SOAP defines
attributes to indicate who should deal with a feature
and whether understanding is optional or
mandatory.


The Body is a container for mandatory information
intended for the ultimate message receiver.
SOAP (cont’d)


Soap is the communications protocol for XML Web services.

SOAP is a specification that defines the XML format for messages—and that's
about it – a SOAP implementation will probably include mechanisms for object
activation and naming services but the SOAP standard doesn't specify them

Optional parts of SOAP specification describe how to represent program data as
XML and how to use SOAP to do Remote Procedure Calls

SOAP is much smaller and simpler to implement than many of the previous
protocols.

DCE and CORBA took years to implement, so only a few implementations were
ever released; SOAP, however, can use existing XML Parsers and HTTP
libraries to do most of the hard work, so a SOAP implementation can be
completed in a matter of months – so several implementations for it have been
released (> 70 to date).

SOAP obviously doesn't do everything that DCE or CORBA do, but the lack of
complexity in exchange for features is what makes SOAP so readily available
Web Service Description Language
(WSDL)

A Web Service Description defines all the supported
methods that a Web Service provides.

WSDL is an XML grammar that developers and
development tools use to represent the capabilities and
syntax of a Web Service.

Similar to IDL for COM and CORBA

Imagine you want to start calling a SOAP method provided
by one of your business partners. WSDL specifies what a
request message must contain and what the response
message will look like in unambiguous notation.
Universal Discovery Description and
Integration (UDDI)

UDDI is the yellow pages of Web Services

you can search for a company that offers the services you need, read about the service
offered and contact someone for more information

A UDDI directory entry is an XML file that describes a business and the services it offers.

There are three parts to an entry in the UDDI directory
 "white pages" describe the company offering the service: name, address, contacts, etc.
 "yellow pages" include industrial categories based on standard taxonomies such as the North
American Industry Classification System and the Standard Industrial Classification.
 "green pages" describe the interface to the service in enough detail for someone to write an
application to use the Web service.

UDDI defines a document format and protocol for searching and retrieving discovery
documents - which in turn link to DISCO documents.

DISCO (Discovery of Web Services) is a Microsoft protocol for retrieving the contracts for
Web Services (WDSL documents).
Web application project files
AssemblyInfo.vb Info about the compiled project file stored
in /bin and named project.dll
Global.asax Event handler commands visible to all web
forms in a project
Global.asax.resx Define application resources such as text
strings, images. Can change without
recompiling project.
Global.asax.vb Asp.net code for application events eg
session.start
Project.sln Stores links to all project files
Project.suo VS.NET IDE configuration info for the proj.
Project.vbproj Configuration and build settings for project
files.
Web application project files cont.
Project.vbproj.webinfo URL to project web server
Project.vsdisco Enables search for web services
Styles.css Project style sheet
Web.config Project and folder configuration information
Webform.aspx Web form .aspx file;Html
Webform.aspx.resx Resources in corresponding web form
Webform.aspx.vb Code written for the form (code behind)
Bin\project.dll Compiled project output file (assembly)

Bin\project.pdb Debugging information used by developer


The lab environment.

Each machine is set up to be an IIS server –
http://localhost:1900/…..

You create your web projects with Visual Studio.Net.
VS.NET will create a subdirectory in
c:/inetpub/wwwroot for your project. You must copy this
subdirectory when moving to another machine or
home.

URL
 http://localhost:1900/MyfirstApp/homepage.aspx

Alternative to VS.Net is webmatrix
ASP.NET Vs PHP
Feature PHP ASP.NET
HTML Yes Yes
CSS Yes Yes
‘php Templates’ Yes UserControls
ServerControls No Yes
(buttons,grids etc)

Javascript Yes Yes + Validation controls


Database Conn Yes Yes
Cookies & Sessions Yes Yes
VIEWSTATE No Yes
POSTBACK No Yes
.NET and C#

.NET Platform
Web-based applications can be
distributed to a variety of devices
and desktops

C#
developed specifically for .NET
.NET and C#


.NET platform
 Web-based applications can be distributed to variety of
devices and desktops


C#
 Developed specifically for .NET
 Enable programmers to migrate from C/C++ and Java easily
 Event-driven, fully OO, visual programming language
 Has IDE
 Process of rapidly creating an application using an IDE is
called Rapid Application Development (RAD)
What Is C#?

C# is type-safe object-oriented language

Enables developers to build a variety of secure and
robust applications

It was developed by Microsoft within the .NET
Framework
C#

Language interoperability
 Can interact with software components written in different
languages or with old packaged software written in C/C++

Can interact via internet, using industry standards (SOAP
and XML)
 Simple Object Access Protocol - Helps to share program “chunks”
over the internet


Accommodates a new style of programming in which
applications are created from building blocks available
over internet (reusability)
C# and the .NET IDE


Console applications
 No visual components
(buttons, text boxes, etc.)
 Only text output
 Two types

MS-DOS prompt -Used in Windows 95/98/ME

Command prompt -Used in Windows 2000/NT/XP
Features

Very similar in syntax to C, C++, and Java.


Syntax is highly expressive.


Key features: nullable value type,
enumerations, delegates, lambda expressions,
and direct memory access
Advantages

Interoperability
 “Interop” process enables C# programs to do
almost anything that a native C++ application can
do.

Ease of Use
 Syntax allows for users familiar with C, C++, or
Java to easily start coding in C# very effortlessly.
Advantages (contd)

Reliability
 Progression of versions gives the user the feeling of
reliable mature standard.

Support of Community
 It approval from the ISO and ECMA as well as
development support from Microsoft give the
standard elite standing.
Applications


C# programs run on the .NET Framework which
is an integral component of Windows that
includes a virtual execution system called
common language runtime (CLR).

Likewise C# programs run on a unified set of
class libraries as well.
Source code relationships

The following diagram
illustrates the compile-
time and run-time
relationships of C#
source code files,
the .NET Framework
class libraries,
assemblies, and the
CLR.
Namespaces


Group related C# features into categories

Contain code that can be reused

.NET framework library (FCL) contains
many namespaces

Must be referenced in order to be used

Example: Console feature is in
namespace System
Methods


Building blocks of C# programs

Every program is a class!

The Main method
 Each console or windows application must
have exactly one
Example explained


Using System means that we can use classes from the System
namespace.

namespace is used to organize your code, and it is a container for
classes and other namespaces.

class is a container for data and methods, which brings functionality
to your program.

Another thing that always appear in a C# program, is the Main
method.

Console is a class of the System namespace, which has a
WriteLine() method that is used to output/print text.

● If you omit the using System line, you would have to write
System.Console.WriteLine() to print/output text.
Displaying output

 With C# Console applications



Text output only

Console.Write(“... {0}”, Sum);


Console.WriteLine(“…”);
Getting input

Primitive data types built into C#
(string, int, double, char, long …15 types)

Console.ReadLine( )
 Used to get a value from the user input

Int32.Parse( )
 Converts a string argument to an integer
 Allows math to be performed once the string is
converted

number2 = Int32.Parse( Console.ReadLine( ) );
ASP.NET introduction

ASP.NET is a web application framework developed and
marketed by Microsoft to allow programmers to build
dynamic web sites.

ASP is a development framework for building web pages.

ASP supports many different development models:
 Classic ASP
 ASP.NET Web Forms
 ASP.NET MVC
 ASP.NET Web Pages
 ASP.NET API
 ASP.NET Core
ASP.NET introduction
ASP supports a lot of development models which are as follows:
1. Classic ASP: It is the first server side scripting language developed by
Microsoft.
2. ASP.NET: It is web development framework
3. ASP.NET Core:, it is considered as an important redesign of ASP.NET with
the feature of open-source and cross-platform.
4. ASP.NET Web Forms: These are the event-driven application model
which are not considered a part of the new
ASP.NET Core. These are used to provide the server-side events and
controls to develop a web application.
5. ASP.NET MVC: It is the Model-View-Controller application model which can
be merged with the new ASP.NET Core. It is used to build dynamic
websites as it provides fast development.
6. ASP.NET Web Pages: These are the single page application which can be
merged into ASP.NET Core.
7. ASP.NET API: It is the Web Application Programming Interface(API).
ASP.NET Life Cycle

The page life cycle phases are:
1. Page Request
2. Start
3. Initialization
4. Load
5. Postback event handling
6. Rendering
7. Unloading
ASP.NET - Basic Controls
1. Button Controls
2. Text Boxes and Labels
3. Check Boxes and Radio Buttons
4. List Controls
5. The ListItemCollection
6. HyperLink Control
7. Image Control
Button Controls

ASP.NET provides three types of button control:

Button : It displays text within a rectangular area.

Link Button : It displays text that looks like a hyperlink.

Image Button : It displays an image.

When a user clicks a button, two events are raised: Click
and Command.

Basic syntax of button control:

<asp:Button ID="Button1" runat="server"
onclick="Button1_Click" Text="Click" / >
Text Boxes and Labels

Basic syntax of text control:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Check Boxes and Radio Buttons

Basic syntax of check box:
<asp:CheckBox ID= "chkoption" runat= "Server">
</asp:CheckBox>

Basic syntax of radio button:
<asp:RadioButton ID= "rdboption" runat= "Server"> </asp:
RadioButton>
List Controls

ASP.NET provides the following controls
 Drop-down list,
 List box,
 Radio button list,
 Check box list,
 Bulleted list.
List Controls

Basic syntax of list box control:
<asp:ListBox ID="ListBox1" runat="server"
AutoPostBack="True"
nSelectedIndexChanged="ListBox1_SelectedIndexChang
ed"> </asp:ListBox>

Basic syntax of drop-down list control:
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedInde
xChanged"> </asp:DropDownList>
HyperLink Control

The HyperLink control is like the HTML <a> element.

Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server"> HyperLink
</asp:HyperLink>
Image Control

The image control is used for displaying images
on the web page, or some alternative text, if the
image is not available.

Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
Thank You!

You might also like