Awp Superbank

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

AWP SUPERBANK

#college #c-sharp

Unit 1

What are .NET languages


Explain various features of C# languages
What is .NET Framework?
Explain its architecture in brief
with diagram

The .NET Framework is a software development framework developed by


Microsoft that provides a runtime environment and a set of libraries and
tools for building and running applications on Windows operating systems.
The framework includes a variety of programming languages, such as C#,
F#, and Visual Basic, and supports a range of application types, including
desktop, web, mobile, and gaming applications.

1. The .NET Framework includes two main components: the Common


Language Runtime (CLR) and the .NET Framework Class Library. The
CLR is responsible for managing the execution of code written in any of
the supported languages, while the class library provides a large set of
pre-built functions and classes that can be used to create a wide range
of applications.
2. One of the key advantages of the .NET Framework is its support for a
variety of programming languages. This means that developers can
choose the language that best fits their needs and expertise, while still
being able to use the same set of libraries and tools provided by the
framework.

the following are the components of .Net Framework:

User and program Interfaces


It specifies the type of application that can generated using .Net.
We can create following:
Console application:
These are the application where input and output are
through console command.
There are no forms, no internet connectivity required.
Windows application:
Here input and output are through windows form.
No internet connectivity required.
Web application
Int needs remote server processing, needs internet
connectivity.
Net primarily used to create web application.
Base Class Libraries
.NET frame supports rich base class libraries to provide access to
system functionalities.
BCL is the foundation on which .NET framework application its
components and controls are build.
Using BCL we can create types of application such as windows
application, console application, web application, etc.
Developers just need to import the BCL in their language code and
uses its predefine methods to create application.
CLR Common Language Runtime
It is virtual machine component of .NET framework.
It manages creation, compilation, memory allotment, execution,
garbage collection of .NET application.
It ensures conversion of sources code to MSIL Microsoft
Intermediate Language by compiler
It also ensures the JIT conversion of your MSIL code to machine
code.
CLR provides additional service like memory management,
execution handling garbage collection, security and thread
management.
All programs written in .NET framework irrespective of language are
managed by CLR

C# is object oriented programming language. It provides a lot of features


that are given below:-

1. Simple :- C# is a simple language in the sense that it provides structured


approach, rich set of library functions, data types etc. Unsafe operations
such as direct memory manipulation are not allowed.
2. Modern :- C# programming is based upon the current trend and it is
very powerful and simple for building scalable, interoperable and robust
applications. C# programming is based upon the current trend and it is
very powerful and simple for building scalable interoperable and robust
applications.
3. Object Oriented Programming :- C# is object oriented programming
language i.e it supports data encapsulation, inheritance, polymorphism,
interfaces. OOP’s makes development and maintenance easier where as
in Procedure-oriented programming language it is not easy to manage if
code grows as project size grow.
4. Type Safe :- C# type safe code can only access the memory location
that it has permission to execute. Therefore it improves a security of the
program.
5. Scalable and Updatable :- C# is automatic scalable and updateable
programming language. For updating our application we delete the old
files and update them with new ones.
6. Component Oriented :- C# is component oriented programming
language. It is the predominant software development methodology
used to develop more robust and highly scalable applications.

Explain various types of constructors in C#


- with examples code
A
constructor is used for creating objects of a class. Following is the list of
constructors in C#.

Default constructor

Parameterized constructor

Copy constructor

Static constructor

Private constructor

What is a constructor?

A constructor is a special method that is used to initialize an object. A


constructor is invoked at the time of an object creation. Constructor name
must be the same as its class name. A constructor must have no explicit
return type.

Default Constructor

A constructor without any parameters is called a default constructor. If we


do not create constructor the class will automatically call default constructor
when an object is created.

using System;
language-cs
namespace DefaultConstructor_Demo

public class Customer

public string firstName;

public string lastName;

public Customer()

class Program

static void Main(string[] args)

Customer custormer = new Customer();

custormer.firstName = "Farhan";

custormer.lastName = "Ahmed";

Console.WriteLine("Full Name:"+custormer.firstName+ " "+


custormer.lastName);

Console.ReadLine();

Parameter Constructor

A constructor with at least one parameter is called a parametrized


constructor.

Copy Constructor

The constructor which creates an object by copying variables from another


object is called a copy constructor.

using System;
language-cs
namespace CopyConstructor_Demo

public class Employee

public string firstName;

public string lastName;

public string position;

public int salary;

public Employee()

// Copy constructor.

public Employee(Employee employee)

firstName = employee.firstName;

lastName = employee.lastName;

position = employee.position;

salary = employee.salary;

class Program

static void Main(string[] args)

Employee emp = new Employee();

Employee emp1 = new Employee(emp);

Console.WriteLine("Enter your first name:");

emp1.firstName = Convert.ToString(Console.ReadLine());

Console.WriteLine("Enter your last name:");

emp1.lastName = Convert.ToString(Console.ReadLine());

Console.WriteLine("Enter your position:");

emp1.position = Convert.ToString(Console.ReadLine());

Console.WriteLine("Enter your salary:");

emp1.salary = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("First Name:" + emp1.firstName);

Console.WriteLine("Last Name:" + emp1.lastName);

Console.WriteLine("Position:" + emp1.position);

Console.WriteLine("Salary:" + emp1.salary);

Static Constructor

A static constructor is used to initialize any static data, or to perform a


particular action that needs to be performed once only. It is called
automatically before the first instance is created or any static members are
referenced.

Characteristic of static constructor

A static constructor does not take any access modifiers.


A static constructor does not have a parameter.
A static constructor is called automatically to initialize the class before
the first instance is created or any static members are referenced.
A static constructor cannot be called directly.
The user has no control over when the static constructor is executed in
the program.
A typical use of static constructors is when the class is using a log file
and the constructor is used to write entries to this file.
A class can have only one static constructor.
It can access only static members of a class.

using System;
language-cs
namespace StaticConstructor_Demo

public class Customer

public string firstName;

public string lastName;

public static string discount;

public Customer(string FirstName, string LastName)

firstName = FirstName;

lastName = LastName;

static Customer()

discount = 10+"%";

public void CustomerDetails()

Console.WriteLine("Full Name:{0}", firstName +"


"+lastName );

Console.WriteLine("Discount:{0}",discount + "\n");

class Program

static void Main(string[] args)

Customer c1 = new Customer("Farhan","Ahmed");

Customer c2 = new Customer("Abdul", "Jabbar");

c1.CustomerDetails();

c2.CustomerDetails();

Console.ReadLine();

private constructor
A private constructor is a special instance constructor. It
is generally used in classes that contain static members only. If a class has
one or more private constructors and no public constructors, other classes
(except nested classes) cannot create instances of this class. The use of
private constructor is to serve singleton classes. A singleton class is one
which limits the number of objects created to one. Using private constructor
we can ensure that no more than one object can be created at a time

One use of private constructor is when we have the only static member.
It provides the implementation of singleton class pattern.
Once we provide constructor (private/public/any) the compiler will not
add the no parameter public constructor to any class.

using System;
language-cs
using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace PrivateConstructor_Demo

public class Candidate

private Candidate()

public static int CandidateVisitedForInterview;

public static int CountCandidate()

return ++CandidateVisitedForInterview;

class Program

static void Main(string[] args)

// The following comment line will throw an error because


constructor is inaccessible

//Candidate candidate = new Candidate();

Candidate.CandidateVisitedForInterview = 20;

Candidate.CountCandidate();
Console.WriteLine("Interviewed candidates: {0}",
Candidate.CandidateVisitedForInterview);

Console.ReadLine();

Explain types of Array


all types
one & two dimensional array
Elaborate Array memory representation with an example

Like other programming languages, array in C# is a group of similar types of


elements that have contiguous memory location. In C#, array is an object of
base type System.Array. In C#, array index starts from 0. We can store only
fixed set of elements in C# array.

C# Array Types
There are 3 types of arrays in C# programming:

1. Single Dimensional Array


2. Multidimensional Array
3. Jagged Array

C# Single Dimensional Array


To create single dimensional array, you need to use square brackets [] after
the type.
int[] arr = new int[5];//creating array
language-cs

example

using System;
language-cs
public class ArrayExample

public static void Main(string[] args)

int[] arr = new int[5];//creating array

arr[0] = 10;//initializing array

arr[2] = 20;

arr[4] = 30;

//traversing array

for (int i = 0; i < arr.Length; i++)

Console.WriteLine(arr[i]);

C# - Multidimensional Arrays
C# supports multidimensional arrays up to 32 dimensions. The
multidimensional array can be declared by adding commas in the square
brackets. For example, declares two-dimensional array, [, ,] declares three-
dimensional array, , , , declares four-dimensional array, and so on. So, in a
multidimensional array, no of commas = No of Dimensions - 1.

language-cs
int[,] arr2d; // two-dimensional array

int[, ,] arr3d; // three-dimensional array

int[, , ,] arr4d ; // four-dimensional array

int[, , , ,] arr5d; // five-dimensional array

example
language-cs
int[,] arr2d = new int[3,2]{

{1, 2},

{3, 4},

{5, 6}

};

arr2d[0, 0]; //returns 1

arr2d[0, 1]; //returns 2

arr2d[1, 0]; //returns 3

arr2d[1, 1]; //returns 4

arr2d[2, 0]; //returns 5

arr2d[2, 1]; //returns 6

C# Jagged Arrays: An Array of Array


A jagged array is an array of array. Jagged arrays store arrays instead of
literal values.

A jagged array is initialized with two square brackets [][]. The first bracket
specifies the size of an array, and the second bracket specifies the
dimensions of the array which is going to be stored.

The following example declares jagged arrays.

int[][] jArray1 = new int[2][]; // can include two single-dimensional


arrays

int[][,] jArray2 = new int[3][,]; // can include three two-dimensional


arrays

Example

int[][] jArray = new int[2][];


language-cs
jArray[0] = new int[3]{1, 2, 3};

jArray[1] = new int[4]{4, 5, 6, 7 };

Memory representation
Explain inheritance with example
single inheritance
multiple inheritance (only works using interfaces)

Inheritance is an important pillar of OOP(Object Oriented Programming). It is


the mechanism in C# by which one class is allowed to inherit the
features(fields and methods) of another class.

Important terminology:

Super Class: The class whose features are inherited is known as super


class(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as
subclass(or a derived class, extended class, or child class). The
subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of
the existing class.

How to use inheritance

The symbol used for inheritance is :.

Syntax:

class derived-class : base-class


language-cs
{

// methods and fields

Example: In below example of inheritance, class GFG is a base class, class


GeeksforGeeks is a derived class which extends GFG class and class Sudo
is a driver class to run program.

// C# program to illustrate the


language-cs
// concept of inheritance

using System;

namespace ConsoleApplication1 {

// Base class

class GFG {

// data members

public string name;

public string subject;

// public method of base class

public void readers(string name, string subject)

this.name = name;

this.subject = subject;

Console.WriteLine("Myself: " + name);

Console.WriteLine("My Favorite Subject is: " +


subject);

// inheriting the GFG class using :

class GeeksforGeeks : GFG {

// constructor of derived class

public GeeksforGeeks()

Console.WriteLine("GeeksforGeeks");

// Driver class

class Sudo {

// Main Method

static void Main(string[] args)

// creating object of derived class

GeeksforGeeks g = new GeeksforGeeks();

// calling the method of base class

// using the derived class object

g.readers("Kirti", "C#");

Types of Inheritance in C#

Below are the different types of inheritance which is supported by C# in


different combinations.

1. Single Inheritance: In single inheritance, subclasses inherit the features


of one superclass. In image below, the class A serves as a base class for
the derived class B.
2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the derived class also act as the
base class to other class. In below image, class A serves as a base class
for the derived class B, which in turn serves as a base class for the
derived class C.

3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as


a superclass (base class) for more than one subclass. In below image,
class A serves as a base class for the derived class B, C, and D.

1. Multiple Inheritance(Through Interfaces):In Multiple inheritance, one


class can have more than one superclass and inherit features from all
parent classes. Please note that C# does not support multiple
inheritance with classes. In C#, we can achieve multiple inheritance only
through Interfaces. In the image below, Class C is derived from interface
A and B.

using System;
language-cs
namespace InheritanceApplication {

class Shape {

public void setWidth(int w) {

width = w;

public void setHeight(int h) {

height = h;

protected int width;

protected int height;

// Base class PaintCost

public interface PaintCost {

int getCost(int area);

// Derived class

class Rectangle : Shape, PaintCost {

public int getArea() {

return (width * height);

public int getCost(int area) {

return area * 70;

class RectangleTester {

static void Main(string[] args) {

Rectangle Rect = new Rectangle();

int area;

Rect.setWidth(5);

Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.

Console.WriteLine("Total area: {0}", Rect.getArea());

Console.WriteLine("Total paint cost: ${0}" ,


Rect.getCost(area));

Console.ReadKey();

1. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of


the above types of inheritance. Since C# doesn’t support multiple
inheritance with classes, the hybrid inheritance is also not possible with
classes. In C#, we can achieve hybrid inheritance only through
Interfaces.

Important facts about inheritance in C#

Default Superclass: Except Object class, which has no superclass,


every class has one and only one direct superclass(single inheritance).
In the absence of any other explicit superclass, every class is implicitly a
subclass of Object class.
Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is
because C# does not support multiple inheritance with classes.
Although with interfaces, multiple inheritance is supported by C#.
Inheriting Constructors: A subclass inherits all the members (fields,
methods) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass.
Private member inheritance: A subclass does not inherit the private
members of its parent class. However, if the superclass has
properties(get and set methods) for accessing its private fields, then a
subclass can inherit.

Explain everything on
class
functions
namespace

Class and Object are the basic concepts of Object-Oriented Programming


which revolve around the real-life entities. A class is a user-defined blueprint
or prototype from which objects are created. Basically, a class combines the
fields and methods(member function which defines actions) into a single
unit. In C#, classes support polymorphism, inheritance and also provide the
concept of derived classes and base classes.

Declaration of class
Generally, a class declaration contains only a keyword class, followed by
an identifier(name) of the class. But there are some optional attributes that
can be used with class declaration according to the application requirement.
In general, class declarations can include these components, in order:

Modifiers: A class can be public or internal etc. By default modifier of


the class is internal.
Keyword class: A class keyword is used to declare the type class.
Class Identifier: The variable of type class is provided. The identifier(or
name of the class) should begin with an initial letter which should be
capitalized by convention.
Base class or Super class: The name of the class’s parent (superclass),
if any, preceded by the : (colon). This is optional.
Interfaces: A comma-separated list of interfaces implemented by the
class, if any, preceded by the : (colon). A class can implement more
than one interface. This is optional.
Body: The class body is surrounded by { } (curly braces).

Constructors in class are used for initializing new objects. Fields are
variables that provide the state of the class and its objects, and methods are
used to implement the behavior of the class and its objects.

// declaring public class


language-cs
public class Geeks

// field variable

public int a, b;

// member function or method

public void display()

Console.WriteLine(“Class & Objects in C#”);

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All
the instances share the attributes and the behavior of the class. But the
values of those attributes, i.e. the state are unique for each object. A single
class may have any number of instances.

Example:

As we declare variables like (type name;). This notifies the compiler that we
will use the name to refer to data whose type is type. With a primitive
variable, this declaration also reserves the proper amount of memory for the
variable. So for reference variable, the type must be strictly a concrete class
name. 

Dog tuffy;
language-cs

If we declare a reference variable(tuffy) like this, its value will be


undetermined(null) until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object.

Initializing an object
The new operator instantiates a class by allocating memory for a new object
and returning a reference to that memory. The new operator also invokes
the class constructor.

Example:

// C# program to illustrate the


language-cs
// Initialization of an object

using System;

// Class Declaration

public class Dog {

// Instance Variables

String name;

String breed;

int age;

String color;

// Constructor Declaration of Class

public Dog(String name, String breed,

int age, String color)

this.name = name;

this.breed = breed;

this.age = age;

this.color = color;

// Property 1

public String GetName()

return name;

// Property 2

public String GetBreed()

return breed;

// Property 3

public int GetAge()

return age;

// Property 4

public String GetColor()

return color;

// Method 1

public String ToString()

return ("Hi my name is " + this.GetName()

+ ".\nMy breed, age and color are " +


this.GetBreed()

+ ", " + this.GetAge() + ", " +


this.GetColor());

// Main Method

public static void Main(String[] args)


{

// Creating object

Dog tuffy = new Dog("tuffy", "papillon", 5, "white");

Console.WriteLine(tuffy.ToString());

C# Function
Function is a block of code that has a signature. Function is used to execute
statements specified in the code block. A function consists of the following
components:

Function name: It is a unique name that is used to make Function call.

Return type: It is used to specify the data type of function return value.

Body: It is a block that contains executable statements.

Access specifier: It is used to specify function accessibility in the


application.

Parameters: It is a list of arguments that we can pass to the function during


call.

C# Function Syntax
using System;
language-cs
namespace FunctionExample

class Program

// User defined function without return type

public void Show() // No Parameter

Console.WriteLine("This is non parameterized function");

// No return statement

// Main function, execution entry point of the program

static void Main(string[] args)

Program program = new Program(); // Creating Object

program.Show(); // Calling Function

C# Function: using parameter but no return type


using System;
language-cs
namespace FunctionExample

class Program

// User defined function without return type

public void Show(string message)

Console.WriteLine("Hello " + message);

// No return statement

// Main function, execution entry point of the program

static void Main(string[] args)

Program program = new Program(); // Creating Object

program.Show("Rahul Kumar"); // Calling Function

C# | Namespaces
Namespaces are used to organize the classes. It helps to control the scope
of methods and classes in larger .Net programming projects. In simpler
words you can say that it provides a way to keep one set of names(like class
names) different from other sets of names. The biggest advantage of using
namespace is that the class names which are declared in one namespace
will not clash with the same class names declared in another namespace. It
is also referred as named group of classes having common features. The
members of a namespace can be namespaces, interfaces, structures, and
delegates.

Example
namespace name1
language-cs
{

// C1 is the class in the namespace name1

class C1

// class code

Example Code

// C# program to illustrate the


language-cs
// use of namespaces

// namespace declaration

namespace first {

// name_1 namespace members

// i.e. class

class Geeks_1

// function of class Geeks_1


public static void display()

// Here System is the namespace

// under which Console class is defined

// You can avoid writing System with

// the help of "using" keyword discussed

// later in this article

System.Console.WriteLine("Hello Geeks!");

/* Removing comment will give the error

because no two classes can have the

same name under a single namespace

class Geeks_1

} */

} // ending of first namespace

// Class declaration

class Geeks_2

// Main Method

public static void Main(String []args)

// calling the display method of

// class Geeks_1 by using two dot

// operator as one is use to access

// the class of first namespace and

// another is use to access the

// static method of class Geeks_1.

// Termed as fully qualified name

first.Geeks_1.display();

Unit 2
Write note on AdRotator and calendar with rich controls

The AdRotator control randomly selects banner graphics from a list, which is
specified in an external XML schedule file. This external XML schedule file is
called the advertisement file.

The AdRotator control allows you to specify the advertisement file and the
type of window that the link should follow in the AdvertisementFile and the
Target property respectively.

The basic syntax of adding an AdRotator is as follows:

<asp:AdRotator language-cs
runat = "server" AdvertisementFile = "adfile.xml"
Target = "_blank" />

The Advertisement File


The advertisement file is an XML file, which contains the information about
the advertisements to be displayed.

Extensible Markup Language (XML) is a W3C standard for text document


markup. It is a text-based markup language that enables you to store data in
a structured format by using meaningful tags. The term 'extensible' implies
that you can extend your ability to describe a document by defining
meaningful tags for the application.

XML is not a language in itself, like HTML, but a set of rules for creating new
markup languages. It is a meta-markup language. It allows developers to
create custom tag sets for special uses. It structures, stores, and transports
the information.

Following is an example of XML file:

<BOOK>
language-cs
<NAME> Learn XML </NAME>

<AUTHOR> Samuel Peterson </AUTHOR>

<PUBLISHER> NSS Publications </PUBLISHER>

<PRICE> $30.00</PRICE>

</BOOK>

Like all XML files, the advertisement file needs to be a structured text file
with well-defined tags delineating the data. There are the following standard
XML elements that are commonly used in the advertisement file:

Properties and Events of the AdRotator Class


The AdRotator class is derived from the WebControl class and inherits its
properties. Apart from those, the AdRotator class has the following
properties:

Example

<form id="form1" runat="server">


language-cs
<div>

<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile


="~/ads.xml" onadcreated="AdRotator1_AdCreated" />

</div>

</form>

Calendar and Rich controls


ASP.NET provides a Calendar control that is used to display a calendar on a
Web page. ASP.NET Calendar control displays a month calendar that allows
user to select dates and move to the next and previous months

The Calendar is complex, powerful Web server control that you can use
to add a calendar feature to your web page. We can use Calendar
control to display any date between 0 A.D. and 9999 A.D.

<asp:Calendar ID="Calendar1" runat="server" </asp:Calendar>


language-cs

When rendered to a user's browser, the calendar control generates an HTML


<table> element and a set of associated JavaScript.

The Calendar control can be used to select a single date or multiple dates.
The SelectionMode property is used for this.

The SelectionMode properties are:

The Calendar control presents a single-month view.


When the user clicks a
date, the date becomes highlighted in gray box. You can retried the
selected
day in your code as a DateTime object from the Calendar.SelectedDate
property.

write a note with example about webserver controls


example ListBox drop
down etc

Server Controls are the tags that are understood by the server. There are
basically three types of server controls.

HTML Server Controls - Traditional HTML tags


Web Server Controls - New ASP. NET tags
Validation Server Controls - For input validation
User controls   Controls that you create as ASP.NET Web pages. You
can embed ASP.NET user controls in other ASP.NET Web pages, which
is an easy way to create toolbars and other reusable elements.

ASP.NET HTML Server Controls

ASP.NET provides a way to work with HTML Server controls on the server


side; programming with a set of controls collectively is called HTML
Controls.

These controls are grouped together in the Visual Studio Toolbox in the
HTML Control tab. The markup of the controls is similar to the HTML
control.
These controls are basically the original HTML controls but enhanced to
enable server side processing.
HTML elements in ASP. NET files are, by default, treated as text. To
make these elements programmable, add a runat="server" attribute to
the HTML element. This attribute indicates that the element should be
treated as a server control.

Note:

All HTML server controls must be within a form tag with the runat="server"
attribute. The runat="server" attribute indicates that the form should be
processed on the server. It also indicates that the enclosed controls can be
accessed by server scripts.

The System.Web.UI.HtmlControls.HtmlControl base class contains all of


the common properties. HTML server controls derive from this class.

For example, consider the HTML input control:


The following table describes the HTML server controls:

ASP.NET Web Server Controls

Web server controls are special ASP. NET tags understood by the
server.
Like HTML server controls, Web server controls are also created on the
server and they require a runat="server" attribute to work.
However, Web server controls do not necessarily map to any existing
HTML elements and they may represent more complex elements.
Mostly all Web Server controls inherit from a common base class,
namely the WebControl class defined in
the System.Web.UI.WebControls namespace.

The syntax for creating a Web server control is:


The following table describes the WEB server controls:

ASP.NET Validation Server Controls

After you create a web form, you should make sure that mandatory
fields of the form elements such as login name and password are not
left blank; data inserted is correct and is within the specified range.
Validation is the method of scrutinizing (observing) that the user has
entered the correct values in input fields.
A Validation server control is used to validate the data of input control. If
the data does not pass validation, it will display an error message to the
user.
In ASP. NET you can use ASP. NET Validation Controls while creating the
form and specify what ASP. NET Validation Controls you want to use
and to which server control you want to bind this.
Validation Controls are derived from a common base class and share a
common set of properties and methods. You just have to drag and drop
the ASP. NET Validation Control in the web form and write one line of
code to describe its functionality.
This reduces the developer time from writing JavaScript for each type of
validation. Moreover, through ASP. NET Validation Controls if any invalid
data is entered the browser itself detects the error on the client-side
and displays the error without requesting the server. This is another
advantage because it reduces the server load.

Some Server Validation controls are:

write a note on asp web forms with examples

Web Forms are web pages built on the ASP.NET Technology. It executes on
the server and generates output to the browser. It is compatible to any
browser to any language supported by .NET common language runtime. It is
flexible and allows us to create and add custom controls.

We can use Visual Studio to create ASP.NET Web Forms. It is an IDE


(Integrated Development Environment) that allows us to drag and drop
server controls to the web forms. It also allows us to set properties, events
and methods for the controls. To write business logic, we can choose any
.NET language like: Visual Basic or Visual C#.

Web Forms are made up of two components: the visual portion (the ASPX
file), and the code behind the form, which resides in a separate class file.

Server Controls
The following table contains the server-side controls for the Web Forms.

HTML Controls
These controls render by the browser. We can also make HTML controls as
server control. we will discuss about this in further our tutorial.

Write a brief note on various validator controls with examples


ASP.NET validation controls validate the user input data to ensure that
useless, unauthenticated, or contradictory data don't get stored.

ASP.NET provides the following validation controls:

RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary

RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not
empty. It is generally tied to a text box to force input into the text box.

The syntax of the control is as given:

<asp:RequiredFieldValidator ID="rfvcandidate"
language-cs
runat="server" ControlToValidate ="ddlcandidate"

ErrorMessage="Please choose a candidate"


InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

RangeValidator Control
The RangeValidator control verifies that the input value falls within a
predetermined range.

<asp:RangeValidator ID="rvclass" runat="server" language-cs


ControlToValidate="txtclass"

ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"

MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator Control
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.

<asp:CompareValidator ID="CompareValidator1" runat="server"


language-cs
ErrorMessage="CompareValidator">

</asp:CompareValidator>

RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching
against a pattern of a regular expression. The regular expression is set in the
ValidationExpression property.

<asp:RegularExpressionValidator ID="string" runat="server" language-cs


ErrorMessage="string"

ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side validation.

<asp:CustomValidator ID="CustomValidator1" runat="server"


language-cs
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>

ValidationSummary
The ValidationSummary control does not perform any validation but shows a
summary of all errors in the page. The summary displays the values of the
ErrorMessage property of all validation controls that failed validation.

The following two mutually inclusive properties list out the error message:

ShowSummary : shows the error messages in specified format.


ShowMessageBox : shows the error messages in a separate window.

The syntax for the control is as given:

<asp:ValidationSummary ID="ValidationSummary1" runat="server"


language-cs
DisplayMode = "BulletList" ShowSummary = "true"
HeaderText="Errors:" />

Unit 3
Explain exception handling mechanism with proper syntax and example
Exception Handling in C# is a process to handle runtime errors. We perform
exception handling so that normal flow of the application can be maintained
even after runtime errors.

In C#, exception is an event or object which is thrown at runtime. All


exceptions the derived from System.Exception class. It is a runtime error
which can be handled. If we don't handle the exception, it prints exception
message and terminates the program.
In C#, we use 4 keywords to perform
exception handling:

try
catch
finally, and
throw

try {
language-cs
// statements causing exception

} catch( ExceptionName e1 ) {

// error handling code

} catch( ExceptionName e2 ) {

// error handling code

} catch( ExceptionName eN ) {

// error handling code

} finally {

// statements to be executed

What are State management techniques in ASP .NET? with examples

In an ASP NET application, state management in ASP NET is an object and


preserves type state control. This is because ASP NET applications are
basically stateless. In ASP NET, the information of users is stored and
maintained till the user session ends. Each time the page is posted on the
server, a new instance of the Web page class is created.

There are two types of State management in ASP net. They are :

Server-side 
Client-side

These are further subdivided into the following -

Server-Side
Session
Application
Cache

Client-Side
Cookies 
Viewstate
Control state
Query String
Hidden Field

Session
An important technique to maintain state. It is used to store identity and
information; information is stored in the server using Sessionid.

To start the user session -


Example

protected void btnSubmit_Click(object sender, EventArgs e)


language-cs

Session["UserName"] = txtName.Text;

Response.Redirect("Home.aspx");

Session Event

Two types -

Session starts - Raised every time a new user requests without a session ID.

Example

void Session_Start(object sender, EventArgs e)


language-cs

Session["Master"] = "~/Master.master";

Session end - Raised everytime the user ends the session or a time out
occurs.

Example

void Session_End(object sender, EventArgs e)


language-cs

Response.Write("Session_End");

cookies
One of the smallest but important parts of the ASP NET, it is used to store
the session and application information of the user. It can be constant and
temporary and works with browser requests. The server can read these
cookies from the client-side and perform data abstraction. 

There are two types of cookies that are available -

Persistence - The Persistence cookie works along with Time and Date.

Example 

Response.Cookies["CookiesName"].Value = "Testing Cookies";


language-cs

//setting the expire time

language-cs
Response.Cookies["CookiesName"].Expires = DateTime.Today.AddHours(2);

Non-Persistence - Temporary cookie created with application access and


closed application is discarded.

Example 

Response.Cookies["CookiesName"].Value = "Testing Cookies";


language-cs

What is a theme? How does it work?


ASP.NET themes are a collection of properties that define the appearance of
pages and controls in your Web site. A theme can include skin files, which
define property settings for ASP.NET Web server controls, and can also
include cascading style sheet files (.css files) and graphics. By applying a
theme, you can give the pages in your Web site a consistent appearance.

Global Theme
A Global theme is a theme that is applied to all the web sites on a web
server and includes property settings, and graphics. This theme allows us to
maintain all the websites on the same web server and define the same style
for all the web pages of the web sites.

Skins
A skin file has the file name extension .skin and contains property settings
for individual controls such as Button, Label, TextBox, or Calendar controls.
Control skin settings are like the control markup itself, but contain only the
properties you want to set as part of the theme. For example, the following
is a control skin for a Button control

Cascading Style Sheets


A theme can also include a cascading style sheet (.css file). When you put a
.css file in the theme folder, the style sheet is applied automatically as part
of the theme. You define a style sheet using the file name extension .css in
the theme folder

Themes vs. Cascading Style Sheets


Themes are similar to cascading style sheets in that both themes and style
sheets define a set of common attributes that can be applied to any page.
However, themes differ from style sheets in the following ways:

Themes can define many properties of a control or page, not just style
properties. For example, using themes, you can specify the graphics for a
TreeView control, the template layout of a GridView control, and so on.

Themes can include graphics.

Themes do not cascade the way style sheets do. By default, any property
values defined in a theme referenced by a page's Theme property override
the property values declaratively set on a control, unless you explicitly apply
the theme using the StyleSheetTheme property. For more information, see
the Theme Settings Precedence section above.

Only one theme can be applied to each page. You cannot apply multiple
themes to a page, unlike style sheets where multiple style sheets can be
applied.

CSS
following are the selectors present in CSS:

1. Universal Selector:
The universal selector, indicated by an asterisk ( *),
applies to all element in your page.
The universal selector can be used
to set global settings like a font family. The following
rule set changes
the font for all elements in our page to Arial:

*{
language-css
Font-family: Arial;

2. Type Selector:
The type selector enables us to point to an HTML
element of a specific type. With a type
selector all HTML elements of
that type will be styled accordingly.

h1
language-css
{

Color:Green;

3. ID Selector:
Th id selector always prefixed by a hash symbol (#) and
enables us to refer to a single
element in the page. Within an HTML or
ASPX page, we can give an element a unique
ID using the id attribute.
With the ID selector, we can change the behavior for that single
element, for example:

#IntroText
language-css
{

Font-style: italic;

Because we can reuse this ID across multiple pages in our site, you can use
this rule to
quickly change the appearance of an element that use once per
page, but more than once
in our site, for example with the following HTML
code:
<p id= “IntroText”> I am italic because I have right ID </p>

4. Class Selector:
The class selector enables us to style multiple HTNL
elements through the class
attribute. This is handy when we want to give
the same type of formatting to several
unrelated HTML elements. The
following rule changes the text to red and bold for all
HTML elements that
have their class attributes set to highlight:

.Highlight
language-css
{ font-weight:bold; color:Red; }

Explain Master Page with its uses and working


ASP.NET master pages allow you to create a consistent layout for the pages
in your application. A single master page defines the look and feel and
standard behavior that you want for all of the pages (or a group of pages) in
your application. You can then create individual content pages that contain
the content you want to display. When users request the content pages,
they merge with the master page to produce output that combines the
layout of the master page with the content from the content page.

A master page is an ASP.NET file with the extension .master (for example,
MySite.master) with a predefined layout that can include static text, HTML
elements, and server controls. The master page is identified by a special @
Master directive that replaces the @ Page directive that is used for ordinary
.aspx pages. The directive looks like the following.

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" language-cs


Inherits="MasterPage" %>

How Master Pages Work


Master pages actually consist of two pieces, the master page itself and one
or more content pages.

Master Page
<% @ Master Language="VB" %>
language-cs
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Master page title</title>

</head>

<body>

<form id="form1" runat="server">

<table>

<tr>

<td><asp:contentplaceholder id="Main"
runat="server" />

</td>

<td>

<asp:contentplaceholder
id="Footer" runat="server" />

</td>

</tr>

</table>

</form>

</body>

</html>

Content Pages
You define the content for the master page's placeholder controls by
creating individual content pages, which are ASP.NET pages (.aspx files and,
optionally, code-behind files) that are bound to a specific master page.

language-vb
<%@ Page Language="VB" MasterPageFile="~/MasterPages/Master1.master"
Title="Content Page" %>

Unit 4
\ Explain details about DataReader with example

A data reader provides an easy way for the programmer to read data from a
database as
if it were coming from a stream. The DataReader is the solution
for forward streaming data
through ADO.NET. The data reader is also called
a firehose cursor or forward read-only cursor
because it moves forward
through the data. The data reader not only allows you to move
forward
through each record of database, but it also enables you to parse the data
from each
column. The DataReader class represents a data reader in
ADO.NET.
Similar to other ADO.NET objects, each data provider has a data
reader class for
example; OleDbDataReader is the data reader class for
OleDb data providers. Similarly,
SqlDataReader and ODBC DataReader are
data reader classes for SQL and ODBC data
providers, respectively.
The
IDataReader interface defines the functionally of a data reader and works as
the
base class for all data provider-specific data reader classes such as
OleDataReader.
SqlDataReader, and OdbcDataReader. Figure 5-36 shows
some of the classes that implement
IDbDataReader.

Code for DataReader:

language-cs
SqlCommand myCMD = new SqlCommand("SELECT CategoryID, CategoryName
FROM

Categories;" + "SELECT EmployeeID, LastName FROM Employees",


nwindConn);

nwindConn.Open();

SqlDataReader myReader = myCMD.ExecuteReader();

do {

Console.WriteLine("\t{0}\t{1}", myReader.GetName(0),
myReader.GetName(1));

while (myReader.Read()) Console.WriteLine("\t{0}\t{1}",


myReader.GetInt32(0), myRea

der.GetString(1)); }

while (myReader.NextResult());

myReader.Close();

nwindConn.Close();

WHat is grid view


he GridView control displays the values of a data source in a table. Each
column
represents a field, while each row represents a record. The GridView
control support the
following features:

• Binding to data source controls, such as SqlDataSource.


• Built–in sort
capabilities.
• Built-in update and delete capabilities.
• Built-in paging
capabilities.
• Built-in row selection capabilities.
• Multiple key fields.

Multiple data fields for the hyperlink columns.
• Customizable appearance
through themes and styles.
Sorting allows the user to sort the items in the
GridView control with respect to specific column
by clicking on the columns
header. To enable, sorting, set the AllowSorting property to true.
AllowSorting=”True”
Instead of displaying all the records in the data source
at the same time, the GridView control
can automatically break the records
up into page. To enable paging, set the
AllowPaging=”True”
Also we can set
how many rows we want to see in page.
PageSize-“4”

HeaderStyle :- It configures the appearance of the header row that contains


column titles,
if we’ve chosen to show it (if ShowHeader is true).
➢ RowStyle
:- It configures the appearance of every data row. AlternatingRowStyle If set,
applies additional formatting to every other row. This formatting acts in
addition to the
RowStyle formatting.

➢ SelectedRowStyle :- It configures the appearance of the row that’s


currently selected. This
formatting acts in addition to the RowStyle
formatting.

➢ EditRowStyle :- It configures the appearance of the row that’s in edit


mode. This formatting
acts in addition to the RowStyle formatting.

➢ EmptyDataRowStyle :- It configures the style that’s used for the single


empty row in the
special case where the bound data object contains no
rows.

➢ FooterStyle :- It configures the appearance of the footer row at the


bottom of the GridView,
if we’ve chosen to show it (if ShowFooter is true).

➢ PagerStyle :- It configures the appearance of the row with the page links,
if we’ve enabled
paging (set AllowPaging to true).
➢ BorderStyle :- It
configures the appearance of border style of the Web server control.

AlternatingRowStyle :- It configures the appearance of TableItemStyle object
that enables
us to set the appearance of alternating data rows in a GridView
control.
➢ SelectedValue :- Gets the data key value of the selected row in a
GridView control.

language-cs
string constr = ConfigurationManager.ConnectionStrings[“constr”]

ConnectionString;

using (SqlConnection con = new SqlConnection(str))

using (SqlCommand cmd = new SqlCommand(“SELECT * FROM Customer”))

cmd.Connection = con;

using (SqlDataAdapter Sda = new SqlDataAdapter(cmd) )

DataTable dt = new dataTable();

Sda.fill(dt);

GridView1.DataSource = dt;

GridVie1.dataBind();

What are the application service provider in ASP.NET?


Explain
ASP.NET 4 ships with a number of application services, of which the most
important
ones are:

• Membership: Enables us to manage and work with user accounts in our


system.
• Roles: Enables us to manage the roles that your users can be
assigned to.
• Profile: Enables us to store user-specific data in a back-end
database.
Overview of these services and how they are related to our web
site and the underlying data
stores that the services may use show are as

follows:

A provider is
software that provides a standardized interface between a service and a
data
source. ASP.NET providers are as follows:
✓ Membership
✓ Role
Management
✓ Sitemap
✓ Profile
✓ Session state etc.
At the top of the
diagram you see the ASP.NET 4 web sites and web application that
represent the web sites that you build. These web sites can contain controls
like the login
controls that it turns can talk to the ASP.NET application
services such as membership and
profile. To create a flexible solution, these
services don’t talk to an underlying data source
directly, but instead talk to a
configured provider.
A provider is an interchangeable piece of software that
is designed for a specific task.
For example, in the case of the work with
users in the underlying data store. You can configure
different providers for
some application service depending on your need.
Data Provider model :-
ADO.NET has a set of classes that are used to connect to a specific
data
source. Each set of data interaction classes is called an ADO. NET data
provider.
ADO.NET data provider includes SQL Server Data Provider, Oracle
Data Provider,
OLEDB Data Provider and ODBC Data Provider. The classes
used to connect to a specific
data source includes Connection, Command,
DataReader and DataAdapter.

• Connection is used to establish a connection to a specific data source.



Command is used to execute SQL statements against the data source.

DataReader is used to read data from data source.
• DataAdapter populates
a DataSet and resolves updates with the data source.
Each provider
designates its own prefix for naming classes. Thus, the SQL Server provider
includes SqlConnection and SqlCommand classes, and the Oracle provider
includes
OracleConnection and OracleCommand classes. Internally, these
classes work quite
differently, because they need to connect to different
databases by using different low-level
protocols. Externally, however, these
classes look quite similar and provide an identical set
of basic methods
because they implement the same common interfaces.
Direct data access :-
The most straightforward way to interact with a database is to use
direct
data access. When we use direct data access, we’re in charge of building an
SQL
command (like the ones we considered earlier in this chapter) and
executing it. We use
commands to query, insert, update, and delete
information. The direct data model is well
suited to ASP.NET web pages,
which don’t need to keep a copy of their data in memory
for long periods of
time.
➢ To query information with simple data access, follow these steps :

1. Create Connection, Command, and DataReader objects.


2. Use the DataReader to retrieve information from the database, and
display it in a
control on a web form.
3. Close your connection.
4. Send the page to the user. At this point, the information your user sees
and the
information in the database no longer have any connection, and
all the ADO.NET
objects have been destroyed.

➢ To add or update information, follow these steps :


5. Create new Connection and Command objects.
6. Execute the Command (with the appropriate SQL statement).

What is Data Binding? Explain its types


ASP.NET adds a feature that allows you to skip the repetitive code process
to retrieve
row of information and pop data directly into HTML elements and
fully formatted controls.
It’s called data binding. Data binding, in the context
of .NET, is the method by which controls
on a user interface (UI) of a client
application are configured to fetch from, or update data into,
a data source,
such as a database or XML document.
Prior to .NET, access to data binding
models was limited to databases. Thus, many
database management
systems (DBM) could indirectly access the data source through their
application programming interface (API) without any flexibility in controlling
the data binding
process. This problem is addressed in .NET by providing
fine control of how the data is bound
and the behavior of UI with Windows
Forms and ADO.NET classes in the framework. The
development of Web
applications is simplified by providing data binding capability to Web
pages
using .NET server-side Web controls.
Two types of ASP.NET data binding
exist,
• Single-Value, or “simple” Data Binding:
⎯ You can use single-value
data binding to add information anywhere on an
Asp.NET page.
⎯ Single-
value data binding doesn’t necessary have anything to do with
ADO.NET.

Single-value data binding allows you to take a variable, a property, or an
expression and insert it dynamically into a page.
⎯ Single-value binding also
helps you create templates for the rich data controls.
• Repeated-Value, or
“List” Binding:
⎯ Repeated-value data binding allows you to display an entire
table.
⎯ Unlike single-value data binding, this type of data binding requires a
special
control that supports it.
⎯ Typically, this is a list control such as
CheckBoxList or ListBox, but it can also
be a much more sophisticated
control such as the GridView.
A dictionary collection is a special kind of
collection in which every item is indexed with
a specific key (or dictionary
word).

• This is similar to the way that built-in ASP.NET collections such as Session,
Application,
and Cache work.

• Dictionary collections always need keys. This makes it easier to retrieve


the item we want.
• In ordinary collections, such as the List, we need to find
the item we want by its index
number position, or more often by traveling
through the whole collection until we come
across the right item.

• With a dictionary collection, we retrieve the item we want by using its key.
• Generally, ordinary collections make sense when we need to work with all
the items at
once, while dictionary collections make sense when we
frequently retrieve a single specific
item.
• We can use two basic dictionary-
style collections in .NET.
• The Hashtable collection allows us to store any
type of object and use any type of object
for the key values.
• The
Dictionary collection uses generics to provide the same “locking in” behavior
as the
List collection.
• We choose the item type and the key type upfront to
prevent errors and reduce the amount
of casting code we need to write.

protected void Page_Load(Object sender, EventArgs e)


language-cs
{

if (!this.IsPostBack)

// Use integers to index each item. Each item is a string.

Dictionary<int, string> fruit = new Dictionary<int, string>();

fruit.Add(1, "Kiwi");

fruit.Add(2, "Pear");

fruit.Add(3, "Mango");

fruit.Add(4, "Blueberry");

fruit.Add(5, "Apricot");

fruit.Add(6, "Banana");

fruit.Add(7, "Peach");

fruit.Add(8, "Plum");

MyListBox.DataSource = fruit; // Define the binding for


the list controls.

MyListBox.DataTextField = "Value";

this.DataBind();
// Activate the binding.

Similarities and differences between form view


and DetailsView in asp .net
Similarities between formview and detailsview :-

1. Like DetailsView, FormView also displays a single record from the data
source at a
time.
2. Both show a single record at a time but can include optional pager
buttons that let us
step through a series of records (showing one per
page).
3. Both controls can be used to display, edit, insert and delete database
records but one at
a time. And both support templates, but the
FormView requires them.
4. Both have paging feature and hence support backward and forward
traversal.
ItemTemplate of FormView :-
• ItemTemplate is used to display
the data from data the source in ReadOnly mode.
• The controls
included in an ItemTemplate are controls that only display data, such as
a
Label control.
• The template can also contain command buttons to
change the FormView control’s
mode to insert or edit, or to delete the
current record.
• The ItemTemplate template can include Link Button
controls that change the mode of
the FormView control based on the
Command Name value.
• A CommandName value of New puts the
record into insert mode and loads the
InsertItemTemplate, which allows
the user to enter values for a new record.
• We can add a button with a
CommandName value of Edit to the ItemTemplate template
to put the
FormView control into edit mode.
• A button with a CommandName
value of Delete can be added to the ItemTemplate
template to allow
users to delete the current record from the data source.

Following are some points which shows the difference between FormView
and
DetailsView:
• Like DetailView, FormView also displays a single record
from the data source at a time.
• Both controls can be used to display, edit,
insert and delete database records but one at a
time. Both have paging
features and hence support backward and forward traversal.
• FormView is
a new data-bound control that is nothing but a templated version of
detailsView control.
• The major difference between DetailsView and
FormView is, here user need to define the
rendering template for each item.
• The FormView control provides more formatting and layout options than
DetailsView.
• The DetailsView control can uses elements or elements
to
display bound data whereas FormView can use only templates to display
bound data.
• The FormView control renders all fields in a single table row
whereas the DetailsView
control displays each field as a table row.
• When
compare to DetailsView, the FormView control provides more control over
the
layout.
A FormView control after a data source has been assigned

Write short note on Data Source Controls.


Following are the various data source controls in Ado.Net:
• SqlDataSource:
This data source allows you to connect to any data source that has an
ADO.NET data provider. This includes SQL Server, Oracle, and OLE DB or
ODBC
data sources. When using this data source, you don’t need to write
the data access code.
• AccessdataSource: This data source allows you to
read and write the data in an access
database file(.mdb). However, its uses
are discouraged, because access doesn’t scale
well to large numbers of
users.
• ObjectDataSource: This data source allows you to connect to a
custom data access
class. This is the preferred approach for large-scale
professional web applications, but
it forces you to write much more code.

XmlDataSource: This data source allows you to connect to an XML file.

SiteMapDataSource: This data source allow you to connect to a .sitemap file
that
describes the navigational structure of your website

EntityDataSource: This data source allows you to query a database by using
the LINQ
to Entities feature.
• LinqDataSource: This data source allows you
to query a database by using the LINQ
to SQL feature, which is a similar (but
somewhat less powerful) predecessor to LINQ
to Entities

The SqlDataSource control represents a connection to a relational database


such as AQL
server or Oracle database, or data accessible through OLEDB
or Open Database
Connectivity(ODBC). Connection to data is mode through
teo important properties
ConnectionString and ProviderName.
SqlDataSource control attributes:

The following code provides the basic syntax of the control:


<asp:SqldataSource runat= “server” ID== “MySqlSource” ConnectionString=
‘<%
ConnectionString : EmpconstrT hef ollowingcodeshowsadatasourcecontrolenabledf ord

ConnectionString:Empconstr %>’ SelectionCommand= “SELECT* FROM


EMPLOYEES”
UpdateCommand= “UPDATE EMPLOYEES SET
LASTNAME=@lame” DeleteCommand=
“DELETE FROM EMPLOYEES WHERE
EMPLOYEEID=@eid”

FilterExpression= “EMPLOYEEID >10” >


</asp:SqlDataSource>

Unit 5
What is XML? What are its basic characteristics?
XML is short for Extensible Markup Language. It is a very widely used format
for exchanging
data, mainly because it's easy readable for both humans and
machines. If we have ever written
a website in HTML, XML will look very
familiar to us, as it's basically a stricter version of
HTML. XML is made up of
tags, attributes and values.
Following are basic characteristics of XML :-

XML elements are composed of a start tag (like ) and an end tag (like ).
Content is placed between the start and end tags. If we include a start tag,
we must also
include a corresponding end tag. The only other option is to
combine the two by creating
an empty element, which includes a forward
slash at the end and has no content (like
). This is similar to the syntax for
ASP.NET controls.

• Whitespace between elements is ignored. That means we can freely use


tabs and hard
returns to properly align our information.

• We can use only valid characters in the content for an element. We can’t
enter special
characters, such as the angle brackets (< >) and the
ampersand (&), as content. Instead, we
have to use the entity equivalents
(such as < and > for angle brackets, and & for
the ampersand). These
equivalents will be automatically converted to the original
characters when
we read them into our program with the appropriate .NET classes.

• XML elements are case sensitive, so and are completely different


elements.
• All elements must be nested in a root element. In the
SuperProProductList example, the
root element is . As soon as the root
element is closed, the
document is finished, and we cannot add anything
else after it. In other words, if we omit
the element and start with a element,
we’ll be able to
enter information for only one product; this is because as
soon as we add the closing
, the document is complete.
• Every element
must be fully enclosed. In other words, when we open a subelement, we
need to close it before we can close the parent. is valid,
but isn’t. As a
general rule, indent when we open a new
element because this will allow us
to see the document’s structure and notice if we
accidentally close the
wrong element first.
• XML documents usually start with an XML declaration
like .
This signals that the document contains XML and indicates any special
text encoding.
However, many XML parsers work fine even if this detail is
omitted.

XML REAder
XmlTextReader:
Provides forward-only, read-only access to a
stream of XML data. The current node
refers to the node on which the
reader is positioned. The reader is advanced using any of the
read methods
and properties reflect the value of the current node. The syntax to declare
an
object of this class is as follows:
XmlTextReader reader = new
XmlTextReader (“XML1.xml”);
XmlTextReader provides the following
functionality:
MUQuetionPapers.com
Example:

• Enforces the rules of well-formed XML.


• XmlTextReader does not provide
data validation.
• Checks that DocumentType nodes are well-formed.
XmlTextReader checks the
DTD for well-formedness, but does not validate
using the DTD.
• For nodes where NodeType is
XmlNodeType.EntityReference, a single
empty EntityReference node is
returned (that is, the Value property
is String.Empty).
• Does not expand
default attributes.
String xmlNode= “~\XMLFile.xml”;
XmlReader creader =
XmlReader.Create(xmlNode);
While (xreader.Read())
{
Switch
(xreader.NodeType)
{
Case XmlNodeType.Element;
ListBox1.Items.Add(“<” +
xreader.Name + “>”);
Break;
Case XmalNodeType.Text;
ListBox1.Add(xreader.value);
Break;
Case XmlNode Type.EndElement;
ListBox1.Items.Add(“<”+ wxreader.Name + “>”);
MUQuetionPapers.com
}

}
XmlTextWriter:

XmlTextWriter:

Break;
One of the simplest ways to create or read any XML document is to
use the basic
XmlTestWriter and XmlTextReader classes. You create the
entire XML document by calling
the methods of the XmlTextWriter, in the
right order. To start a document, you always begin
by calling
WriteStartDocument(). To end it, you call WriteEndDocument().
You write the
elements you need, in three steps. First, you write the start tag by calling
WriteStartElement(). Then you write attributes, elements, and text content
inside. Finally, you
write the and tag by calling WriteEndElement().
The
methods you see always work with the current element, so if you call
WriteAttributeString() and follow it up with a call to WriteAttributeString(),
you are adding an
attribute to that element. Similarly, if you use
WriteString(), you insert text content inside the
current element, and if you
use WriteStartelement() again, you write another element, nested
inside the
current element.

What is authentication and authorisation and what is


Windows Authentication
Authentication:

⎯ In ASP.NET there are many different types of authentication procedures for


web
applications. If you want to specify your own authentication methods
then that also
is possible.
⎯ The different authentication modes are
accepted through settings that can be applied
to the applications
web.config file.

⎯ The web.config file is XML-bsed file which allows changing of ASP.NET


behavior
easily.
⎯ ASP.NET provides three different authentication provides:
MUQuetionPapers.com
o Windows
o From
o Passport
✓ Windows: It allows to authenticate user
based on their windows accounts. This
provider uses IIS to perform the
authentication and then asses the authenticated
identity to your code. This
is the default provides for ASP.NET. Syntax:

✓ Forms: It uses custom HTML forms to collect authentication information


and lets
you use your own logic to authenticate users. The users
identification are stored
in a cookie for use during the session. Syntax: ✓
Passport: it uses Microsoft passport service to authenticate users. It
maintain only
username and password. Syntax:

Authorization:
⎯ Authentication and Authorization are two interconnected
security concepts.
⎯ Authentication is a process of identifying a user and
authorization is the
process of checking whether authenticated user has
access to the resources
they requested.
⎯ There are two forms of
authorization available in ASP.NET:
o FileAuthorization: it is performed by the
FileAuthorization Module.
It uses the access control list of the .aspx file to
resolve whether a
user should have access to the file. ACL permissions are
confirmed
for the users windows identity.
o UrlAuthorization: In the
Web.config file you can specify the
authorization rules for various directories
or files using the
element.

Authentication is the process of determining users identities and forcing


those users to prove
they are who they claim to be. Usually, this involves
entering credentials into some sort of
login page or window.
We can use two
types of authentication to secure an ASP.NET website :

1. Forms authentication

2. Windows authentication

3. Forms Authentication :-

In Forms authentication, ASP.NET is in charge of authenticating users,


tracking
them, and authorizing every request. Usually, forms
authentication works in conjunction
with a database where we store
user information, but we have complete flexibility.
To implement forms-
based security, follow these three steps:

4. Set the authentication mode to forms authentication in the web.config


file.

5. Restrict anonymous users from a specific page or directory in our


application.

6. Create the login page.


❖ Web.config Settings :- We define the type of security in the web.config
file by using
the tag.
Example -
<configuration>

...
<system.web>

...

</system.web>

</configuration>

Windows Authentication :-
• In Windows authentication, the web server
forces every user to log in as a Windows
user.
• This system required that all
user have windows user account on the server.
• With Windows
authentication, the web server takes care of the authentication
process.

ASP.NET simply makes this identity available to our code for our security
checking.
• When we use Windows authentication, we force users to log into
IIS before they’re
allowed to access secure content in our website.
• The
user login information can be transmitted in several ways, but the end result
is
that the user is authenticated using a local Windows account.
To
implement Windows-based security with known users, we need to follow
three steps:

1. Set the authentication mode to Windows authentication in the


web.config file.
2. Disable anonymous access for a directory by using an authorization rule.
3. Configure the Windows user accounts on our web server.
❖ Web.config
Settings :- To use Windows authentication, we need to make sure the
element is set accordingly in our web.config file.
Example –
<configuration>

<system.web>

...

</system.web>
</configuration>

• At the moment, there’s only one authorization rule, which uses the
question mark to refuse
all anonymous users. This step is critical for
Windows authentication (as it is for forms
authentication). Without this step,
the user will never be forced to log in.
• We can also add and elements to
specifically allow or restrict users from
specific files or directories. Unlike
with forms authentication, we need to specify the name
of the server or
domain where the account exists.
Example –

Form Authentication is a wonderful approach, if you are implementing your


own
authentication process using a back-end database and a custom page.
But if you are creating a
web application for a limited number of users who
are already part of a network domain then
Windows Authentication is
beneficial and the preferred choice for authentication. Windowsbased

authentication is manipulated between the Windows server and the client


machine.
The ASP.NET applications resides in Internet Information Server
(IIS). Any user's web
request goes directly to the IIS server and it provides
the authentication process in a Windowsbased

authentication model. This type of authentication is quite useful in an


intranet
environment in which uses are asked to log into a network.
In this
scenario, you can utilize the credentials that are already in place for the
authentication and authorization process. This authentication is performed
by IIS. It first
accepts user's credentials from the domain login
"Domain\UserName and Password". If this
process fails then IIS displays an
error and asks to re-enter the login information.
To configure Asp.NET to use
windows authentication uses the following code:
<system.web>
</system.web>
Advantage of Windows Authentication:
• It relies and allows
the user to use existing Windows Accounts.
• Establishes the foundation for
Uniform Authentication model for multiple types of
applications.
• From
developer's point of view, easy to implement.
Disadvantage of Windows
Authentication:
• Applicable to Microsoft platforms only.
• No custom
control over this platform provided authentication process.

write a short note on AJAX


Asynchronous JavaScript and XML can be defined as a set of users in
building websites
and web applications. Identifying specific purpose in web
development applications is the best
way to understand Ajax. The main work
of Ajax is to update the content asynchronously means
in user’s web page
whole content need not be reloaded and only the required field is reloaded.
XML is a markup language means these are coded languages to annotate
parts of a web
document which gives web browsers instructions about
understanding and displaying the user
content.
It combines various
programming tools like JavaScript, HTML, DHTML, XML
(extensible markup
language), CSS (cascading style sheets), DOM (document object model)
and
Microsoft object.
MUQuetionPapers.com
Ajax was developed by Microsoft
outlook web applications in 1999 but the complete
usage of Ajax came into
the picture after 6 years. The name Ajax was named by Jesse James
Garrett
in February 2005. Before the naming of Ajax, it is called an XML HttpRequest
scripting
object which runs as MSXML library.
The acronym of Ajax is
Asynchronous JavaScript and XML. It can be defined as a path
in which the
user uses JavaScript to communicate with a web server to get a query
generated
response and to provide it on the webserver without the user
leaving the current page.
Advantages:

1. Reduces the server traffic and increases the speed.

2. Ajax is responsive and time taken is also less.

3. Form validation.

4. Bandwidth usage can be reduced.

5. Asynchronous calls can be made this reduces the time for data arrival.
Disadvantages:

6. Open-source.

7. Active x request is created only in internet explorer and newly created


web browser.

8. For security reason, you can only access information from the web host
that serve

pages. Fetching information from other servers is not possible with Ajax.

The ASP.NET AJAX control toolkit is a joint project between Microsoft and
the
ASP.NET community. It contains of dozens of controls that use the
ASP.NET AJAX libraries
to create sophisticated effects. The ASP.NET AJAX
control toolkit is completely free. It
includes full source code, which helpful if
you are ambitious enough to want to create your
own custom controls that
use ASP.NET AJAX features.

It uses extenders that enhance the standard AP.NET web controls. That
way, you don’t
have to replace all the controls on your web pages instead,
you simply plug in the new bits of
functionality that your need. Installing the
ASP.NET AJAX control toolkit. You can download
the ASP.NET AJAX control
toolkit from http://ajaxcontroltoolkit.codeplex.com. Click the
download tab,
and find the toolkit for the latest version of .NET. After you downloaded this
ZIP file, you can extract the files it contains to a more permeant location on
your hard drive.

After installation of toolkit, all the component from AjaxControlToolkit.dll will


appear
in the list in the choose toolbox items dialog box. ASP.NET AJAX
control toolkit, currently
includes about 50 components. The easiest way to
start experimenting with other controls is to
surf to
www.asp.net/ajaxlibarary/act_tutorials.ashx, where you will find a reference
that
describe each control.
Some of the controls are like AutoComplete,
Color Picker, calendar, Watermark, Modal
Popup extender, slideshow
Extender and more of the useful control. The ASP.NET AJAX
control toolkit is
now maintained by DevExpress team. The current version of ASP.NET AJAX
toolkit is v16.1.0.0. there are lot of new enhancement in the current version
from new controls
to bug fixes in all controls.

Give brief information on Accordion control with


appropriate properties.
The main Accordion features include:
• Unlimited number of hierarchy levels

(AccordionControl.Elements, AccordionControlElement.Elements).
• Items
and groups can display images and text in their headers
(AccordionControlElementBase.Image,
AccordionControlElementBase.ImageIndex,
AccordionControlElementBase.Text)
• Items can display custom controls in
an expandable area below their headers
(AccordionControlElementBase.ContentContainer).
• Load items' content
dynamically

(AccordionControl.HasContentContainer,
AccordionControl.GetContentContainer).
• One or multiple elements can be
expanded simultaneously

(AccordionControl.ExpandElementMode)
• Context buttons in item and
group headers

(AccordionControl.ItemContextButtons, AccordionControl.GroupContextButt
ons and AccordionControl.ContextButtonCustomize).
• Custom controls in
item headers (AccordionControlElementBase.HeaderControl).
• Item
selection feature (AccordionControl.AllowItemSelection) - Allows you to
highlight a clicked item.
• Item and group expanding/collapsing animation
(AccordionControl.AnimationType)
• The built-in search box
(AccordionControl.ShowFilterControl) - Allows you to filter
items based on
the search text.
• Support for an external search box (SearchControl).
Gets
or sets the default action description of the control for use by accessibility
client
applications. Inherited from Control.

You might also like