Dot Net Notes
Dot Net Notes
Topics:
.Net Framework |OOPs with C#
[Type here]
Q1. What is .NET Framework? Explain its architecture with help of diagram.
.NET Framework is a platform created by Microsoft for building, deploying, and running applications
and services that use .NET technologies, such as desktop applications and Web services.
It is a platform for application developers.
It is a Framework that supports Multiple Language and Cross language integration.
It has IDE (Integrated Development Environment).
Framework is a set of utilities or can say building blocks of our application system.
.NET Framework provides interoperability between languages i.e. Common Type System (CTS).
.NET Framework also includes the .NET Common Language Runtime (CLR), which responsible
for maintaining the execution of all applications developed using the .NET library.
The .NET Framework consists primarily of a gigantic library of code.
Components of the .Net Framework:
User Interface and Program:
We can create various type of application using .net framework such as
Console Application
Windows Application
Web application
Base class Library:
Base class library is one of component of .Net Framework. It supplies a library of base classes
that we can use to implement applications quickly.
[Type here]
Much of the functionality in the base framework classes resides in the vast namespace called
System.
We can use the base classes in the system namespaces for many different tasks including:
o Input/output Operations.
o String handling.
o Managing arrays, lists, maps etc.
o Accessing files & file systems.
o Accessing the registry.
o Security.
o Windowing.
o Windows messages.
o Database Management.
o Drawing.
o Managing errors & exceptions.
[Type here]
Common Type System (CTS) describes a set of types that can be used in different .Net
languages in common. That is, the Common Type System (CTS) ensure that objects written in
different .Net languages can interact with each other. For Communicating between programs
written in any .NET complaint language, the types have to be compatible on the basic level.
These types can be Value Types or Reference Types. The Value Types are passed by values
and stored in the stack. The Reference Types are passed by references and stored in the heap.
CLS
It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS.
MSIL
It is language independent code. When you compile code that uses the .NET Framework
library, you don't immediately create operating system - specific native code.
Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL
code is not specific to any operating system or to any language.
Functions of the CLR
o Garbage Collector
o Exception handling
o Type safety
o Memory management (using the Garbage Collector)
o Security
o Improved performance
Example:
using System;
namespacefirst_space
{
classnamespace_cl
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespacesecond_space
{
classnamespace_cl
[Type here]
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
classTestClass
{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_clsc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
Alias of Namespace:
using A=System.Console;
class Test
{
static void Main()
{
A.Write("Craetion of Alias");
A.ReadKey();
}
}
Value Type
[Type here]
Value type variables can be assigned a value directly. They are derived from the class
System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int type,
the system allocates memory to store the value.
Reference Type
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types
can refer to a memory location. If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this change in value. Example of built-in
reference types are: object, dynamic, and string.
Q6. Explain the implicit and explicit conversion of data types with examples.
The process of converting from one data type to another data type is called conversion.
Conversion can be 2 types as follows:
[Type here]
When one type of data is assigned to another type of variable, an implicit type conversion will
take place automatically if
o The two types are compatible.
o The destination type has a range that is greater than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int
type is always large enough to hold all valid byte values, and both int and byte are compatible
integer types, so an implicit conversion can be applied.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other.
For example, the following program is perfectly valid since long to double is a widening
conversion that is automatically performed.
using System;
classLtoD {
static void Main()
{
long L;
double D;
L = 100123285L;
D = L;
Console.WriteLine("L and D: " + L + " " + D);
}
}
Although the implicit type conversions are helpful, they will not fulfil all programming needs
because they apply only to widening conversions between compatible types. For all other cases
we must employ a cast. A cast is an instruction to the compiler to convert the outcome of an
expression into a specified type. Thus, it requests an explicit type conversion.
[Type here]
Here, even though x and y are of type double, the cast converts the outcome of the expression
to int. The parentheses surrounding x / y are necessary. Otherwise, the cast to Int would apply
only to the x and not to the outcome of the division.
The cast is necessary here because there is no implicit conversion from double to int. When a
cast involves a narrowing conversion, information might be lost.
Q7. Explain Boxing and Unboxing with reference to value type and reference type.
Boxing:
Any type, value or reference can be assigned to an object without explicit conversion. When a
compiler fined a value where it needs a reference type, it creates an object ‘box’ into which it
places the value of the value type.
Example:-
int m = 10;
object om = m;
When executed, this code creates a temporary reference _type ‘box’ for the object on heap.
We can also use a C-style cast for boxing.
int m = 10;
object om = (object) m;
Note that the boxing operation creates a copy of the value of the m integer to the object om.
Both the variables exist but the value of om resides on the heap. This means that the values
are independent of each other.
Example
int m =10;
object om = m;
m = 20;
Console.WriteLine(m); // m= 20
Console .WriteLine(om); //om=10
Unboxing:
Unboxing is the process of converting the object type back to the value type. Remember that
a variable can be unboxed only if it has been previously boxed. In contrast to boxing, unboxing
is an explicit operation.
Example:-
int m = 100;
object om = m; //boxing
int n = (int) om; //unboxing
When performing unboxing, C# checks the value type we request is actually stored in the object
under conversion. Only if it is, the value is unboxed.
Q8. List and explain the comparison and logical operators in C#.
Comparison operators:
It is also called as relational operator. They are used to compare at least two operands.
Below is the list of relational operator as follows:
[Type here]
Logical operators
Logical operators are used to combine two or more condition. Below is list of logical operator
used in C#/
Q9. Explain flow control, explain what is break and continue statement
The statements inside your source files are generally executed from top to bottom, in the order
that they appear. Control flow statements, however, break up the flow of execution by
employing decision making, looping, and branching, enabling your program to conditionally
execute particular blocks of code.
Break Statement
The break statement is used to exit from loops and switch statements. The break statement
terminates the execution control from a loop or a switch statement to the next statement after
the loop or switch statement.
The general format is:
[Type here]
}
Console.WriteLine(" ");
}
}
}
Continue Statement
The continue statement causes early iteration of a loop. It skips the remaining statements
after the continue statement and moves the execution control to the next iteration of the loop.
The general format is:
using System;
class demo
{
public static void Main()
{
for(int i=1;i<=25;i++)
{
if(i%2!=0)
{
continue;
}
else
Console.Write(" "+i);
}
}
}
Use the break keyword to stop the loop and the continue keyword to skip one loop cycle and
continue to the next.
using System;
[Type here]
Number 1
Number 2
Number 3
Number 4
Demonstrating the use of continue.
Number 1
Number 2
Number 3
Number 4
Number 6
Example:
classSwitchEg
{
static void Main(string[] args)
{
const string myName = "karli";
const string sexyName = "angelina";
const string sillyName = "ploppy";
string name;
Console.WriteLine("What is your name?");
name = Console.ReadLine();
switch (name.ToLower())
{
casemyName:
Console.WriteLine("You have the same name as me!");
break;
[Type here]
casesexyName:
Console.ReadKey();
}
}
This loop will cycle through each element, placing it in the variable <name> in turn, without
danger of accessing illegal elements. We don’t have to worry about how many elements are in
the array, and we can be sure that we get to use each one in the loop.
The main difference between using this method and a standard for loop is that foreach gives
us read-only access to the array contents, so we can’t change the values of any of the
elements.
Example
using System;
class Abc
static void Main(string[] args)
{
string[] friendNames = { "Robert Barwell", "Mike Parry", "Jeremy Beacock" };
Console.WriteLine("Here are {0} of my friends:", friendNames.Length);
foreach (string friendName in friendNames)
{
Console.WriteLine(friendName);
}
Console.ReadKey();
}
[Type here]
The foreach statement repeats a group of embedded statements for each element in an array
or an object collection. You do not need to specify the loop bounds minimum or maximum.
Example:
int j = 0;
int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in tempArr )
{
j=j+i;
}
classnumadd
{
public static void Main()
{
int[][] x=new int[4][];
x[0]=new int[2]{5,13};
x[1]=new int[3]{7,8,11};
x[2]=new int[4]{2,3,4,5};
x[3]=new int[1]{9};
for(int i=0;i<4;i++)
{
for(int j=0;j<x[i].Length;j++)
[Type here]
{
Console.Write(x[i][j]+"\t");
}
Console.Write("\n");
}
class Program
{
static void Main(string[] args)
{T
ryReftr = new TryRef();
int y = 5;
Console.WriteLine("The value of y before the function call: " + y);
tr.cube(ref y);
Console.WriteLine("The value of y after the function call: " + y); Console.ReadLine();
}
}
Output Parameter:
Sometimes we do not want to give an initial value to the parameter; in this case we use the out
parameter. The declaration of the out parameter is the same as the ref parameter. But it is
used to pass the value out of a method. Now we look at the
classAbc
{
public int mul(int a, out int b)
{
b = a * a;
return b;
}
}
class Program
[Type here]
{
static void Main(string[] args)
{
tryout to = new tryout();
intx,y;
x = to.mul(10, out y);
Console.WriteLine("The output is: "+x);
Console.ReadLine();
}
}
Structure Class
It is value type It is reference type.
Structure stored in stack memory. Class stored in heap memory.
Does not consist of parametrized Consist of parametrized constructor.
constructor.
Does not allow inheritance. Allow inheritance.
[Type here]
Does not consist of destructor. Consist of destructor.
Structure created with help of struct Classes created with the help of class
keyword. keyword.
Example:- Example:-
struct Book class Abc
{ {
} }
class Abc
{
public static void main()
{
Console.WriteLine((int)Days.Wed);
Console.WriteLine((Days)4);
}
}
Two types
Compile time polymorphism
Runtime time polymorphism
[Type here]
Q19. What are sealed classes and sealed methods? Why are they used?
The methods declared with a sealed keyword in its header are known as sealed methods. Such
method provides a complete implementation to its base class virtual method using the override
keyword.
Characteristics
A method cannot be defined as sealed unless that method is an override of a method in its
base class.
A sealed method cannot be overridden further.
Sealed methods are useful to avoid problems caused by overriding the existing functionality.
It prevents the user from changing the internal functionality of a class.
Example:
using System;
class A
{
public virtual void F()
{
Console.WriteLine("A.F");
}
public virtual void G()
{
Console.WriteLine("A.G");
}
}
class B: A
{
sealed override public void F()
{
Console.WriteLine("B.F");
}
override public void G()
{
Console.WriteLine("B.G");
}
}
class C: B
{
override public void G()
{
Console.WriteLine("C.G");
}
}
The class B provides two override methods: an F method that has the sealed modifier and a G
method that does not. B's use of the sealed modifier prevents C from further overriding F.
Sealed Classes:
Generally if we create classes we can inherit the properties of that created class in any class
without having any restrictions.
[Type here]
In some situation we will get requirement like we don’t want to give permission for the users to
derive the classes from it or don’t allow users to inherit the properties from particular class.
For that purpose we have keyword called “sealed” in OOPS.
When we defined class with keyword “Sealed” then we don’t have a chance to derive that
particular class and we don’t have permission to inherit the properties from that particular class.
A sealed class cannot be inherited.
It is an error to use a sealed class as a base class.
Use the sealed modifier in a class declaration to prevent inheritance of the class.
It is not permitted to use the abstract modifier with a sealed class.
Example:
using System;
sealed class MyClass
{
public int x;
public int y;
}
classMainClass
{
public static void Main()
{
MyClassmC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Q20. What are the rules in defining a constructor? Explain static constructor with example.
Rules for constructor:
A constructor should have the same name as that of its class.
Constructors can take any number of arguments.
Constructor cannot return any value.
A static constructor is used to initialize static variables of a class. It is declared using the static
keyword. A class can have only one static constructor.
Static Constructor:
The general syntax of a static constructor is shown below.
staticclassname()
{
//static member initializations;
}
Also note that a static constructor is parameter less and no access modifiers are allowed
with its declaration. The exact timing of static constructor execution is implementation-
dependent, but is subject to the following rules:
The static constructor for a class executes before any instance of the class is created.
[Type here]
The static constructor for a class executes before any of the static members for the class
are referenced.
The static constructor for a class executes after the static fields initializes for the class.
The static constructor for a class executes at most one time during a single program
execution.
Example:
class A
{
static A()
{
Console.WriteLine("static constructor A is invoked");
}
public static void Main()
{
}
}
Q21. Explain various Types of Constructors in C#
Default and Parameterized
When constructor does not accept any parameter then it is referred as default constructor or
zero parametrized.
When constructor accepts the parameter then it is referred as parametrized constructor.
Example:
using System;
class test
{
double length, breadth;
public test()
{
Console.WriteLine("default cons");
}
public test(double l, double b)
{
//Console.WriteLine("paramaterized cons");
length = l;
breadth = b;
}
public double area()
{
return (length * breadth);
}
}
classtestmain
{
[Type here]
public static void Main()
{
testdefaultcon =new test();//calls default cons
test t1 = new test(10.05, 100.45);
double result = t1.area();
Console.WriteLine("area of rectangle-->" + result);
Console.ReadLine();
}
}
Private constructor
Private constructors are used to restrict the instantiation of object using ‘new’ operator.
A private constructor is a special instance constructor. It is commonly used in classes that
contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside
if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class having
private constructor.
Example:
using System;
class test
{
private test()
{
Console.WriteLine("private cons ");
}
public test(int x)
{
Console.WriteLine("non private cons--->"+ x);
}
}
classtestmain
{
public static void Main()
{
test t1 = new test();//Error'test.test()' is inaccessible due to its protection level
test t2 = new test(10);
Console.ReadLine();
}
}
Static Constructor
There can be only one static constructor in the class.
[Type here]
The static constructor should be without parameters.
It can only access the static members of the class.
There should be no access modifier in static constructor definition.
Example:
using System;
class test
{
static int x;
static test()
{
Console.WriteLine("static cons ");
x = 10;//set the values for static member here
}
public static void show()
{
Console.WriteLine("show of x--->" + x);
}
}
classtestmain
{
public static void Main()
{
test.show();
Console.ReadLine();
}
}
Copy constructor
When constructor accepts the object as parameter then it is referred as copy constructor.
Example:
using System;
class test
{
double length, breadth;
public test()
{
Console.WriteLine("default cons");
}
public test(double l, double b)
{
//Console.WriteLine("paramaterized cons");
length = l;
breadth = b;
}
public test(test t1)
[Type here]
{
length = t1.length;
breadth = t1.breadth;
}
public double area()
{
return (length * breadth);
}
}
classtestmain
{
public static void Main()
{
testdefaultcon = new test();//calls default cons
test t1 = new test(10,10);
double result = t1.area();
Console.WriteLine("area of rectangle t1-->" + result);
test t2 = new test(20, 20);
double result1 = t2.area();
Console.WriteLine("area of rectangle t2-->" + result1);
test t3 = new test(t2);
doubleresult_copy = t3.area();
Console.WriteLine("area of rectangle t3 is copy_con of t2-->" + result_copy);
Console.ReadLine();
}
}
}
protected int width;
[Type here]
protected int height;
}
Example:
interface I1
[Type here]
{
void A();
}
interface I2
{
void A();
}
class C : I1, I2
{
public void I1.A()
{
Console.WriteLine("A() from I");
}
void I2.A()
{
Console.WriteLine("A() from I2");
}
}
Q24. Explain the similarities and differences between Interfaces and Abstract classes
Similarities:
Both abstract classes and interfaces may contain members that can be inherited by a derived
class.
Neither interfaces nor abstract classes may be directly instantiated, but we can declare
variables of these types. If we do, we can use polymorphism to assign objects that inherit from
these types to variables of these types.
In both cases, we can then use the members of these types through these variables, although
we don’t have direct access to the other members of the derived object.
Differences:
Derived classes may only inherit from a single base class, which means that only a single
abstract class can be inherited directly (although it is possible for a chain of inheritance to
include multiple abstract classes). Conversely, classes can use as many interfaces as they
want
Abstract classes may possess both abstract members and non-abstract members (these
possess a code body, and can be virtual so that they may be overridden in the derived class).
Interface members conversely, must be implemented on the class that uses the interface they
do not possess code bodies.
Moreover, interface members are by definition public but members of abstract classes may
also be private (as long as they aren’t abstract), protected, internal, or protected internal (where
protected internal members are accessible only from code within the application or from a
derived class). In addition, interfaces can’t contain fields, constructors, destructors, static
members, or constants.
Q25. Explain method overriding with example
Method overriding in C# is achieved through inheritance.
If a class is inherited by a derived class, then the derived class can override the base class
method. This concept is termed as Method Overriding.
[Type here]
Method Overriding is implemented in C# using the keywords virtual and override. The base
class method that has to be overridden must be marked as virtual or abstract (if the base class
is an abstract class).
The derived class method that overrides the base class method should be marked with the
keyword override.
Example:
using System;
class A
{
public virtual void Test() { Console.WriteLine("A::Test()"); }
}
class B : A
{
public override void Test() { Console.WriteLine("B::Test()"); }
}
class C : B
{
public override void Test() { Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output --> "A::Test()"
b.Test(); // output --> "B::Test()"
c.Test(); // output --> "C::Test()"
a = new B();
a.Test(); // output --> "B::Test()"
b = new C();
b.Test(); // output --> "C::Test()"
Console.ReadKey();
}
}
[Type here]
A subclass inherits methods from a base class. Sometimes, it is necessary for the subclass to
modify the methods defined in the base class. This is referred to as method overriding.
This can be achieved by using the virtual and override keywords. We have to use the virtual
keyword for the method which in base class and override keyword for the method in subclass.
By default functions are not virtual in C# and so you need to write “virtual” explicitly.
classtest:demo
{
new public void disp()
{
System.Console.WriteLine("From disp method of derived class");
}
public static void Main()
{
[Type here]
t.disp();
}
}
Q28. What is the difference between overriding methods and hiding methods?
Overriding methods:
In method overriding we can override a method in base class by creating similar method in
derived class this can be achieved by using inheritance principle and using “virtual & override”
keywords.
If we want to override base class method then we need to declare base class method with
“virtual” keyword and the method which we created in derived class to override base class
need to declare with “override” keyword like as shown below
Example:-
classSampleA
{
public virtual void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
classSampleB:SampleA
{
public override void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}
Hiding methods:
To hide base class methods in derived classes we can declare derived class methods with new
keyword. To use new keyword we need to write the code like as shown below
Example:-
classSampleA
{
public void Show()
{
[Type here]
Console.WriteLine("Sample A Test Method");
}
}
classSampleB:SampleA
{
public new void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
An Abstract class is a non-instantiable class which is either partially implemented, or not at all
implemented. It can have abstract methods as well as non-abstract methods. Abstract classes
require subclasses to provide implementations for the abstract methods. It provides default
functionality to its sub classes.
Static class
A static class is class whose objects cannot be created and must contain only static members.
Sealed class
A sealed class is a class which cannot be inherited. In C#, the sealed modifier is used to define
a class as sealed.
Partial class
It is possible to split the definition of a class over two or more source files. Each source file
contains a section of the type or meth
Q30. Why exception handling is required? Write syntax for user define exception?
Exception handling:
The mechanism of Exception Handling is throwing an exception and catching it C# uses try-
catch block. Code which may give rise to exceptions is enclosed in a try block, and
[Type here]
Catch block catches that exception and handles it appropriately. The try block is followed by
one or more catch blocks.
Basic syntax:
try
{
//programming logic(code which may give rise to exceptions)
}
catch (Exception e)
{
//message on exception
}
finally
{
// always executes
}
Try:A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
Catch:A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
Finally:The finally block is used to execute a given set of statements, whether an exception is
thrown or not thrown. For example, if you open a file, it must be closed whether an exception
is raised or not.
Example:
using System;
classtryCatch
{
public static void Main()
{
int k=0;
try
{
int n= 10/k;
Console.WriteLine(”n=” + n);
}
catch(Exception e)
{
Console .WriteLine (“Division By zero exception”);
}
Console.WriteLtne(”Statement executed after Exception because of try catch”);
}
[Type here]
Unit-II
Topics:
Advance C# |Asp.Net |CSS
[Type here]
for any other programs (these have .exe file extension) and libraries (which have .dll extension)
for use by other applications.
In addition to containing CIL, assemblies also include Meta information (that is, information about
the information contained in the assembly, also known as metadata) and optional resources
(additional data used by the CIL, such as sound files and pictures). The Meta information
enables assemblies to be fully self-descriptive.
We need no other information to use an assembly, meaning we avoid situations such as failing
to add required data to the system registry and so on, which was often a problem when
developing with other platforms.
This means that deploying applications is often as simple as copying the files into a directory on
a remote computer. Because no additional information is required on the target systems, we can
just run an executable file from this directory and (assuming the .NET CLR is installed) we’re
good to go. Of course, we won’t necessarily want to include everything required to run an
application in one place.
We might write some code that performs tasks required by multiple applications. In situations
like that, it is often useful to place the reusable code in a place accessible to all applications. In
the .NET Framework, this is the global assembly cache (GAC). Placing code in the GAC is
simple we just place the assembly containing the code in the directory containing this cache.
MSIL
It contains Intermediate language code.
Resources
It contains bitmaps, icons, audios and other types of resources .
[Type here]
However, we never need to clear this memory manually. As soon as our reference to an object
goes out of scope (or our application ends), the object becomes available for garbage
collection. The garbage collector runs periodically inside the CLR, automatically reclaiming
unused memory for inaccessible objects.
The .NET Framework provides automatic memory management called garbage collection. A
.NET program that runs in a managed environment is provided with this facility by .NET CLR
(common language runtime).
The purpose of using Garbage Collector is to clean up memory. In .NET all dynamically
requested memory is allocated in the heap which is maintained by CLR. The garbage collector
continuously looks for heap objects that have references in order to identify which ones are
accessible from the code. Any objects without reference will be removed at the time of garbage
collection. The Garbage collection is not deterministic.
It is called only when the CLR decides that it is most needed. It happens in a situation such as
the heap for the given process is becoming full and requires a clean-up.
In the common language runtime (CLR), the garbage collector serves as an automatic
memory manager. It provides the following benefits:
Enables you to develop your application without having to free memory.
Allocates objects on the managed heap efficiently.
Reclaims objects that are no longer being used, clears their memory, and keeps the memory
available for future allocations. Managed objects automatically get clean content to start with,
so their constructors do not have to initialize every data field.
Provides memory safety by making sure that an object cannot use the content of another
object.
GC.Collect () method:
This method is used to call garbage collector explicitly. It is used to force a garbage collection
to occur at any time.
Q4. What is namespace? Explain System namespace.
Namespaces are C# program elements designed to help you organize our programs. They
also provide assistance in avoiding name clashes between two sets of code. Implementing
Namespaces in our own code is a good habit because it is likely to save us from problems later
when we want to reuse some of our code.
For example, if we created a class named Console, we would need to put it in our own
namespace to ensure that there wasn't any confusion about when the System.Console class
should be used or when our class should be used. Generally, it would be a bad idea to create
a class named Console, but in many cases your classes will be named the same as classes in
either the .NET Framework Class Library or namespaces help usto avoid the problems that
identical class names would cause.
System is fundamental namespace for C# application. It contains all the fundamental classes
and base classes which are required in simple C# application. These classes and sub classes
defines reference data type, method and interfaces. Some classes provide some other feature
like data type conversion, mathematical function.
Some functionality provided by System namespace
Commonly-used value
Mathematics
Remote and local program invocation
Application environment management
[Type here]
Reference data types
Events and event handlers
Interfaces Attributes Processing exceptions
Data type conversion
Method parameter manipulation
Alias of namespace
Below example demonstrate use of alias where A is alias for System.Consolenamespaces.
using A=System.Console;
class Abc
{
public static void Main()
{
A.Write(“Welcome to C# !!!!”);
}
}
Q5. List and explain the use of any five namespaces in c#.
The System namespace contains fundamental classes and base classes that define commonly-
used value and reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
The System.Collections namespace contains interfaces and classes that define various
collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
The System.Text.RegularExpressions namespace contains classes like Regex, Match and
MatchCollection Class that provide access to the .NET Framework regular expression engine.
The System.Data namespace provides access to classes that represent the ADO.NET
architecture. ADO.NET lets you build components that efficiently manage data from multiple
data sources.
The System.Drawing parent namespace contains types that support basic GDI+ graphics
functionality.
Q6. What are the different types of collections in .NET? Explain.
Collection: Collections are basically group of records which can be treated as a one logical
unit.
.NET Collections are divided in to four important categories as follows.
Indexed based.
Key Value Pair.
Prioritized Collection.
Specialized Collection.
Indexed based:
It helps us to access the value by using generated index number by the collection.
ArrayList: A simple resizable, index-based collection of objects.
Key Value Pair: It helps you to access value by the user defined key.
[Type here]
Queue: A first-in, first-out collection of objects
Stack: A last-in, first-out collection of objects
Specialized Collection:
It is very specific collections which are meant for very specific purpose like hybrid dictionary
that start as list and become Hashtable.
StringCollection: A simple resizable collection of strings
StringDictionary: A collection of name/values pairs of strings that allows retrieval by name or
index
ListDictionary: An efficient collection to store small lists of objects
HybridDictionary: A collection that uses a ListDictionary for storage when the number of items
in the collection is small, and then migrate the items to a Hashtable for large collections
Q7. What is delegate? Explain the steps to implement delegate in C#.NET.
Delegate:
The dictionary meaning of ‘Delegates’ is “A person acting for another person”. A delegate in
C# is a class type object & is used to invoke a method that has been encapsulated into it at the
time of its creation.
Following steps are used to create delegate:
Delegate declaration
modifier delegate return_typedelegate_name(parameters)
Delegate methods definition
modifierfunction_name(parameters)
{
//statement(s)
}
Delegate instantiation
new delegate_type(expression);
Delegate invocation
Delegate_object (parameters);
Note: signature of delegate and function must be same
Example:
public delegate void MyDelegate(int , int );
class Abc
{
public void Addition(int a, int b)
{
Console.WriteLine (“Addition :”+(a+b));
}
public void Subtraction(int a, int b)
{
Console.WriteLine (“Subtraction :”+(a-b));
}
}
class Xyz
{
public static void Main()
{
Abc a1=new Abc();
[Type here]
MyDelegate m1=new MyDelegate(a1.Addition);
MyDelegate m2=new MyDelegate(a1.Subtraction);
m1(10,20);
m2(40,5);
Console.Read();
}
}
}
class Xyz
{
public static void Main()
{
Abc a1=new Abc();
MyDelegate m1=new MyDelegate(a1.Show);
MyDelegate m2=new MyDelegate(a1.Display);
m1=m1+m2+m1+m2-m1;
m1();
Console.Read();
}
Q9. Delegates in C# are used for Event Handling. Justify this statement with a relevant
example program.
Events:
An important C# feature is built upon the foundation of delegates: the event. An event is,
essentially, an automatic notification that some action has occurred. Events work like this: An
[Type here]
object that has an interest in an event registers an event handler for that event. When the event
occurs, all registered handlers are called. Event handlers are represented by delegates. Events
are members of a class and are declared using the event keyword.
Its most commonly used form is shown here:
event event-delegate event-name;
Here, event-delegate is the name of the delegate used to support the event, and event-name
is the name of the specific event object being declared.
Example:
using System;
delegate void MyEventHandler();
classMyEvent
{
public event MyEventHandlerSomeEvent;
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();
}
}
classEventDemo
{
static void Handler() {
Console.WriteLine("Event occurred");
}
static void Main()
{
MyEventevt = new MyEvent();
evt.SomeEvent += Handler;
evt.OnSomeEvent();
}
}
[Type here]
Q11. Explain ASP.NET Life Cycle
When a page is requested, it is loaded into the server memory, processed and sent to the
browser. Then it is unloaded from the memory. At each of this steps, methods and events are
available, which could be overridden according to the need of the application.
[Type here]
At this stage, the controls on the page are assigned unique ID by setting the UniqueID property
and themes are applied.
Page load
At this stage, control properties are set using the view state and control state values.
Validation
Validate method of the validation control is called and if it runs successfully, the IsValid property
of the page is set to true.
Postback event handling
If the request is a postback (old request), the related event handler is called.
Page rendering
At this stage, view state for the page and all controls are saved.
Unload
The rendered page is sent to the client and page properties, such as Response and Request
are unloaded and all cleanup done.
Following are the page life cycle events:
PreInit()
Init()
InitComplete()
LoadViewState()
LoadPostData()
PreLoad()
Load()
LoadComplete()
PreRender()
PreRenderComplete()
SaveStateComplete()
UnLoad()
[Type here]
For example, to change the appearance of an <h1> element in the current page alone, you
can add the following code to the <head> of your page:
<head runat=”server”>
<style type=”text/css”>
h1
{
color: Blue;
}
</style>
</head>
Inline style sheet
The third way to apply CSS to your HTML elements is to use inline styles. Because the style
attribute is already applied to a specific HTML element, you don’t need a selector and we can
write the declaration in the attribute directly:
<span style=”color: White; background-color: Black ;”>
This is white text on a black background.
</span>
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
{
color: Green;
}
This Type selector now applies to all <h1> elements in your code and gives them a green color.
Type
Selectors are not case sensitive, so you can use both h1 and H1 to refer to the same heading.
ID Selector
The ID selector is always prefixed by a hash symbol (#) and enables us to refer to a single
element in the page. Within an HTML or ASPX page, you 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
{
font-style: italic;
Because you can reuse this ID across multiple pages in your site (it only has to be unique
within a single page), you can use this rule to quickly change the appearance of an element
[Type here]
that you use once per page, but more than once in your site, for example with the following
HTML code:
<p id=”IntroText”>I am italic because I have the right ID. </p>
Class Selector
The Class selector enables us to style multiple HTML elements through the class attribute.
This is handy when we want to give the same type of formatting to a number of 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
{
font-weight: bold;
color: Red;
}
The following code snippet uses the Highlight class to make the contents of a <span> element
and a link (<a>) appear with a bold typeface:
This is normal text but <span class=”Highlight”>this is Red and Bold.</span>
This is also normal text but
<a href=”CssDemo.aspx” class=”Highlight”>this link is Red and Bold as well.</a>
Example:
<html>
<head>
<title>HTML link Tag</title>
<link rel="stylesheet" type="text/css" href="default.css" />
</head>
<body>
<div>
<p>Welcome to our website. We provide tutorials on various subjects.</p>
</div>
</body>
</html>
Where,
rel-can be used to specify the relationship of the target of the link to the current page.
type-This attribute Provides information about the content type of the destination resource, telling
wether it's an HTML document, a JPG image, an Excel document, etc.
href(uri)-The "href" attribute specifies the destination resource, which the element is linking to. It
may specify a resource in the same website or in an external one.
[Type here]
Unit-III
Topics:
Asp.net Web Server Controls |Programming
Asp.net web pages
[Type here]
Q1. What is the difference between buttons, Link Buttons and Image Buttons? Explain any
three common button attributes.
These controls differ only in how they appear to the user. A button displays text within a
rectangular area. A Link button displays text that look like a hyperlink and an image button
displays an image.
Q2. What is the difference between Button and LinkButton web server controls?
Button Control:
The Button control is used to display a push button. The push button may be a submit button
or a command button. By default, this control is a submit button.
A submit button does not have a command name and it posts the page back to the server
when it is clicked. It is possible to write an event handler to control the actions performed
when the submit button is clicked.
A command button has a command name and allows you to create multiple Button controls
on a page. It is possible to write an event handler to control the actions performed when the
command button is clicked.
Basic syntax:
<asp:Button id="b1" Text="Submit" runat="server" />
LinkButton:
The LinkButton and the ImageButton controls operate similarly to an ordinary Button control.
It presents itself as a simple <a> element but posts back (using JavaScript) instead of
requesting a new page.
Basic syntax:
<asp:LinkButton Text="Click me" OnClick="lblClick" runat="server" />
[Type here]
CheckBox properties:
AutoPostBack:Specifies whether the form should be posted immediately after the Checked
property has changed or not. Default is false
CausesValidation:Specifies if a page is validated when a Button control is clicked
Checked:Specifies whether the check box is checked or not
Id:A unique id for the control
Text: The text next to the check box
Event:
OnCheckedChanged
The name of the function to be executed when the checked property has changed
RadioButton
RadioButton control is used to give single select option to the user from multiple items.
Basic syntax for radio button:
<asp:RadioButton ID= "rdboption" runat= "Server"></asp: RadioButton>
RadioButton properties:
AutoPostBack:A Boolean value that specifies whether the form should be posted immediately
after the Checked property has changed or not. Default is false
Checked : A Boolean value that specifies whether the radio button is checked or not id a unique
id for the control
GroupName : The name of the group to which this radio button belongs
Text : The text next to the radio button
[Type here]
ListBox control is similar to the DropDownList control with two important differences. First, the
ListBox control requires more screen real estate because it always displays a certain number
of list items. Furthermore, unlike the DropDownList control, the ListBox control enables a user
to select multiple items.
<asp:ListBox ID="dropStatic" runat="server">
<asp:ListItem Text="Red" Value="red"></asp:ListItem>
<asp:ListItem Text="Blue" Value="blue"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:ListBox>
Some properties are
SelectedIndexChanged
SelectedIndexChanged event occurs when the selection from the list control changes
between posts to the server.
OnSelectedIndexChanged
OnSelectedIndexChanged method raises the SelectedIndexChanged event.
This allows you to provide a custom handler for the event.
Q6. What is the difference between List Box and Drop-Down Lists? List and explain any
three common properties of these controls.
List boxes are used in cases where there are small numbers of items to be selected. In
contrast, drop-down lists are typically used with larger list so that they don’t take up much
space on the page.
A list box lets a user select one or more items from the list of items. A drop-down list lets a
user choose an item from the drop-down list of items.
Following are common properties of ListBox and DropDownList:
Properties Description
[Type here]
Items Gets the collection of items from the dropdown box.
SelectedValue Get the value of the Selected item from the dropdown box.
SelectedIndex Gets or Sets the index of the selected item in the dropdown box.
SelectedItem Gets the selected item from the list.
MultiColumn:
A multicolumn ListBox places items into as many columns as are needed to make vertical
scrolling unnecessary. The user can use the keyboard to navigate to columns that are not
currently visible. Set the HorizontalScrollbar property to true to display a horizontal scroll bar
that enables the user to scroll to columns that are not currently shown in the visible region of
the ListBox. The value of the ColumnWidth property determines the width of each column.
listBox1.MultiColumn = true;
[Type here]
SelectedItem
Gets or sets the currently selected item in the ListBox. We can get text associated with currently
selected item by using Items property.
stringselectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
SelectedIndex
Gets or sets the zero-based index of the currently selected item in a ListBox.
listBox1.SelectedIndex = 1;
Q9. What is use of autopostback and runat properties?
AutoPostback or Postback is nothing but submitting page to server. AutoPostback is webpage
going to server, Server processes the values and sends back to same page or redirects to
different page.
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.
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.
AutoPostBack means that if any change happens on a control by the client, it should postback
to the server to handle that change at server side. If this property is set to TRUE the automatic
post back is enabled, otherwise FALSE. Default is FALSE.
Example
<asp:TextBox id= " t1" AutoPostBack="true" runat="server" />
Web server controls are created on the server and they require a runat="server" attribute to
work. This attribute indicates that the control should be treated as a server control.
Example
<asp:Button id="button1" Text="Click me!" runat="server" />
[Type here]
We cannot send special characters through query string. All special characters should be
encoded when you pass them through the query string. The encoded string must be decoded
at the receiver.
There are two methods to achieve this: UrlEncode and UrlDecode():
The main purpose of these two methods is to encode and decode the URLrespectively. We
need to encode the URL because some of the characters are not safe sending those across
browser.
Some characters are being misunderstood by the browser and that leads to data mismatch on
the receiving end. Characters such as a question mark (?), ampersand (&), slash mark (/), and
spaces might be truncated or corrupted by some browsers.
UrlEncode()
This method is used to encode a string to be passed through URL to another web page.
URLencode replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
Syntax:
UrlEncode (string str )
UrlDecode()
This method is used to decode the encoded URL string. Decodes any %## encoding in the
given string.
Syntax:
UrlDecode (string str )
Q12. Explain the use of web.config and global.asx files in ASP.NET application.
The Global.asax file, also known as the ASP.NET application file, is an optional file that
contains code for responding to application-level events raised by ASP.NET or by
HttpModules.
The Global.asax file resides in the root directory of an ASP.NET-based application. The
Global.asax file is parsed and dynamically compiled by ASP.NET.
The Global.asax file itself is configured so that any direct URL request for it is automatically
rejected; external users cannot download or view the code written within it.
The Global.asax file does not need recompilation if no changes have been made to it. There
can be only one Global.asax file per application and it should be located in the application's
root directory only.
The Global.asax contains two types of events those are
o Events which are fired for every request
o Events which are not fired for every request
Events which are fired for every request:-
Application_BeginRequest() – This event raised at the start of every request for the web application.
Application_EndRequest() – This event raised at the end of each request right before the objects
released.
Application_PreRequestHandlerExecute() – This event called before the appropriate HTTP
handler executes the request.
Application_PostRequestHandlerExecute() – This event called just after the request is handled
by its appropriate HTTP handler.
Events which are not fired for every request:-
Application_Start() – This event raised when the application starts up and application domain
is created.
[Type here]
Session_Start() – This event raised for each time a new session begins, This is a good place to
put code that is session-specific.
Application_Error() – This event raised whenever an unhandled exception occurs in the
application. This provides an opportunity to implement generic application-wide error handling.
Session_End() – This event called when session of user ends.
Application_End() – This event raised just before when web application ends.
Application_Disposed() – This event fired after the web application is destroyed and this event
is used to reclaim the memory it occupies.
Web.Config
Configuration file is used to manage various settings that define a website. The settings are
stored in XML files that are separate from our application code.
In this way we can configure settings independently from our code. Generally a website
contains a single Web.config file stored inside the application root directory.
However there can be many configuration files that manage settings at various levels within an
application. Usage of configuration file: ASP.NET Configuration system is used to describe the
properties and behaviors of various aspects of ASP.NET applications.
Configuration files help us to manage the many settings related to your website. Each file is an
XML file (with the extension .config) that contains a set of configuration elements. Configuration
information is stored in XML-based text files.
[Type here]
Unit-IV
Topics:
Validation Controls| State Management
|Master Pages |Navigation
[Type here]
Q1. Why we use validation controls? List various types of validation controls used in
asp.net
Validation is important part of any web application. User's input must always be validated
before sending across different layers of the application.
Validation controls are used to:
Implement presentation logic.
To validate user input data.
Data format, data type and data range is used for validation.
Validation Controls in ASP.NET
An important aspect of creating ASP.NET Web pages for user input is to be able to check that
the information users enter is valid. ASP.NET provides a set of validation controls that provide
an easy-to-use but powerful way to check for errors and, if necessary, display messages to the
user.
[Type here]
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator Server Control is another validator control, which checks to see if a
control value is within a valid range. The attributes that are necessary to this control are:
MaximumValue, MinimumValue, and Type.
It has three specific properties:
Q3. What is the use of Compare Validator? Explain it along with its properties.
CompareValidator Control
The CompareValidator control allows you to make comparison to compare data entered in an
input control with a constant value or a value in a different control.
It can most commonly be used when you need to confirm password entered by the user at
the registration time. The data is always case sensitive.
It has the following specific properties:
[Type here]
Example:
Small number:<br />
<asp:TextBoxrunat="server" id="txtSmallNumber" /><br /><br />
Big number:<br />
<asp:TextBoxrunat="server" id="txtBigNumber" /><br />
<asp:CompareValidatorrunat="server" id="cmpNumbers" controltovalidate="txtSmallNumber"
controltocompare="txtBigNumber" operator="LessThan" type="Integer" errormessage="The
first number should be smaller than the second number!" /><br />
Example:
In this below example we will simply check the length of the string in the TextBox.
Custom Text:<br />
<asp:TextBoxrunat="server" id="txtCustom" />
<asp:CustomValidatorrunat="server" id="cusCustom" controltovalidate="txtCustom"
onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8
characters long!" />
<br /><br />
[Type here]
A web application is stateless. That means that a new instance of a page is created every time
when we make a request to the server to get the page and after the round trip our page has
been lost immediately.
It only happens because of one server, all the controls of the Web Page is created and after
the round trip the server destroys all the instances. So to retain the values of the controls we
use state management techniques.
State Management Techniques
They are classified into the following 2 categories:
Application State:
If the information that we want to be accessed or stored globally throughout the application,
even if multiple users access the site or application at the same time, then we can use an
Application Object for such purposes.
It stores information as a Dictionary Collection in key - value pairs. This value is accessible
across the pages of the application / website.
There are 3 events of the Application which are as follows
Application_Start
Application_Error
Application_End
Example - Just for an example, I am setting the Page title in the Application Start event of the
Global.asax file.
Code for setting value to the Application Object - "PageTitle" is the Key and "Welcome to State
Management Application" is the value.
[Type here]
Q6. What is Query String? Explain encoding and decoding of Query string
Query String is the most simple and efficient way of maintaining information across requests.
The information we want to maintain will be sent along with the URL. A typical URL with a query
string looks like www.somewebsite.com/search.aspx?query=foo
The URL part which comes after the ?symbol is called a QueryString.
QueryString has two parts, a key and a value. In the above example, query is the key and foo
is its value.
We can send multiple values through querystring, separated by the & symbol. The following
code shows sending multiple values to the foo.aspx page.
Response.Redirect("foo.aspx?id=1&name=foo");
The following code shows reading the QueryString values in foo.aspx
string id = Request.QueryString["id"];
string name = Request.QueryString["name"];
The HtmlEncode() method is particularly useful if you’re retrieving values from a database and
you aren’t sure if the text is valid HTML.
We can use the HtmlDecode() method to revert the text to its normal form if we need to perform
additional operations or comparisons with it in your code.
The UrlEncode() method changes text into a form that can be used in a URL, escaping spaces
and other special characters. This step is usually performed with information we want to add
to the query string.
Label1.Text = Server.HtmlEncode("To bold text use the <b> tag.");
Advantages
Query string is lightweight and will not consume any server resources.
It is very easy to use and it is the most efficient state management technique. However, it has
many
Disadvantages
We can pass information only as a string.
URL length has limitations. So you can't send much information through URL.
Information passed is clearly visible to everyone and can be easily altered.
[Type here]
Persist Cookie - A cookie has not have expired time which is called as Persist Cookie
Non-Persist Cookie - A cookie has expired time which is called as Non-Persist Cookie
Creation of cookies:
It’s really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookieuserInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
Example 2:
stringUser_name = string.Empty;
stringUser_color = string.Empty;
HttpCookiereqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
When we make request from client to web server, the web server process the request and give
the lot of information with big pockets which will have Header information, Metadata, cookies
etc., Then repose object can do all the things with browser.
Cookie's common property:
Domain: This is used to associate cookies to domain.
Secure: We can enable secure cookie to set true (HTTPs).
Value: We can manipulate individual cookie.
Values:We can manipulate cookies with key/value pair.
Expires: Which is used to set expire date for the cookies.
Advantages of Cookie:
Its clear text so user can able to read it.
We can store user preference information on the client machine.
Its easy way to maintain.
Fast accessing.
Disadvantages of Cookie
[Type here]
If user clears cookie information we can't get it back.
No security.
Each request will have cookie information with page.
Q8. Write a program to create a new cookie with the name “Username” and add it to the
HttpResponse object on the click of a button. Set the expiry date of the cookie to One year
from Now.
[Type here]
Q10. Difference between Application state and Session state
ASP.NET implements application state using the System.Web.HttpApplicationState class.
It provides methods for storing information which can be accessed globally.
Information stored on application state will be available for all the users using the website.
Usage of application state is the same as sessions.
The following code shows storing a value in an application variable and reading from it.
We should get a basic knowledge about the events associated with application and session.
These events can be seen in the global.asax file.
Application_Start This event executes when application initializes. This will execute when
ASP.NET worker process recycles and starts again.
Application_End Executes when the application ends.
Session_Start Executes when a new session starts.
Session_End Executes when session ends. Note: this event will be fired only if you are
using InProc as session mode.
Example
The most common usage of application variables is to count the active number of visitors that
are browsing currently.
The following code shows how this is done .
voidApplication_Start(object sender, EventArgs e)
{
// Application started - Initializing to 0
Application["activeVisitors"] = 0;
}
voidSession_Start(object sender, EventArgs e)
{
if (Application["activeVisitors"] != null)
{
Application.Lock();
intvisitorCount = (int)Application["activeVisitors"];
Application["activeVisitors"] = visitorCount++;
Application.UnLock();
}
}
Data stored in session will be kept in server memory and it is protected as it will never get
transmitted to a client.
Every client that uses the application will have separate sessions. Session state is ideal for
storing user specific information.
The following code shows storing a string value in session.
Session["name"] = "Value";
Values stored in sessions can be removed by several methods.
Session.Abandon() : Cancels the session and fires end event. This is used when you are done
with the session.
[Type here]
Session.Clear() /Session.RemoveAll() : Clears all contents of the session. This will not end the
session
Session.Remove(string) : Removes the session name supplied.
Working of Session:
ASP.NET maintains a unique id which is called as "session id" for each session. This id is
generated using a custom algorithm and it is unique always.
Session id will be sent to the client as a cookie and the browser resends this upon each request.
ASP.NET uses this session id to identify the session object.
stringsessionId = Session.SessionID
Session State
Session state is user and browser specific.
Session state can be stored in memory on the server as well as client's cookies.
If client has disabled cookies in his browser then session state will be stored in URL.
Session state has scope to the current browser only. If we change the browser session id is
changed.
Application State
Application state is application specific.
Application state is stored only in the memory on the server.
Application state does not track client's cookies or URL.
Application state has no scope to the current browser. If we change the browser application
id remains same.
[Type here]
The master pages can be used to accomplish the following:
Creating a set of controls that are common across all the web pages and attaching them to
all the web pages.
A centralized way to change the above created set of controls which will effectively change all
the web pages.
To some extent, a master page looks like a normal ASPX page.
It contains static HTML such as the <html>, <head>, and <body> elements, and it can also
contain other HTML and ASP.NET server controls.
Inside the master page, you set up the markup that you want to repeat on every page, like the
general structure of the page and the menu.
However, a master page is not a true ASPX page and cannot be requested in the browser
directly it only serves as the template that real web pages called content pages
One difference is that while web forms start with the Page directive, a master page starts with
a Master directive that specifies the same information, as shown here
[Type here]
Q13. Explain Menu control in ASP.NET
The Menu control is used to create a menu of hierarchical data that can be used to navigate
through the pages. The Menu control conceptually contains two types of items. First is
StaticMenu that is always displayed on the page, second is DynamicMenu that appears when
opens the parent item.
ASP.NET TreeView Web control is used to display hierarchical data (such as a table of
contents) in a tree structure in a Web page.
The TreeView control is made up of TreeNode objects. The TreeView control can be bound
to data.
It supports the following features:
Automatic data binding, this allows the nodes of the control to be bound to hierarchical data,
such as an XML document.
Site navigation support through integration with the SiteMapDataSource control.
[Type here]
Node text that can be displayed as either selectable text or hyperlinks.
Customizable appearance through themes, user-defined images, and styles.
Programmatic access to the TreeView object model, which allows you to dynamically create
trees, populates nodes, set properties, and so on.
Node population through client-side callbacks to the server (on supported browsers).
The ability to display a check box next to each node .
<asp:TreeViewExpandDepth="1" runat="server">
<Nodes>
<asp:TreeNode Text="Employees">
<asp:TreeNode Text="Bradley" Value="ID-1234" />
<asp:TreeNode Text="Whitney" Value="ID-5678" />
<asp:TreeNode Text="Barbara" Value="ID-9101" />
</asp:TreeNode>
</Nodes>
</asp:TreeView>
Each node in the Tree is represented by a name/value pair (not necessarily unique), defined
by the Text and Value properties of TreeNode, respectively. The text of a node is rendered,
whereas the value of a node is not rendered and is typically used as additional data for
handling postback events.
This example also uses the ExpandDepth property of TreeView to automatically expand the
tree 1 level deep when it is first rendered.
The TreeView control is made up of one or more nodes. Each entry in the tree is called a
node and is represented by a TreeNode
[Type here]
Unit-V
Topics:
Database (ADO.Net)| Asp.Net Security
[Type here]
Q1. List and Explain ADO .NET objects.
ADO.NET includes many objects we can use to work with data. Some important objects of
ADO.NET are:
SqlConnection
To interact with a database, we must have a connection to it. The connection helps identify the
database server, the database name, user name, password, and other parameters that are
required for connecting to the data base.
A connection object is used by command objects so they will know which database to execute
the command on.
SqlCommand
The process of interacting with a database means that we must specify the actions we want to
occur. This is done with a command object. We use a command object to send SQL statements
to the database.
A command object uses a connection object to figure out which database to communicate with.
We can use a command object alone, to execute a command directly, or assign a reference to
a command object to an SqlDataAdapter, which holds a set of commands that work on a group
of data as described below.
SqlDataReader
Many data operations require that we only get a stream of data for reading. The data reader
object allows us to obtain the results of a SELECT statement from a command object. For
performance reasons, the data returned from a data reader is a fast forward-only stream of
data. This means that we can only pull the data from the stream in a sequential manner this is
good for speed, but if we need to manipulate data, then a DataSet is a better object to work
with.
DataSet
DataSet objects are in-memory representations of data. They contain multiple Datatable
objects, which contain columns and rows, just like normal database tables. We can even define
relations between tables to create parent-child relationships.
The DataSet is specifically designed to help manage data in memory and to support
disconnected operations on data, when such a scenario make sense. The DataSet is an object
that is used by all of the Data Providers, which is why it does not have a Data Provider specific
prefix.
SqlDataAdapter
Sometimes the data we work with is primarily read-only and we rarely need to make changes
to the underlying data source some situations also call for caching data in memory to minimize
the number of database calls for data that does not change. The data adapter makes it easy
for us to accomplish these things by helping to manage data in a disconnected mode.
The data adapter fills a DataSet object when reading the data and writes in a single batch when
persisting changes back to the database. A data adapter contains a reference to the connection
object and opens and closes the connection automatically when reading from or writing to the
database.
Additionally, the data adapter contains command object references for SELECT, INSERT,
UPDATE, and DELETE operations on the data. We will have a data adapter defined for each
table in a DataSet and it will take care of all communication with the database for us. All we
need to do is tell the data adapter when to load from or write to the database.
Q2. Explain Command Class and DataAdapter class with properties and methods
Command class properties and methods
[Type here]
[Type here]
Q3. Differentiate between DataSet and DataReader.
DataReader
DataReader is connection oriented architecture.
DataReader is like a forward only recordset.
It fetches one row at a time so very less network cost compare to DataSet (Fetches all the
rows at a time).
DataReader is readonly so we can't do any update or transaction on them.
DataReader will be the best choice where we need to show the data to the user which
requires no transaction.
As DataReader is forward only so we can't fetch data randomly.
.NET Data Providers optimizes the DataReader to handle huge amount of data.
Performance is good.
DataAdapter
Q5. What is a GridView control? Explain how to enable row selection, paging and sorting
features of GridView.
The GridView server control displays data provided by a data source in a tabular format. It
renders its data as an HTML table. The GridView control supports automatic paging, sorting,
editing, deleting, and selecting. To enable row selection AutoGenerateSelectButton property
of GridView can be set to true.
[Type here]
The GridView data can be sorted based on any or all of its columns. To sort GridView data,
following are the steps
Set AllowSorting attribute of GridView to True
Also set SortExpression property of columns to respective field from database to sort.
Paging refers to the ability of GridView control to display bound data one page at a time. Users
can arbitrarily select pages from a GridView. To enable paging feature of a GridView
Set AllowPaging property of GridView control to true.
Set PageSize property to no of records we want in each page.
Example:
<asp:gridview AllowSorting="true" AllowPaging="true" PageSize="5" ID="Gridview1"
runat="server" DataKeyNames="pid" DataSourceID="SqlDS" >
<Columns>
<asp:BoundFieldDataField="pname" HeaderText="PRODUCT NAME"
SortExpression="pname"></asp:BoundField>
</Columns>
</asp:gridview>
[Type here]
Q7. Briefly explain FormView control. How is it different from DetailsView?
Like DetailsView, 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 feature and hence support backward and forward traversal.
The FormView control provides more formatting and layout options than DetailsView.
The DetailsView control uses <BoundField> elements or <TemplateField> 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.
Q8. What is the difference between ListView and Gridview control? Explain the ListView
control.
ListView presents the data in rows and columns just like a GridView control. The main
difference between the ListView control and Gridview control is that the ListView control
includes an additional row for inserting a new row into the table.
ListView Control:
The ListView control displays columns and rows of data and allows sorting and paging. It is by
far the most popular data display control, and is ideal for understanding how data display
controls interact with data retrieval controls and code.
ListView provides various templates which we can use to display the data. The templates
are:
o LayoutTemplate
o ItemTemplate
o ItemSeparatorTemplate
o GroupTemplate
o GroupSeparatorTemplate
o EmptyItemTemplate
o EmptyDataTemplate
o SelectedItemTemplate
o AlternatingItemTemplate
o EditItemTemplate
o InsertItemTemplate
Example:
<form id="form1" runat="server">
<asp:ListView ID="ListView1" runat="server"DataSourceID="SqlDataSource1">
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [tblPeople]"></asp:SqlDataSource>
</form>
Q9. What is a Data source? Explain various types of data sources in ASP.NET.
The Data source control connects to and retrieves data from a data source and makes it
available for other controls to bind to, without requiring code. ASP.NET allows a variety of data
sources such as a database, an XML file, or a middle-tier business object.
The common data source controls are:
[Type here]
AccessDataSource – Enables you to work with a Microsoft Access database.
XmlDataSource – Enables you to work with an XML file.
SqlDataSource – Enables you to work with Microsoft SQL Server, OLE DB, ODBC, or Oracle
databases.
ObjectDataSource – Enables you to work with a business object or other class
SiteMapDataSource – Used for ASP.NET site navigation.
EntityDataSource - Enables you to bind to data that is based on the Entity Data Model.
LinqDataSource – Enables you to use Language-Integrated Query (LINQ) in an ASP.NET
Web page.
Authentication is process of validating the identity of a user so the user can be granted
access to an application. A user must typically supply a user name and password to be
authenticated.
After a user authenticated, the user must still be authorized to use the required application.
The process of granting user access to an application is called authorization.
There are 3 types of authentication as follows:
Windows-based authentication:
It causes the browser to display a login dialog box when the user attempts to access
restricted page.
It is supported by most browsers.
It is configured through the IIS management console.
It uses windows user accounts and directory rights to grant access to restricted pages.
Forms-based authentication:
Developer codes a login form that gets the user name and password.
The username and password entered by user are encrypted if the login page uses a secure
connection.
It doesn’t reply on windows user account.
[Type here]
Windows Live ID authentication:
It is centralized authentication service offered by Microsoft.
The advantage is that the user only has one maintain one username and password.
<authorization>
<deny users="?"/>
</authorization>
We also need to specify the authorization part. We need to insert the below snippet in the
‘web.config’ file .stating that only ‘Administrator’ users will have access to
<location path="Admin.aspx">
<system.web>
<authorization>
<allow roles="questpon-srize2\Administrator"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
The next step is to compile the project and upload the same on an IIS virtual directory. On the
IIS virtual directory we need to ensure to remove anonymous access and check the integrated
windows authentication.
Now if we run the web application we will be popped with a userid and password box.
Q12. What is the application services provided 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.
[Type here]
Figure below gives an overview of these services and shows how they are related to our web
site and the underlying data stores that the services may use.
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
Site map
Profile
Session state etc.
At the top of the diagram you see the ASP.NET 4 web sites and web applications that represent
the web sites that you build. These web sites can contain controls like the login controls that in
turn 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 membership services, the membership provider is designed to work
with users in the underlying data store. You can configure different providers for the same
application service depending on your needs.
[Type here]
Unit-VI
Topics:
LINQ | Ajax | JQuery
[Type here]
Q1. What is LINQ? Explain its syntax and give its advantages.
Language-Integrated Query (LINQ) is an innovation introduced in Visual Studio 2008 and .NET
Framework version 3.5 that bridges the gap between the world of objects and the world of data.
Traditionally, queries against data are expressed as simple strings without type checking at
compile time or IntelliSense support. Furthermore, we have to learn a different query language
for each type of data source: SQL databases, XML documents, various Web services, and so
on.
LINQ makes a query a first-class language construct in C# and Visual Basic. We write queries
against strongly typed collections of objects by using language keywords and familiar
operators.
LINQ Syntax:
LINQ query syntax is a set of query keywords built into the .NET framework (3.5 and higher)
that allow the developer to write SQL style commands in line straight in the code editor, without
the use of quotes
The .NET framework 3.5 introduces us to the following query keywords;
from / in - Specifies the data source
where - Conditional Boolean expression
orderby (ascending/descending) - Sorts the results into ascending or descending order
select - Adds the result to the return type
group / by - Groups the results based on a given key
Advantages:
The availability of strong typed queries: The classes are auto generated according to the
relations in relational databases. The language is very much easy to understand as in SQL.
The automatic join functioning in foreign keys: In normal SQL, the user has to join the
tables if it is necessary. In LINQ, it provides the ability to join each function automatically when
there is a foreign key reference.
The code size: There are many occasions that the users have to write long sentences for
getting a SQL query. LINQ provides relatively short codes in such advanced occasions. It
reduces the complexity of the code and makes it much easy for the program to read.
Code equality: One of the most advantages in using LINQ is that its availability over any
.NET platform language such as C#.net, VB.NET and F#.NET.
[Type here]
When it comes to querying databases, LINQ is in most cases a significantly more productive
querying language than SQL.
Compared to SQL, LINQ is simpler, tidier, and higher-level
LINQ enabling us to access and query a wide variety of sources including collections in your
own code, XML files, .NET Datasets, and databases from your VB.NET or C# code.
SQL language is used to create, modify and retrieve information from RDBMS. LINQ is a
uniform programming model for any kind of data access.
Advantages
LINQ is a technique for querying data across various kinds of data sources and formats.
It can be used to query data from various data sources like XML documents, SQL
databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ
provider is available.
The .NET application can interact with LINQ for database operations and LINQ takes care
of complete database operations.
Q3. Short Note on LINQ to object and Query Expression
LINQ to Objects is the purest form of language integration. With LINQ to Objects, we can
query collections in our .NET applications.
We are not limited to arrays because LINQ enables us to query almost any kind of collection
that exists in the .NET Framework.
LINQ to Objects allows us to replace iteration logic with a declarative LINQ expression
IEnumerable<EmployeeDetails> matches;
matches = from employee in employees select employee;
All LINQ expressions must have from clause that indicates the data source and a select
clause that indicates the data you want to retrieve.
The from clause identifies two pieces of information .
The word immediately after in identifies the data source -in this case, it’s the collection
object named employees that holds the EmployeeDetails instances.
The word immediately after from assigns an alias that represents individual items in the data
source.
Q4. Explain LINQ to Objects with an example.
It is used to query collections.
The LINQ can be used to query any IEnumerable or IEnumerable<T> collection.
Any enumerable collections such as List<T>, Array, ArrayList, Dictionary<TKey, TValue>
etc. can be queried using LINQ.
Example:
Label1.Text = "";
String [] a = {“The Darkest Hour", "Heartbreaker", "Contraband", "Haywire", “The
Descendants"};
var query = from x in a select x;
foreach (string s in query)
{
Label1.Text += s+"<br>";
[Type here]
}
Q5. Explain the Standard Query operators “Select”, “From”, “orderby” and “Where” in
LINQ.
Select: The select keyword is used to retrieve objects from the source you are querying.
varallReviews = from r in myEntities.Reviewsselect r;
The r variable in this example is referred to as a range variable that is only available within
the current query.
From: It defines the collection or data source that the query must act upon.
Orderby: With order bywe can sort the items in the result collection. Order by is followed by
an optional ascending and descending keyword to specify sort order. We can specify multiple
criteria by separating them with a comma.
varallGenres = from g in myEntities.Genresorderbyg.SortOrder descending, g.Name select
g;
Where: The where clause in LINQ enables you to filter the objects returned by the query.
varallReviews = from r in myEntities.Reviews where r.Authorized == true select r;
Q6. Explain LINQ to SQL with the help of a query that performs equijoin.
LINQ to SQL allows developers to generate .NET classes that represent data. These generated
classes map directly to database tables. When the application runs, LINQ to SQL translates
the language-integrated queries in the object model into SQL and sends them to the database
for execution. When the database returns the results, LINQ to SQL translates them back to
objects that you can work with in Visual Basic or C#.
LINQ to SQL needs a Data Context object. The Data Context object is the bridge between
LINQ and the database. The Data Context is created using the LINQ to SQL designer. The
LINQ to SQL designer creates a .dbml file which contains auto-generate Visual Basic or C#
source code that represents data. The Data Context is named after .dbml file.
If the name of the .dbml file is DataClasses1 then Data Context class name would be
DataClasses1DataContext. The name of the data context in the following example is
DataClasses1DataContext and has mapped objects Orders and Order_Details. These objects
are mapped to relational tables Order and Order_Detail respectively.
Q7. What are the benefits using Ajax? Explain UpdatePanel and ScriptManager.
The major benefit of Ajax is partial page rendering. The partial update of a page does not
necessitate full reload of the page and hence leads to flicker-free page rendering.
UpdatePanel
It is a container control.
A page can have multiple update panels.
The UpdatePanel control enables you to create a flicker free page by providing partial-page
update support to it.
It identifies a set of server controls to be updated using an asynchronous post back.
[Type here]
If a control within the UpdatePanel causes a post back to the server, only the content within
that UpdatePanel is refreshed.
ScriptManager
The ScriptManager control manages client script for AJAX-enabled ASP.NET Web pages.
Although this control is not visible at runtime, it is one of the most important controls for an
Ajax enabled web page.
This control work with UpdatePanel control to facilitate partial page rendering in Ajax enabled
web pages.
There can be only one ScriptManager in an Ajax enabled web page.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
[Type here]
The UpdateProgress provides status information about partial page updates in UpdatePanel
controls. Despite the visual problems that postbacks usually cause, they have one big
advantage: the user can see something is happening.
The UpdatePanel makes this a little more difficult. Users have no visual cue that something is
happening until it has happened. To tell users to hold on for a few seconds while their request
is being processed, we can use the UpdateProgress control.
We usually put text such as “Please wait” or an animated image in this template to let the user
know something is happening, although any other markup is acceptable as well. We can
connect the UpdateProgress control to an UpdatePanel using the AssociatedUpdatePanelID
property.
Its contents, defined in the <ProgressTemplate> element, are then displayed whenever the
associated UpdatePanel is busy refreshing.
[Type here]
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
Example: $("#test")
The .class Selector
The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the
class:
Example: $(".test")
Q12. What is the use of Document Ready function?
All jQuery methods in our examples are inside a document ready event:
$(document).ready (function () {// jQuery methods go here...});
This is to prevent any jQuery code from running before the document is finished loading (is
ready).
It is good practice to wait for the document to be fully loaded and ready, before working with
it. This also allows us to have our JavaScript code before the body of our document, in the
head section.
Here are some examples of actions that can fail if methods are run before the document is
fully loaded:
Trying to hide an element that is not created yet
Trying to get the size of an image that is not loaded yet
Tip: The jQuery team has also created an even shorter method for the document ready
event:
$(function ()
{
// jQuery methods go here...
}
);
Q15. Write a program using jQuery that hides a paragraph on click of a button.
<html><head><title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready (function () {
$("p”).click (function () {
$(this).hide ();
});
});
</script></head><body>
<p> ASP.NET with C# is simple </p>
</body></html>
Q16. What is post-back event? Explain IsPostBack with suitable example.
If Page.IsPostBack property is false, the page is loaded at a first time. If it is true, the page
is posted back to the server i.e. loaded for the next time.
The Page_Load() event runs every time the page is loaded but if you want to execute the
code in the Page_Load event only once i.e. for the first time page is loaded then you can
use Page.IsPostBack property.
[Type here]
Example:
<HEAD runat=”server”>
<Script runat=”server”>
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Text=”Page is loaded first time”
}
else
{
Label1.Text=”Page is not loaded first time”
}
</Script>
</HEAD>
<BODY>
<Form id=”form1” runat=”server”>
<asp:Label id=”Label1” runat=”server” Text=” ”/>
<asp :Button id=”Button1” runat “server” Text=”Submit” />
</Form>
</BODY>
[Type here]