0% found this document useful (0 votes)
15 views127 pages

Dot Net - Chapter-1 - Combine

Uploaded by

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

Dot Net - Chapter-1 - Combine

Uploaded by

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

ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)

Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture Notes
Chapter-1

1. Explain Architecture of .Net Framework.

- It collects all the Technology needed to build window application, web application as web
services.
- It is managed and safe environment for developing & executing an application.
- Its provide Runtime Environment for Execution of program.
- It is responsible for Memory management, code validation, code access security, code
compilation & code execution.
- .NET Framework Architecture has languages at the top such as VB .NET C#, VJ#, VC++ .NET;
developers can develop (using any of above languages) applications such as Windows
Forms, Web Form, Windows Services and XML Web Services. Bottom two layers are most
important components consist of .NET Framework class library and Common Language
Runtime.

- There are mainly two parts of .Net framework


- (1). Common language runtime (CLR) (2) .NET Framework class library

(1) Common language runtime (CLR) :

- It is the heart of .Net framework.


- It provides core services like code memory management, code validation, code
access security, Thread management, code compilation, code execution and garbage
collection.
6th CE – Dot Net Technology Page 1
ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Mostly all the functionality to execute .net application provide by CLR.


- All the Language has runtime and its responsibility is to take care of code
compilation & execution.
- For example VB6 has MSVBVM60.DLL, Java has JVM.
- Same way .Net has CLR
- It is same as Java Virtual Machine (JVM) in JAVA.
- Someone say it is clone of JAVA.

 Responsibility of CLR :

(1) Memory Management:

- Automatic memory management provided by Garbage collector in .Net.


- You can explicitly Run Garbage collector by gc.collect method.
- When object is out of scope or it will take long time then it will reclaim
memory and speed up the process.
- Before .NET introduce, this was mostly the responsibility of programmers,
and a few simple errors in code could reserved large blocks of memory. That
usually slowdown of your system or some time system may be crash.

(2) Code Compilation & Execution :

- In .Net all source code contain any language vb.net, c# etc.. compiled into
Microsoft intermediate language.
- CLR is responsible for converting intermediate language (IL) code to native
code.

- Now CLR provides Just In Time Compiler (JIT) that converts MSIL to Native
Language which is CPU Specific code.
- All the executables and DLL also exists as MSIL so they can freely
interoperate.

6th CE – Dot Net Technology Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(3) Code Access Security:

- CAS is the part of .Net security mode.


- It will take care of proper code execution.
- It determines whether a piece of code is allowed to run or not. It provides
security for application
- It prevents source code to perform such illegal operation.
- For example, it is CAS that will prevent formatting .Net web applet from your
harddisk.
- CAS allows an application to read but not write and delete a file from folder.

(4) Thread execution


- The .NET Framework provides threading and synchronization facilities to allow
you to build high performance, multithreaded code.
- Your choice of threading approach and synchronization mechanism impacts
application concurrency; hence, it also impacts overall performance.

(5) Type Checker

- Type checker will verify types used in the application with CTS or CLS
standards supported by CLR, this provides type safety.

(6) Exception Manager

- The CLR supports structured exception handling to allow you to build robust,
maintainable code.

- Use language constructs such as try/catch/finally to take advantage of


structured exception handling.

 Implications of CLR :

(1) Language Integration:

- .NET Framework includes no restriction on the type of applications that are


possible. The .NET Framework allows the creation of Windows applications, Web
applications, Web services, and lot more.

- The .NET Framework has been designed so that it can be used from any language,
including VB.net, C#, C++, Visual Basic, JScript, and even older languages such as
COBOL.

(2) Side by Side Execution/Versioning:

6th CE – Dot Net Technology Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Side-by-side execution is the ability to run multiple versions of an application or


component on the same computer.
- You can have multiple versions of the common language runtime, and multiple
versions of applications and components that use a version of the runtime, on the
same computer at the same time.
- When a component or application is updated on a computer, the older version is
removed and replaced with the newer version. If the new version is not compatible
with the previous version, this usually breaks other applications that use the
component or application.
- The .NET Framework provides support for side-by-side execution, which allows
multiple versions of an assembly or application to be installed on the same
computer at the same time. Because multiple versions can be installed
simultaneously, managed applications can select which version to use without
affecting different version applications.

(3) End of DLL Hell :

Before some time, if we install an application then dll of that application get stored
in the registry then if we install other application that has same name .dll so that
previously installed .dll get overwrite by the same name new .dll. Its ok for newly
installed application but previously installed application cant get execute properly
because of mismatching version of assembly. This is called Dell-Hell problem.
And it solved by Side by side execution/versioning. So now End of DLL Hell.

 Drawback of CLR :

(1) Performance :

- In CLR code checking (code validation/CAS) occur that will take time to
execute application.
- In C++ and other language no validation and checking so run fastly.

(2) Code Transparency :

- If you distribute a compiled component then other programmers can easily


determines how your program works. And this is not much issue for asp.net
application which is not distributed but is hosted on secure web server.

- There are Decompiler/Deassembler available in market.


- By this type of Decompiler any one can see what is in assembly and Reverse
engineer convert them back into actual source code. In this way they can able
to crack your application.

(2) .Net Class Library :

- It is the large range of predefined classes that are designed to integrate with common
language runtime (CLR).

6th CE – Dot Net Technology Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- It contains more than 7000 classes and data types to read and write files, access
databases, process XML, display a graphical user interface, draw graphics, use Web
services, etc…

- These classes are fully object oriented and reusable.


- Base class for .Net application is system.
- From system class all the classes are inherited.
- It has classes relate to Database access, web forms, window forms, xml, I/O files as
well as core system classes like Threading, serialization, reflection, collection etc..
- These classes are grouped together according to functionality called Namespace.
- Namespace is the logical group of related classes. Namespace provide many useful
services and objects that useful to write code in your application
- A namespace acts as a container—like a disk folder
- Ex: System, System. Data, System.Data.SqlClient.
- Tiers of Namespace defined by Dot.
- First example refers to System Namespace.
- Second refers to System.Data Namespace.
- Third refers to System.Data.SqlClient Namespace.

2. Define Following.

(i) CLS (Common Language Specification): It defines basic requirement and


standards that allow language to run under the CLR. It defines the rules and
regulation to support language integration. CLS ensures that any source
code to successfully compiled by .Net compiler can interoperate with .Net
framework or not.
(ii) CTS (Common Type System): This functionality provided by .Net
framework to communicate with different language. If two Languages (C#,
Vb.net, J#, VC++) want to communicate with each other then they have to
convert into some common type.
For example, Vb.net has Integer & C# has Int, so both are represented a
System.Int32

(iii) Garbage collector : See .Net Framework- Memory management


(iv) Manifest :
 Assembly manifest contains information about what contained within
the assembly.
 Assembly manifest contains list of other assembly required by assembly.
 It provides code access security instruction including permissions
required & denied.
 Manifest contains assembly metadata.

6th CE – Dot Net Technology Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(v) Namespace : Refer .Net Class Library


(vi) JIT (Jitter): In .Net all the source code are converted into Microsoft
intermediate language by the language specific compiler . By the use of JIT
compiler this Intermediate code is then converted into Native code which
is CPU specific. The JIT compiler is an important element of CLR, which loads
MSIL on target machines for execution.
(vii) Managed code :
 The code which is developed in .Net Framework is known as managed
code.
 This code is executed by CLR with Managed code execution.
 It Includes IL, CAS, Memory management, JIT etc..
 Any language written in .Net framework is Managed code.
 In Managed code, the memory allocation, type safety, security, etc.
handled by managed environment (CLR).
 Example – Vb.Net, C#

(viii) Unmanaged code :


 The code which is developed outside .Net Framework is known as
unmanaged code.
 This code is not Run under the take care of CLR.
 Unmanaged code executed by RCW (Runtime Callable wraper)
 In unmanaged code, the memory allocation, type safety, security, etc.
needs to be taken care of by the developer.
 Example – C, C++, VB6, COM
(ix) Side by side execution: See .Net Framework Implications.
(x) MSIL (IL) - Intermediate Language, is the compiled form of the .NET
language source code. When .NET source code is compiled by the language
specific compiler into Intermediate Language which is platform
independent. Safe code & unsafe code
(xi) Safe and Unsafe code :
 To make the language powerful we need direct access to the memory so
to make direct memory access unsafe code was invented.
 Unmanaged codes may use pointers and direct memory addresses.
 Unsafe still runs under the CLR, but it will let you access memory
directly through pointers.

3. What is DLL HELL Problem? How it solve?


Refer .Net Framework – Implications of CLR
4. Importance and Drawback of CLR
Refer .Net Framework

6th CE – Dot Net Technology Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

5. Explain Assembly Structure. Write a code to create shared assembly


and store the assembly in GAC using tools.
- Assembly is the unit of deployment like DLL and EXE.
- It is group of resources, types & references.
- Assembly is the self describing collection of code, resources and metadata.
- Assembly may contain the reference to other assembly.
- These resources, types & references are described in block called “Manifest”.
- Each Assembly has one and only one assembly manifest.
Assembly Menifest :
 Assembly manifest contains information about what contained within
the assembly.
 Assembly manifest contains list of other assembly required by assembly.
 It provides code access security instruction including permissions
required & denied.
 Manifest contains assembly metadata.

Assembly Metadata :
 It describes all classes & class member that are defined in assembly.
 Also describe classes & class member that the current assembly will call
from another assembly.
 It contains complete description of the method including the class,
return type & parameters.
 .Net language compiler will generate the metadata and store this in
assembly which containing IL.

- There are Two types of assemblies:

(1) Private assembly :


 It is used by single application and stored in application’s directory or
sub director
 Easy deployment no needs any fancy installation program. Just delete
from hard drive.
(2) Shared assembly :
 It is stored in global assembly cache (GAC). It is installed in GAC.
 It is globally accessible to all .Net application
 Shared assemblies are usually libraries of code which many applications
can use.
 For example – Crystal report classes which will used by all application
 GAC is located at C:\Windows\Assembly OR C:\Winnt\Assembly

6th CE – Dot Net Technology Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Steps to create shared assembly and store the assembly in


GAC using tools.

Step 1 : Creating our sample component (class library project)

Add Class library project from visual studio 2008 new project. Suppose name is dlltest

Create class file and one method that return simple string

public class Class1


{
public string display()
{
return "Hello Kitrc Kalol";
}
}
Step 2 : Create a strong key using the sn.exe tool

Go to .NET command interpreter, and type the following...

sn –k “C:\keyname.snk”

This will create a strong key and save it to the location C:\keyname.snk

Step 3 : Sign your component with the keyfile we just created

Go to the assemblyinfo.vb file of your project. Open this file. Add this Line in file

<Assembly: AssemblyKeyFile("C:\keyname.snk")>

Step 4 : Installing shared assembly in Global Assembly Cache

Go to .NET command interpreter, use the tool gacutil.exe


Type the following...

gacutil -I "C:\[PathToBinDirectoryInVSProject]\dlltest.dll"

To uninstall it, use... gacutil –u dlltest.dll

After hosting the assembly just go to WINNT\Assembly folder and you will find your
assembly listed there.

Step 5 : Access this assembly data or call it from other Client application.

6th CE – Dot Net Technology Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Just open console application and call it as below.

using System;
using System.Linq;
using System.Text;
using dlltest;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Class1 obj=new Class1();
Console.WriteLine(obj.display().ToString());
}
}
}

6th CE – Dot Net Technology Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)

Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture Notes
Chapter-2,3

Q-1. Explain Access Modifiers in C#

- Whenever a class is created by us we want to have the ability to decide who can
access certain members of the class. In other words, we would like to restrict access
to the members of the class.
- An access modifier is a keyword of the language that is used to specify the access
level of members of a class.
- C#.net supports the following access modifiers.
- Public, private, protected, internal and protected internal

Default Access Modifiers in C#

- Namespaces by default can have no accessibility modifiers at all. They are


public by default and we cannot add any other access modifier including public
again.
- Default access modifier for class, structure, Interface, Enum, Delegate is Internal. A
class can only be public or internal. It cannot be marked as protected or private.
- Default access modifier for class member and structure members is private.
- Interface members are always public and no access modifier can be applied.
- Enum members are always public and no access modifier can be applied.

Public: When Members of a class are declared as public, then they can be accessed

1. Within the class in which they are declared.


2. Outside the class within the same assembly. //when class is static
3. Outside the class outside the assembly. //when class is static
4. Within the derived classes of that class available within the same assembly.
5. Within the derived classes of that class available outside the assembly.

[ DOT NET TECHNOLOGY – 6th CE ] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Private: Private members of a class are completely restricted and are accessible
only within the class in which they are declared.

Protected: When Members of a class are declared as protected, then they can be
accessed
1. Within the class in which they are declared.
2. Within the derived classes of that class available within the same assembly.
3. Within the derived classes of that class available outside the assembly.

Internal: When Members of a class are declared as internal, then they can be
accessed
1. Within the class in which they are declared.
2. Within the derived classes of that class available within the same assembly.
3. Outside the class within the same assembly //when class is static

Protected internal: When Members of a class are declared as protected internal,


then they can be accessed
1. Within the class in which they are declared.
2. Within the derived classes of that class available within the same assembly.
3. Within the derived classes of that class available outside the assembly.
4. Outside the class within the same assembly. //when class is static

[ DOT NET TECHNOLOGY – 6th CE ] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Q-2. Explain Namespace , Constructor and Destructor in C#


Namesapce:
- Namespace is the logical group of related classes. Namespace provide many useful
services and objects that useful to write code in your application.
- Namespaces are heavily used in C# programming in two ways.
- First, the .NET Framework uses namespaces to organize its many classes, as follows:

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

- System is a namespace and Console is a class in that namespace.


- The using keyword can be used so that the complete name is not required, as in the
following example:

using System;
Console.WriteLine("Hello");
Console.WriteLine("World!");

- Second, declaring your own namespaces can help you control the scope of class and
method names in larger programming projects.
- Use the namespace keyword to declare a namespace, as in the following example:

namespace SampleNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(“HELLO KITRC KALOL");
}
}
}

Constructor

- Constructors are special methods (Member functions) which called when a class is
instantiated.
- Constructor is called when object is created.
- Constructor will not return anything.
- Constructor name is same as class name.
- By default C# will create default constructor internally.

[ DOT NET TECHNOLOGY – 6th CE ] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Constructor with no arguments and nobody is called default constructor.


- Constructor with arguments is called parameterized constructor.
- Constructor can be overloaded means we can have several constructors with the
same name, but different parameters.
- Constructor by default public.
- Constructor can be a static.
- A static constructor cannot be a parameterized constructor.
- Within a class you can create only one static constructor.

Default Constructor:

- A constructor without any parameters is called as default constructor.


Drawback of default constructor is every instance of the class will be
initialized to same values and it is not possible to initialize each instance
of the class to different values.
- When you are not creating a constructor in the class, then compiler will
automatically create a default constructor in the class that initializes all
numeric fields in the class to zero and all string and object fields to null.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
oopdemo obj = new oopdemo();
Console.ReadLine();
}
}

class oopdemo
{
public oopdemo()
{
Console.WriteLine("Hello Constructor");
}
}
}

Output: Hello Constructor

[ DOT NET TECHNOLOGY – 6th CE ] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Parameterized Constructor:

- A constructor with at least one parameter is called as parameterized


constructor. Advantage of parameterized constructor is you can initialize
each instance of the class to different values.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
oopdemo obj1 = new oopdemo();
oopdemo obj2 = new oopdemo(20,30);
Console.ReadLine();
}
}

class oopdemo
{
public oopdemo()
{
Console.WriteLine("Default Constructor");
}

public oopdemo(int a, int b)


{
Console.WriteLine("Two Parameter Constructor");
}
}
}

Static Constructor:

- You can create a constructor as static and when a constructor is created


as static, it will be invoked only once for any number of instances of the
class and it is during the creation of first instance of the class or the first
reference to a static member in the class.
- Static constructor is used to initialize static fields of the class and to write
the code that needs to be executed only once.

[ DOT NET TECHNOLOGY – 6th CE ] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

namespace ConsoleApplication1
{
class Test3
{
public Test3()
{

Console.WriteLine("Instance Constructor");
}

static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
//Static Constructor and instance constructor,
both are invoked for first instance.

Test3 T1 = new Test3();

//Only instance constructor is invoked.

Test3 T2 = new Test3();

Console.ReadLine();
}
}
}

Output:

Destructor:

- A destructor is a special method of the class that is automatically invoked


while an instance of the class is destroyed.
- Destructor is used to write the code that needs to be executed while an
instance is destroyed.

[ DOT NET TECHNOLOGY – 6th CE ] Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- To create a destructor, create a method in the class with same name as


class preceded with ~ symbol.
- The .NET framework has an in built mechanism called Garbage Collection to de-
allocate memory occupied by the un-used objects. It internally uses the destruction
method to clean up the un-used objects.
- But Sometimes the programmer needs to do manual cleanup therefore Destructor is
used.

Syntax:

~ClassName()
{

- Remember that a destructor can't have any modifiers like private, public etc. If we
declare a destructor with a modifier, the compiler will show an error.
- Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
- There is no parameterized destructor in C#.

namespace ConsoleApplication1
{
class Example
{
public Example()
{
Console.WriteLine("Constructor");
}
~Example()
{
Console.WriteLine("Destructor");
}
}
class Program
{
static void Main()
{
Example x = new Example();
}
}
}

Output: Constructor
Destructor

[ DOT NET TECHNOLOGY – 6th CE ] Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Q-3. Explain Function Overloading and Inheritance in C# with Example.

Overloading:

- The process of creating more than one method in a class with same name or creating
a method in derived class with same name as a method in base class is called as
method overloading.
- In VB.net when you are overloading a method of the base class in derived class, then
you must use the keyword “Overloads”.
- But in C# no need to use any keyword while overloading a method either in same
class or in derived class.

- Example of Overloading
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
yyy a = new yyy();
a.abc(10);
a.abc("bye");
a.abc("no", 100);
Console.ReadLine();
}
}

class yyy
{
public void abc(int i)
{
System.Console.WriteLine("abc" + i);
}
public void abc(string i)
{
System.Console.WriteLine("abc" + i);
}
public void abc(string i, int j)
{
System.Console.WriteLine("abc" + i + j);
}
}
}

- Here the class yyy has three functions, all of them having the same name abc.
- The difference between them is in the data types of the parameters. They are all

[ DOT NET TECHNOLOGY – 6th CE ] Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

different.
- In C# we are allowed to have functions with the same name, but having different
data types parameters.
- The advantage is that we call the function by the same name as by passing different
parameters, a different function gets called. This feature is called function
overloading.
- All is fine only if the parameter types to the function are different. We do not have to
remember a large number of functions by name.
- The only reason why function overloading works is that C# does not know a function
by name, but by its signature.
- Signature means methods must have same name, same number of arguments and
same type of arguments.

Overriding:

- Creating a method in derived class with same signature as a method in base class is
called as method overriding.
- Same signature means methods must have same name, same number of arguments
and same type of arguments.
- Method overriding is possible only in derived classes, but not within the same class.
- When derived class needs a method with same signature as in base class, but wants
to execute different code than provided by base class then method overriding will be
used.
- To allow the derived class to override a method of the base class, C# provides
two options, virtual methods and abstract methods.
- Virtual keyword is used in Base Class and Override keyword used in Derive class

Overriding example using virtual methods

namespace methodoverriding
{
class BaseClass
{
public virtual string YourCity()
{
return "INDIA";
}
}

class DerivedClass : BaseClass

[ DOT NET TECHNOLOGY – 6th CE ] Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

{
public override string YourCity()
{
return "USA";
}
}

class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}

Output : USA

Virtual

- Virtual properties can behave like abstract methods, except virtual method has
method body. The implementation of a virtual member can be changed by overriding
member in derive class

Overriding example using Abstract methods

namespace methodoverriding
{
abstract class BaseClass
{
public abstract string YourCity();

class DerivedClass : BaseClass


{
public override string YourCity() //It is mandatory to
implement absract method
{
return "London";
}

private int sum(int a, int b)


{
return a + b;
}

[ DOT NET TECHNOLOGY – 6th CE ] Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}

Output : Londan

Abstract:

- Abstract classes cannot be instantiated and may contain abstract methods.


- A non-abstract class derived from abstract class must include implementations of all
inherited abstract methods and accessors.
- Abstract method declarations are only permitted in abstract classes.
- Abstract method has no method body
- it’s an error to use “static” or “virtual” in abstract method declaration

Override:

An override method provides a new implementation of a member inherited from a


base class. We cannot override non-virtual methods or static method. The override
base method must be virtual, abstract, or override.

Inheritance

- One of the most important concepts in object-oriented programming is that of


inheritance.
- Acquiring (taking) the properties of one class into another class is called inheritance.
- Inheritance provides reusability by allowing us to extend an existing class.
- This also provides an opportunity to reuse the code functionality and fast
implementation time.
- When creating a class, instead of writing completely new data members and member

[ DOT NET TECHNOLOGY – 6th CE ] Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

functions, the programmer can designate that the new class should inherit the
members of an existing class. This existing class is called the base class, and the
new class is referred to as the derived class.

(1) Single Inheritance

It is the type of inheritance in which there is one base class and one derived
class.

namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
rectangle r1 = new rectangle();
circle c1 = new circle();
r1.area();
c1.area();

[ DOT NET TECHNOLOGY – 6th CE ] Page 12


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

c1.volume();
Console.ReadLine();
}
}

class rectangle
{
public void area()
{

Console.WriteLine("the area of rectagle....");


}
}
class circle : rectangle
{
public void volume()
{
Console.WriteLine("the volume of circle....");
}
}
}

Output: the area of rectagle....


the area of rectagle....
the volume of circle....

(2) MultiLevel Inheritance

When one class is derived from another derived class then this type of
inheritance is called multilevel inheritance.

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
rectangle r1 = new rectangle();
circle c1 = new circle();
square s1 = new square();

s1.dimension();
s1.volume();
Console.ReadLine();
}
}

class rectangle
{

[ DOT NET TECHNOLOGY – 6th CE ] Page 13


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

public void area()


{
Console.WriteLine("the area of rectagle....");
}
}
class circle : rectangle
{
public void volume()
{
Console.WriteLine("the volume of circle....");
}
}
class square : circle
{
public void dimension()
{
Console.WriteLine("the dimension of square.");
}
}
}

Output: the dimension of square.


the volume of circle....

(3) Hierarchical Inheritance

This is the type of inheritance in which there are multiple classes derived from
one base class.

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
rectangle r1 = new rectangle();
circle c1 = new circle();
square s1 = new square();

s1.area();
c1.area();
Console.ReadLine();
}
}

[ DOT NET TECHNOLOGY – 6th CE ] Page 14


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

class rectangle
{
public void area()
{
Console.WriteLine("the area of rectagle");
}
}
class circle : rectangle
{
public void volume()
{
Console.WriteLine("the volume of circle");
}
}
class square : rectangle
{
public void dimension()
{
Console.WriteLine("the dimension of square");
}
}
}

Output: the area of rectagle


the area of rectagle

Q-4. Demonstrate use of Property and Indexer in C#.

Property:

- Very few programming languages support the notion of a property.

- Unlike a variable, a property is not stored in a memory location. It is made up of


functions.
- Property has the advantage over variable is that code gets called.

- When we initialize a variable, no code in our class gets called. We are not able to
execute any code for a variable access or initialization at all.

- In the case of a property, we can execute tons of code. This is one singular reason
for the popularity of a product like Visual Basic - the use of properties.

- The reason we use a property and not a variable is because if we change the value of
a variable/field, then code in our class is not aware of the change. Also we have no
control over what values the variable will contain.
- Using a property, reading or writing to the variable also can be monitored.

[ DOT NET TECHNOLOGY – 6th CE ] Page 15


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Properties are named members of classes, structure, and interfaces. They provide a
flexible mechanism to read, write, or compute the values through accessors.
- The properties of a Base class can be inherited to a Derived class.
- There are two types of accessors: get & set
- The set accessor is used to set the value to variable.
- The get accessor is used to return the value of variable.
- A property should have at least one accessor
- Syntax of set and get

set {accessor-body}

get {accessor-body}

- There are several kinds of property in c#:

Read and Write (2) Read Only (3) Static (4) Interface property (5) Auto-implemented

1. Read and Write Property:


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class1 obj = new Class1();

obj.name = "A R Kazi"; //set accessor is invoked

Console.WriteLine("Your Name is= " + obj.name);

//get accessor is invoked here

Console.ReadLine();
}
}

class Class1
{
private string myname;

public string name


{
get
{
return myname;

[ DOT NET TECHNOLOGY – 6th CE ] Page 16


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

}
set
{
myname = value;
}
}
}

2. Read Only Property:

- Properties that do not implement a set accessor are read only.


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class1 obj = new Class1();

Console.WriteLine("Your Name is= " + obj.name);

//get accessor is invoked here

Console.ReadLine();
}
}

class Class1
{
private string myname="A R Kazi";

public string name


{
get
{
return myname;
}

}
}

[ DOT NET TECHNOLOGY – 6th CE ] Page 17


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

3. Static Property:

- C# also supports static properties, which belongs to the class rather than to the objects
of the class. All the rules applicable to a static member are applicable to static
properties also.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Class1 o1 = new Class1();
Console.WriteLine(Class1.counter);
}

Console.ReadLine();
}
}

class Class1
{
private static int number = 0;

public Class1() //Constructor


{
number++;
}

public static int counter //Static Property


{
set
{
number = value;
}

get
{
return number;
}
}
}

[ DOT NET TECHNOLOGY – 6th CE ] Page 18


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Indexer:

- An indexer allows an object to be indexed like an array. When you define an indexer for
a class, this class behaves like a virtual array.
- You can then access the instance of this class using the array access operator ([ ]).
- Like properties, you use get and set accessors for defining an indexer.
- However, properties return or set a specific data member, whereas indexers returns or
sets a particular value from the object instance. In other words, it breaks the instance
data into smaller parts and indexes each part, gets or sets each part.
- Property defines with a property name while Indexers are not defined with names, but
with the this keyword, which refers to the object instance.
- Indexers can be overloaded. Indexers can also be declared with multiple parameters and
each parameter may be a different type.
- Syntax :
element-type this[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
// The set accessor.
set
{
// set the value specified by index
}

Example:

namespace indexer
{
class Program
{
static void Main(string[] args)
{
Class1 list = new Class1();
list[0] = "A R K";
list[1] = "S K P";
list[2] = "N D P";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(list[i]);

[ DOT NET TECHNOLOGY – 6th CE ] Page 19


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

}
Console.ReadLine();
}
}

class Class1
{
string[] name = new string[3];
public string this[int index]
{
set
{
name[index] = value;
}
get
{
return (name[index]);
}

}
}

Q-5. Difference between Property and Indexer in C#.

Property Indexer
Properties don't use "this" keyword and Indexers are created by using "this"
identified by simple names. keyword and identified by its
signature.
Allows methods to be called as if they Allows elements of an internal collection of
were public data members. an object to be accessed by using array
notation on the object itself.
Accessed through a simple name. Accessed through an index.
Property cannot be overload Indexer can be overload
Can be a static or an instance Must be an instance member.
member. Indexer is an instance member so can't be
Property can be static. static
A get accessor of a property has no A get accessor of an indexer has the
parameters. same formal parameter list as the
indexer.
A set accessor of a property contains the A set accessor of an indexer has the same
implicit value parameter. formal parameter list as the indexer, and
also to the value parameter.

[ DOT NET TECHNOLOGY – 6th CE ] Page 20


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Q-6. Explain Reflection in C#.

- Sometimes it is necessary to know how many objects, methods, properties etc in our
program while our program is executing or running. And for that we could always read
the documentation if we wanted to know more about the functionality of a class.
- But, C# gives us a large number of functions that tell us the innards of a class.
- These functions put together have to be used in a certain way. The functions have to be
called in a certain order and the parameters to them have to conform to certain data
types. This concept is called an API or Application Program Interface.
- In short, an API is how a programmer uses functions to get a desired result.
- By using Reflection in C#, we can able to find out details of an object, method and also
create objects and invoke methods at runtime.
- The System.Reflection namespace contains classes and interfaces that provide a
managed view of loaded types, methods and fields with the ability to dynamically create
and invoke types.
- When writing a C# code that uses reflection, the coder can use the typeof operator to
get the object's type or use the GetType() method to get the type of the current
instance.

Example:

namespace ConsoleApplication2
{
class zzz
{
public static void Main()
{
Type m;
m = typeof(int);
System.Console.WriteLine(m.Name + " " + m.FullName);
m = typeof(System.Int32);
System.Console.WriteLine(m.Name + " " +
m.FullName); m = typeof(yyy);

System.Console.WriteLine(m.Name + " " +


m.FullName); Console.ReadLine();
}
}
class yyy

[ DOT NET TECHNOLOGY – 6th CE ] Page 21


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

{
}
}

Output

Q-7. Base Class Library.

.Net Namespaces Explanation


System 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.

System.Collections This namespace contains interfaces and classes that


define various collections of objects, such as lists,
queues, bit arrays, hash tables and dictionaries.
System.Collections.Generic This namespace contains interfaces and classes that
define generic collections, which allow users to create
strongly typed collections that provide better type safety
and performance than non-generic strongly typed
collections, such as LinkedList<T>, SortedList<TKey,
TValue>.
System.Data
System.Data.Odbc These namespaces are used for interacting with
System.Data.OracleClient relational databases using ADO.NET.
System.Data.OleDb
System.Data.SqlClient
System.IO These namespaces define numerous types used to work
System.IO.Compression with file I/O, compression of data, and port
System.IO.Ports manipulation.
System.Reflection This namespace contains types that retrieve information
System.Reflection.Emit about assemblies, modules, members, parameters, and
other entities in managed code, such as Assembly,
AssemblyName, Module.
System.Runtime.InteropServices This namespace provides a wide variety of members
that support COM(Component Object Model) interop
and platform invoke services.
System.Drawing The System.Drawing namespace provides access to
GDI+ basic graphics functionality. Like-Brush, Font,
Image.

[ DOT NET TECHNOLOGY – 6th CE ] Page 22


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

System.Windows.Forms This namespace contains classes for creating Windows-


based applications
System.Windows The System.Windows namespace is the root for several
System.Windows.Controls new namespaces (introduced with .NET 3.0) that
System.Windows.Shapes represent the Windows Presentation Foundation (WPF)
UI toolkit.
System.Linq These namespaces define types used when
System.Xml.Linq programming against the LINQ API.
System.Data.Linq
System.Web This namespace supplies classes and interfaces that
enable browser-server communication. This namespace
includes the HttpRequest class, which provides extensive
information about the current HTTP request;
theHttpResponse class, which manages HTTP output to
the client; and the HttpServerUtility class, which
provides access to server-side utilities and processes.
System.ServiceModel This is one of many namespaces used to build
distributed applications.
System.Threading This namespace defines numerous types to build
multithreaded applications.
System.Security In the security namespaces, you find numerous types
dealing with permissions, cryptography, and so on.
System.Xml This namespaces contain numerous types used to
interact with XML data.

Q-8. Explain String Manipulation with String Function and Methods.

- string is another kind of data type that represents Unicode Characters.


- It is the alias of System.String however, you can also write System.String
instead of string.
- It is the sequence of character in which each character is a Unicode
character.
- There is no difference between string and String because string is the alias
of System.String.
- Most of the developers get confused what to use between sting and String.
Technically there is no difference between them and they can use any of
them. However, you will have to use “using System” to use the String in C#.
- Another difference is String is a class name whereas string is a reserved
keyword. You should always use string instead of String.

C# String Function :

[ DOT NET TECHNOLOGY – 6th CE ] Page 23


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

String Functions Definitions


Clone() Make clone of string.
Compare two strings and returns integer value as output. It returns 0
CompareTo()
for true and 1 for false.
The C# Contains method checks whether specified character or string
Contains()
is exists or not in the string value.
This EndsW ith Method checks whether specified character is the last
EndsWith()
character of string or not.
The Equals Method in C# compares two string and returns Boolean
Equals()
value as output.
GetHashCode() This method returns HashValue of specified string.
GetType() It returns the System.Type of current instance.
GetTypeCode() It returns the Stystem.TypeCode for class System.String.
IndexOf() Returns the index position of first occurrence of specified character.
ToLower() Converts String into lower case based on rules of the current culture.
ToUpper() Converts String into Upper case based on rules of the current culture.
Insert() Insert the string or character in the string at the specified position.
This method checks whether this string is in Unicode normalization
IsNormalized()
form C.
LastIndexOf() Returns the index position of last occurrence of specified character.
Length It is a string property that returns length of strin g.
This method deletes all the characters from beginning to specified
Remove()
index position.
Replace() This method replaces the character.
Split() This method splits the string based on specified value.
It checks whether the first character of string is same as specified
StartsWith()
character.
Substring() This method returns substring.
ToCharArray() Converts string into char array.
Trim() It removes extra whitespaces from beginning and ending of string.

Examples:

namespace ConsoleApplication3
{

[ DOT NET TECHNOLOGY – 6th CE ] Page 24


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

class Program
{
static void Main(string[] args)
{
string firstname="kazi azhar";
string lastname="kalol";

Console.WriteLine(firstname.Clone());

// Make String Clone

Console.WriteLine(firstname.CompareTo(lastname));

//Compare two string value and returns 0 for true and 1 for false

Console.WriteLine(firstname.Contains("az"));

//Check whether specified value exists or not in string

Console.WriteLine(firstname.EndsWith("r"));

//Check whether specified value is the last character of string

Console.WriteLine(firstname.Equals(lastname));

//Compare two string and returns true and false

Console.WriteLine(firstname.GetHashCode());

//Returns HashCode of String

Console.WriteLine(firstname.GetType());

//Returns type of string

Console.WriteLine(firstname.IndexOf("z"));

//Returns the first index position of specified value

Console.WriteLine(firstname.ToLower());

//Covert string into lower case

Console.WriteLine(firstname.ToUpper());

//Convert string into Upper case

Console.WriteLine(firstname.Insert(0, "Hello"));

//Insert substring into string

Console.WriteLine(firstname.LastIndexOf("z"));

[ DOT NET TECHNOLOGY – 6th CE ] Page 25


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

//Returns the last index position of specified value

Console.WriteLine(firstname.Length);

//Returns the Length of String

Console.WriteLine(firstname.Remove(7));

//Deletes all the characters from begining to specified index.

Console.WriteLine(firstname.Replace('a','m'));

//Replace the character

Console.WriteLine(firstname.Substring(2,5));

//Returns substring

Console.WriteLine(firstname.Trim());

//It removes starting and ending white spaces from string.

Console.ReadLine();

}
}
}
Output

Q-9. Explain Files & I/O classes and methods.


- A file is a collection of data stored in a disk with a specific name and a directory path.
- When a file is opened for reading or writing, it becomes a stream.
- The stream is basically the sequence of bytes passing through the communication path.

[ DOT NET TECHNOLOGY – 6th CE ] Page 26


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- There are two main streams: the input stream and the output stream.
- The input stream is used for reading data from file (read operation) and the output
stream is used for writing into the file (write operation).

C# I/O Classes

- The System.IO namespace has various classes that are used for performing operations
with files, such as creating and deleting files, reading from or writing to a file, closing a
file etc.

The following table shows some commonly used classes in the System.IO namespace:

I/O Class Description

BinaryReader Reads primitive data from a binary stream.

BinaryWriter Writes primitive data in binary format.

BufferedStream A temporary storage for a stream of bytes.

Directory Helps in manipulating a directory structure.

DirectoryInfo Used for performing operations on directories.

DriveInfo Provides information for the drives.

File Helps in manipulating files.

FileInfo Used for performing operations on files.

FileStream Used to read from and write to any location in a file.

MemoryStream Used for random access to streamed data stored in


memory.
Path Performs operations on path information.

StreamReader Used for reading characters from a byte stream.

StreamWriter Is used for writing characters to a stream.

StringReader Is used for reading from a string buffer.

StringWriter Is used for writing into a string buffer.

[ DOT NET TECHNOLOGY – 6th CE ] Page 27


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

The FileStream Class

- The FileStream class in the System.IO namespace helps in reading from, writing to and
closing files. This class derives from the abstract class Stream.
- You need to create a FileStream object to create a new file or open an existing file.
- The syntax for creating a FileStreamobject is as follows:

FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>,


<FileAccess Enumerator>, <FileShare Enumerator>);

Description

FileMode The FileMode enumerator defines various methods for


opening files. The members of the FileMode enumerator
are:
 Append: It opens an existing file and puts cursor at the end
of file, or creates the file, if the file does not exist.
 Create: It creates a new file.
 CreateNew: It specifies to the operating system, that it
should create a new file.
 Open: It opens an existing file.
 OpenOrCreate: It specifies to the operating system that it
should open a file if it exists, otherwise it should create a
new file.
 Truncate: It opens an existing file and truncates its size to
zero bytes.

FileAccess FileAccess enumerators have


members: Read,ReadWrite and Write.

FileShare FileShare enumerators have the following members:


 Inheritable: It allows a file handle to pass inheritance to
the child processes
 None: It declines sharing of the current file
 Read: It allows opening the file for reading
 ReadWrite: It allows opening the file for reading and

[ DOT NET TECHNOLOGY – 6th CE ] Page 28


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

writing
 Write: It allows opening the file for writing

Q-10. A simple program for reading and writing into the file.
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
// Compose a string that consists of three lines.
string lines =" hi kitrc.\n hello kitrc.\n welcome in kitrc.";
// Write the string to a file.
StreamWriter file = new StreamWriter("d:\\test.doc");
file.WriteLine(lines);
file.Close();
// Create an instance of StreamReader to read from a file.
StreamReader sr = new StreamReader("d:\\test.doc");
string line;
// Read and display lines from the file until the end of the file.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
Console.ReadLine();
}
}
}
Output :

[ DOT NET TECHNOLOGY – 6th CE ] Page 29


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Q-11. Explain concept of collections in C #.


- C# Collections are data structures that holds data in different ways for flexible
operations.
- C# Collection classes are defined as part of the System.Collections or
System.Collections.Generic namespace.

(1) ArrayList Class

- ArrayList is one of the most flexible data structure from CSharp Collections.
- ArrayList contains a simple list of values.
- ArrayList implements the IList interface using an array and we can add , insert ,
delete , view array elements easily.
- It is very flexible because we can add without any size information , we can remove
any elements also we can add elements dynamically.

Common Properties and Methods of ArrayList

Add: Add an Item in an ArrayList


Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remove an item from a specified position
Sort : Sort Items in an ArrayList

How to add an Item in an ArrayList ?

Syntax : ArrayList.add(object)
object : The Item to be add the ArrayList
ArrayList arr;
arr.Add("Item1");

How to Insert an Item in an ArrayList ?

Syntax : ArrayList.insert(index,object)
index : The position of the item in an ArrayList
object : The Item to be add the ArrayList
ArrayList arr;
arr.Insert(3, "Item3");

How to remove an item from arrayList ?

Syntax : ArrayList.Remove(object)
object : The Item to be add the ArrayList

[ DOT NET TECHNOLOGY – 6th CE ] Page 30


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

arr.Remove("item2")

How to remove an item in a specified position from an ArrayList ?

Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)

How to sort ArrayList ?

Syntax : ArrayList.Sort()

Example:

protected void Button1_Click(object sender, EventArgs e)


{
ArrayList ItemList = new ArrayList();

ItemList.Add("Item1");
ItemList.Add("Item2");
ItemList.Add("Item3");
ItemList.Add("Item4");
ItemList.Add("Item5");

ListBox1.DataSource = ItemList;
ListBox1.DataBind();

//insert an item
ItemList.Insert(3, "Item6");
//sort itemms in an arraylist
ItemList.Sort();
//remove an item
ItemList.Remove("Item1");
//remove item from a specified index
ItemList.RemoveAt(3);

ListBox2.DataSource = ItemList;
ListBox2.DataBind();
}
Output:

[ DOT NET TECHNOLOGY – 6th CE ] Page 31


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(2) Stack Class

- The Stack represents a list with last-in-first-out (LIFO).


- Stack follows the push-pop operations.
- We can Push (insert) Items into Stack and Pop (retrieve) it back.
- We can push the items into a stack and get it in reverse order.
- Using POP, Stack returns the last item first.

Common Properties and Methods of Stack

Push : Add (Push) an item in the Stack data structure


Pop : Pop return the last Item from the Stack
Contains: Check the object contains in the Stack

How to Push an item in the Stack data structure

Syntax : Stack.Push(Object)
Object : The item to be inserted.
Stack days = new Stack ();
days.Push("Sunday");

How to Pop an Item

Syntax : Object Stack.Pop()


Object : Return the last object in the Stack
days.Pop();

How to Check the object contains in the Stack

Syntax : Stack.Contains(Object)
Object : The specified Object to be search
days.Contains("Tuesday");

protected void Button2_Click(object sender, EventArgs e)


{
Stack days = new Stack();
days.Push("SunDay");
days.Push("MonDay");
days.Push("TueDay");
days.Push("WedDay");
days.Push("ThuDay");
days.Push("FriDay");
Label1.Text=days.Pop().ToString()
}

[ DOT NET TECHNOLOGY – 6th CE ] Page 32


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(2) Queue Class

- The Queue works like FIFO system , a first-in, first-out collections.


- Objects stored in a Queue are inserted at one end and removed from the other.
- The Queue provide additional insertion, extraction, and inspection operations.
- We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue)
item from Queue.

Important functions in the Queue Class are follows:

Enqueue : Add an Item in Queue


Dequeue : Remove the oldest item from Queue
Peek : Get the reference of the oldest item

Enqueue: Add an Item in Queue

Syntax : Queue.Enqueue(Object)
Object : The item to add in Queue
days.Enqueue("Sunday");

Dequeue: Remove the oldest item from Queue (we don't get the item later)

Syntax : Object Queue.Dequeue()


Returns : Remove the oldest item and return.
days.Dequeue();

protected void Button3_Click(object sender, EventArgs e)


{
Queue days = new Queue();

days.Enqueue("SunDay");
days.Enqueue("MonDay");
days.Enqueue("TueDay");
days.Enqueue("WedDay");
days.Enqueue("ThuDay");
days.Enqueue("FriDay");

Label1.Text = days.Dequeue().ToString();
}

Output:

[ DOT NET TECHNOLOGY – 6th CE ] Page 33


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Q-12. Explain Debugging and Error handling in C #.Net


Error handling:

- Programming errors are generally three types:


(1) Design-time errors (Syntax errors) (2) Runtime errors (3) Logical errors.

- A Design-time error is also known as a syntax error. These occur when the
environment you're programming doesn't understand your code. These are easy to
track down in C#.NET, because you get a red marks pointing them out. If you try to
run the program, you'll get error.
- Runtime errors are hard to track. As their name suggests, these errors occur when
the program is running. They happen when your program tries to do something it
shouldn't be doing. An example is trying to access a file that doesn't exist. Runtime
errors usually cause your program to crash. After all, you're the programmer, and
you should write code to trap runtime errors. If you're trying to open a database in a
specific location, and the database has been moved, a Runtime error will occur. It's
your job to predict a thing like this, and code accordingly.
- Logic errors also occur when the program is running. They happen when your code
doesn't quite behave the way you thought it would. A classic example is creating an
infinite loop of the type "Do While x is greater than 10". If x is always going to be
greater than 10, then the loop has no way to exit, and just keeps going round and
round. Logic errors tend not to crash your program but they will ensure that it
doesn't work properly.
Exception Handling

- C#.NET uses the .NET Framework's standard mechanism for error reporting called
Exception Handling.
- Exceptions are classes that trap the error information.
- To utilize .NET's Exception Handling mechanisms, developers need to write smart
code that watches out for exceptions and implement code to deal with these
exceptions.
- Exceptions provide a way to transfer control from one part of a program to another.

[ DOT NET TECHNOLOGY – 6th CE ] Page 34


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- C# exception handling is built with four keywords:


try:
It is 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.
throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

- You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception.

- C# exceptions are represented by classes.


- The exception classes in C# are directly or indirectly derived from the
System.Exception class.
- Some of the exception classes derived from the System.

[ DOT NET TECHNOLOGY – 6th CE ] Page 35


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Exception Classes in C#

- There are another Exception classes in C#, search about it.


Example:

class Program
{
public static void division(int num1, int num2)
{
float result = 0;
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception Error ! divide by zero");
Console.WriteLine("\nException caught: {0}", e);
}
finally
{
Console.WriteLine("\nResult: {0} ", result);
}
}
static void Main(string[] args)
{
division(10, 0);
Console.ReadLine();
}
}

[ DOT NET TECHNOLOGY – 6th CE ] Page 36


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

[ DOT NET TECHNOLOGY – 6th CE ] Page 37


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)


Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture notes
Chapter-4

1. Benefits of ADO.NET. Also Compare ADO.NET with Classic ADO.

ADO.NET ADO (ActiveX Data Objects)

1 CLR Based Library It is COM based Library

2 Disconnected architecture Ado requires active connection. Connection


oriented architecture

3 Data stored in XML Data stored in Binary form

4 XML integration possible XML integration not possible

5 Locking not available Locking feature is available

6 It is use dataset for data access It is use recordset object for data access

7 Dataset can have multiple tables In recordset we can have only one table

8 Firewall proof (Because of XML) Firewall might prevent execution of classic ado
and its execution will never be
interrupted

9 The performance in ADO.NET is Performance low


higher in comparison to ADO
because ADO uses COM

10 Use all .NET Providers Use OleDb & Odbc providers

Note: You have to explain each & every points in short.

Benefits of ADO.NET:

1. Interoperatibilty:
- ADO.NET stored data in XML format, so it can be used by any OS which has XML
components to read the xml documents.

[DOT NET TECHNOLOGY – 6th CE] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Ado.net supports dual programming model.

2. Maintainability:

- ADO.NET supports two-tier & three-tier (levels) applications.


- So in client server two-tier Applications, if you changed in ADO.NET on sever side then
it will easily reflect into the client side.
- Due to multiple tiers you can manage application in efficient way.

3. Programmability:

- ADO.NET classes are grouped together according to their functionality.


- So it is easy to use appropriate class as well as methods of each class.
- Line of code reduced due to the concept of Namespace.

4. Scalability:
- ADO.NET supports disconnected architecture with database, so the limited databases
Resources can be used by several users, and it does not support Locking system of
database, so the limited databases cannot be locked.

5. Performance:
- ADO.NET provides fast execution of disconnected applications using DataSet over
Recordset (in classical ADO), because there can be multiple tables per DataSet while
only one table per Recordset.

Note: Also here you can add points from comparison

2. Explain Characteristics of ADO.Net

(1) Disconnected access

- This is most important characteristics of Ado.net.


- Previous database access technology, provided continuously connected data
access.
- An application creates connection to database and keeps the connection open for
the life of the application.
- However if application become more complex and database serve more and more
clients, connected data access is impractical or make a problem.

[DOT NET TECHNOLOGY – 6th CE] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Open database connection is Expensive in terms of system resources. More


connection then more system resources required to handle it. So performance
decreased.
- Ado.net provides disconnected database access. In this model data access
connections are establish and left open only for a certain requirement.
- For example if you want to load data from database, just open connection, load
data into application & close connection.
- If you want to update the data then just open the connection, execute update
command and close again.
- In this case connection is open only for minimum require time. So ado.net saves
system resources so data access fast & increase the performance.
(2) Data store as XML (Dual programming model)

- Ado.net use XML (Extensive Markup Language) to store data while Ado data stores
in binary format.
- In reality, when we retrieve information from a database into an ADO.NET DataSet,
the data is stored in memory in an XML format.
- If we want we can modify values, remove rows and add new records using XML in
.Net
- So its provide Dual programming model.
(3) Managed code

- Like .Net class library component, Ado.net is the managed code environment which
means it can be used easily in .net application
- While ADO use COM to communicate and it is unmanaged code. So you have to
jump again & again from unmanaged code to managed code. That will reduce the
efficiency of program.
(4) Data providers

- ADO support OLEDB provider, Ado.net support exactly same. OLEDB jump from
managed to unmanaged.
- Ado.net support new managed provider like SqlServer data provider.

(5) Cross-Language Support

- ADO wasn't really designed for cross-language use. It was aimed primarily at VB
programmers.
- While ADO.Net supports multiple languages.

[DOT NET TECHNOLOGY – 6th CE] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

3. Explain All ADO.Net Namespace

The ADO.NET hold mainly six namespaces in the .NET class library.

(1) System.Data:
- Contains fundamental classes with the core ADO.NET functionality.
- It contains classes used by all data providers.
- These include DataSet and DataRelation, which allow us to manipulate structured
relational data.
- These classes are totally independent of any specific type of database or the way
we use to connect to it.
(2) System.Data.Common:
- All Data provider share these classes.
- These classes are not used directly in the code. Instead, they are used by other
classes.
- Example DbConnection, DbCommand, DbDataAdapter etc...
(3) System.Data.OleDb
- This namespace is used to use OleDbDataSource using OleDbDataProvider.
- If you want to make database connectivity with access database import this
namespace.
- It contains the classes like OleDbCommand and OleDbConnection.
(4) System.Data.SqlClient
- This namespace is used to use SqlDataSource
- If you want to make database connectivity with Microsoft SQL Server database
import this namespace.
- It contains the classes like SqlCommand and SqlConnection.

(5) System.Data.Odbc
- This namespace is used to use OdbcDataSource using OdbcDataProvider.
- If you want to make database connectivity with Oracle database import this
namespace.
- It contains the classes like OdbcCommand and OdbcConnection.
(6) System.Data.SqlTypes
- This Namespace is used to represents specific DataTypes for the SqlServer
Database.

[DOT NET TECHNOLOGY – 6th CE] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

4. Explain Different ADO.NET Objects.


(1) Connection Object
- Connection object allow you to establish a connection.
- Connection object is used to make the link between data source and application.
- Connection object discover the data source and login to it properly.
- This information provided by ConnectionString
- Connection object for different providers: SqlConnection, OleDbConnection,
OdbcConnection
- Properties of Connection object.

DataSource Returns the Name of the instance of database


Database Returns the Name of the Database to use after connection
open.
State It returns the current status of the database whether it is
Broken, Closed, Connecting, Executing, Fetching and Open.
ConnectionString It is used to connect the database with database path string.
It provides full information regarding database like name of
database, name of database server, username password etc…

(2) Command Object


- Command object uses the connection object to execute the Query.
- Command object is used to write the query and then execute it.
- The query can be in the form of text, stored procedure or direct table format.
- Command object provides a number of Execute methods to execute the query.
- Properties of Command object

CommandText Retrieve either query statement or stored procedure


CommandType It is used to specify the type of query whether text, stored
procedure or direct table.
Connection Set Connection object which is used by this Command object

CommandTimeout - Returns no. of seconds wait while attempting to execute a


command.
- Command is aborted after Timeout. And Default 30 seconds

- Command Object’s Execute methods

ExecuteNonQuery It is used to execute insert, update & delete queries and it


returns the number of rows affected.
ExecuteReader It executes the command and it is read-only, forward-only

[DOT NET TECHNOLOGY – 6th CE] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

cursor that allow you to retrieve Rows from DataSource


ExecuteScalar It execute the command and return the first column of first row

(3) DataReader
- DataReader object is a simple forward only and Read only cursor.
- It requires live connection with the DataSource.
- This object cannot be directly instantiated instead you must call the ExecuteReader
method of the command object to get valid DataReader object.
- Be sure to close the Connection when you use DataReader otherwise Connection
stays alive until it is explicitly closed.
- You can close Connection object by calling the Close method of Connection object.
- DataReader is a stream of data that is returned from Database query.
- DataReader reads one row at a time from the Database and can only move forward
one record at a time.
- As the DataReader reads the rows from the Database, the value of the columns in
each row can be read and evaluated but cannot be edited.
- As DataReader is forward only, we cannot fetch data randomly.

(4) DataAdapter
- DataAdapter is the Bridge between Disconnected Dataset and DataSource
- It provides two way Data transfer mechanism.
- From Dataset to Database and From Database to Dataset
- It is capable of executing select statement, retrieve data from DataSource and
transferring this result set into DataTable/Dataset
- It is capable of executing Insert, Update and Delete statement.
- Properties of DataAdapter

SelectCommand This command is automatically executed to fill a DataTable with


the result data.
InsertCommand This command is automatically executed to insert a new record
into the database.
UpdateCommand This command is automatically executed to update an existing
record in the databse.
DeleteCommand This command is automatically executed to delete an existing
record in the databse.

- It provides also Fill method.


- Calling Fill method automatically executed the command provided in select
command property, receives the result set & copied it to DataTable/Dataset.
-

[DOT NET TECHNOLOGY – 6th CE] Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(5) DataSet
- Dataset is the most commonly used part of Ado.net
- Dataset is a Disconnected and used to representation of database.
- It is the local copy of relevant database
- We can updating the record in Dataset without updating original database.
- Data can be loaded into Dataset from any valid DataSource such as SqlServer DB,
MSAccess DB or from XML file.
- Dataset first introducing during .Net version 1.0
- The current version of Ado.net retains all the previous features as well as provides
some new features.
- In DataSet, There can be multiple DataTables and DataRelations.
- It contains the collection of data retrieved from the Datasource (Database).
- And the DataAdapter object is used to transfer the data between DataSet and
Database.

DataTable

- DataTable object represents Tables.


- You can add DataTable in Dataset object.
- DataTable contains collection of DataRow which contains all the Data in the Table.
- It contains also collection of DataColumns which contains information about each
column in Table and collection of constraint which specifies additional column
metadata such as primary key.

DataRelation

- Data Relation object allows you to create Join (Association) between Rows in one
Table and Rows in another Table.
- It defines relationship between multiple tables.
- For example consider a dataset that has two related tables : employee and projects
- Each employee represented only once and identified by unique employeeID field.
- Now in project table, an employee in charge of project is identified by employeeID
field. But can appear more than once if that employee is in charge of multiple
projects.
- This is example of one to many relationships.
- You can use DataRelation object to define this relationship.
- DataSet is a collection of DataTables and as shown in below figure, DataTable is a
collection of Rows Collection, Column Collection, Constraints Collection, and Child
Relation & Parent Relation Collections.

[DOT NET TECHNOLOGY – 6th CE] Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

[Fig. Basic Structure of DataSet]

5. Explain Structure /Architecture of ADO.Net. or Explain managed Data


Provider in .Net

- Draw this figure and Explain here all Ado.net object


- Explain Connection object, Command object, DataReader, Dataset, Data Table, Data
Relation, DataAdapter

[DOT NET TECHNOLOGY – 6th CE] Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

6. Explain Command object’s Execution Methods.

- Refer Command object from Ado.net object

7. What are DataReader, DataAdapter and Dataset with Example? When to


use DataReader or DataSet?

- Refer Ado.net objects for DataReader, DataAdapter and Dataset


- DataReader and dataset both are used for select statement that means a statement
which returns result set.
- If you want to retain the result set or want to use this result set further, you must
use DataAdapter object to fill a Dataset or DataTable.
- If you do not want to retain the result set or your aim is to simply displaying that
result set then, simply use DataReader object with appropriate command object’s
method.
Example : How to retrieve record from database using DataReader

SqlConnection con = new


SqlConnection(ConfigurationManager.ConnectionStrings["co
nstr"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from emp", con);
con.Open();
SqlDataReader r;
r = cmd.ExecuteReader();
GridView2.DataSource = r;
GridView2.DataBind();
con.Close();

Example : How to retrieve record from database using Dataset

SqlConnection con = new


SqlConnection(ConfigurationManager.ConnectionStrings["const
r"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from emp",con);
DataSet ds = new DataSet();
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(ds,"emp");
GridView1.DataSource=ds.Tables["emp"];
GridView1.DataBind();

- Store connectionString in web.config file to run this code.

[DOT NET TECHNOLOGY – 6th CE] Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Where to find connectionString information ?


- Right click on databse and go in property window, you can find connectionString
property, simply copy it and paste in web.config file as shown below.

<connectionStrings>
<add name="constr" connectionString="Data Source=
KITRC\SQLEXPRESS; Initial Catalog=test; Integrated
Security=True;"/>
</connectionStrings>

- If you don’t want to write connectionString manually in web.config file, just open
database in solution explorer, Open tables and drag any one Table in windows/web
forms.
- So automatically one gridview and datasource will add, delete it.
- Now open web.config file, you can see ConnectionString already added. No need to
add manually.
- DataReader needs live connection & works as a forward-only, read-only cursor.
- DataAdapter is a bridge between Dataset and Database.
- Dataset is the local copy of relevant database and you can Load multiple Tables in
single Dataset.

8. In SQLSERVER a table called employee contains the basic details about Employee such as
id, name and city. Develop Ado.Net Program using C#.Net which Insert, update and
delete in Web Application. Also display records in gridview.[here id primary key and auto
increment] – INSERT, UPDATE, DELETE and RETRIEVE in DATABASE.

Insert:

[DOT NET TECHNOLOGY – 6th CE] Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Insert code:

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["constr"].ConnectionString);

SqlCommand cmd=new SqlCommand("insert into employee values


('"+ TextBox1.Text +"','"+ DropDownList1.SelectedItem.Text
+"')",con);

con.Open();
int i= cmd.ExecuteNonQuery();
if (i > 0)
{
Response.Write("Record Inserted Successfully!");
}

con.Close();

TextBox1.Text = "";
}

Update:

[DOT NET TECHNOLOGY – 6th CE] Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Update Code:

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["constr"].ConnectionString);

SqlCommand cmd = new SqlCommand("update employee set name='"


+ TextBox1.Text + "', city='" +
DropDownList2.SelectedItem.Text + "' where id='"+
DropDownList1.SelectedValue +"'", con);

con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Response.Write("Record Update Successful !");
}

con.Close();
TextBox1.Text = "";
}

Delete:

[DOT NET TECHNOLOGY – 6th CE] Page 12


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Delete code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["co
nstr"].ConnectionString);

SqlCommand cmd = new SqlCommand("delete from employee


where id='" + DropDownList1.SelectedValue + "'", con);

con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Response.Write("Record Deleted Successful !");
}

con.Close();
TextBox1.Text = "";
}

Show Records:

[DOT NET TECHNOLOGY – 6th CE] Page 13


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Show Records Code:

protected void Button4_Click(object sender, EventArgs e)


{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["co
nstr"].ConnectionString);
con.Open();

SqlCommand cmd = new SqlCommand("select * from


employee", con);

DataSet ds = new DataSet();


SqlDataAdapter adap = new SqlDataAdapter(cmd);

adap.Fill(ds, "emp");

GridView1.DataSource = ds.Tables["emp"];
GridView1.DataBind();
con.Close();
}

9. Difference between Dataset and DataReader

Dataset DataReader

1 Read/write access Read access only

2 Support multiple tables from different Support single table based on a single sql
database. query of database

3 Disconnected mode Connected mode

4 Bind to multiple controls Bind to single control

5 Forward & Backward data Forward only data

6 Slower access to data Faster access to data

7 Overhead Light weight object

[DOT NET TECHNOLOGY – 6th CE] Page 14


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

10. What is a Typed and UnTyped Dataset in ADO.NET? Why do we use a Typed
DataSet?

Typed Dataset

- A typed DataSet is not a built-in member of the .NET Framework. It is a generated


class that inherits directly from the DataSet class, and allows properties and
methods to be customized from an XML schema that you specify.
- This class also contains other classes for DataTable and DataRow objects.
How to create a Typed DataSet?
- Write click on Solution Explorer --> Add New Item --> Select DataSet
- This adds a new XSD to the project.
- The schema created may be viewed as an XML. When this xsd file is compiled, two
files are created by Visual Studio.
- The first file that contains the .vb or .cs extension contains the information about
the proxy class. This class contains methods & properties that are required to
access the database data.
- The second file has an extension xss and this contains information about the layout
of the XSD.
- The typed dataset is binded with the database tables(s) at design time and you
have all the schema information at design time in your code.
- For example you can access the tables with the actual names, columns with the
actual names. It is added as .xsd file in your application.
- It provides additional methods, properties and events and thus it makes it easier to
use.
- They have .xsd file (Xml Schema definition) associated with them and do error
checking regarding their schema at design time using the .xsd definitions.
- Using Typed Dataset We will get advantage of intelliSense in VS. NET.
- You can work it with simply by drag and drop table into dataset.
- Performance is slower in case of strongly typed dataset
- In complex environment, strongly typed dataset's are difficult to administer.

UnTyped Dataset

- Note that an UnTyped DataSet does not have any schema.


- Untyped dataset is an object of class System.Data.DataSet. It is binded with the
tables at runtime. You are not aware of the schema of the dataset at design time.
- It is not as easy to use as strongly typed dataset.

[DOT NET TECHNOLOGY – 6th CE] Page 15


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Drag and drop is not possible here you have to write code to work with it.

- They do not do error checking at the design time as they are filled at run time when
the code executes.
- We cannot get an advantage of intelliSense.
- Performance is faster in case of untyped dataset.
- Untyped datasets are easy to administer.

11. Explain Data Binding Controls:

There are two types of Data Binding Controls:

1. List Data Bind Control


- DropDownList
- CheckBoxList
- RadioButtonList
- BulletedList
2. Composite Data Bind Control
- GridView
- FormView
- DetailsView
- DataList
- Repeater

Note: See all these control in details with all its property and how to bind it with
Database.

[DOT NET TECHNOLOGY – 6th CE] Page 16


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Advance .Net Technology (Department Elective -I)


Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture notes
Chapter-5,6,7

1. Explain GDI+. Describe the Classes available in System.Drawing


Namespace.

- GDI stands for Graphic Device Interface.


- It provides namespaces, classes, objects and methods to make printing and graphics
in vb.net windows forms.
- It makes the interface between Program and Hardware Devices. i.e. printer, monitor
- GDI+ classes are grouped under six namespaces, which reside in System.Drawing.dll
assembly.
- GDI+ Namespaces
1. System.Drawing
2. System.Drawing.Design
3. System.Drawing.Printing
4. System.Drawing.Imaging
5. System.Drawing.Drawing2D
6. System.Drawing.Text

1. System.Drawing Namespace

- The System.Drawing namespace provides basic GDI+ functionality.


The following table contains some of the System.Drawing namespace classes and
their definition.

Classes Description

Bitmap, Image Bitmap and image classes.

Brush, Brushes Brush classes used define objects to fill GDI objects such
as rectangles, ellipses, pies, polygons, and paths.

Font, FontFamily Defines a particular format for text, including font face,
size, and style attributes.

[6th CE – DOT NET TECHNOLOGY] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Graphics Encapsulates a GDI+ drawing surface.

Pen Defines an object used to draw lines and curves.

SolidBrush, TextureBrush, Defines a brush of a single color. Brushes are used to fill
graphics shapes, such as rectangles, ellipses, pies,
polygons, and paths.

2. System.Drawing.Design Namespace

- It has two types of classes


Editor Classes
- BitmapEditor, FontEditor, and ImageEditor are the editor classes.
- You can use these classes to extend the functionality and provide an option in
properties window to edit images and fonts.
ToolBox Classes
- ToolBoxItem, ToolBoxItemCollection are two major toolbox classes. By using these
classes you can extend the functionality of toolbox and provide the implementation
of toolbox items.

3. System.Drawing.Drawing2D Namespace

- It has following types of classes

Class Description
Blend and ColorBlend These classes define the blend for gradient
brushes. The ColorBlend defines array of colors
and position for multi-color gradient.
GraphicsPath This class represents a set of connected lines and
curves.
HatchBrush A brush with hatch style, a foreground color, and a
background color.
LinearGradientBrush Provides brush functionality with linear gradient.
Matrix 3x3 matrix represents geometric transformation.

4. System.Drawing.Imaging Namespace

- This namespace provides advanced GDI+ imaging functionality.


- It defines classes for metafile images. Other classes are encoder and decoder, which
let you use any image format.

[6th CE – DOT NET TECHNOLOGY] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- It also defines a class PropertyItem, which let you store and retrieve information
about the image files.

5. System.Drawing.Printing Namespace

- The System.Drawing.Printing namespace defines classes for printing functionality in


your applications. Some of its major classes are defines in the following table :

Class Description
PageSettings Page settings
PaperSize Size of a paper.
PreviewPageInfo Print preview information for a single page.
PrintController Controls document printing
PrintDocument Sends output to a printer.
PrinterResolution Sets resolution of a printer.
PrinterSettings Printer settings

6. System.Drawing.Text Namespace

- Even though most of the font's functionality is defined in System.Drawing


namespace, this provides advanced typography functionality such as creating
collection of fonts.
- Right now, this class has only three classes - FontCollection, InstalledFontCollection,
and PrivateFontCollection.

The Graphics Class

- The Graphics class is center of all GDI+ classes. Some of the graphics class methods
are described in the following table:

Class Description
DrawArc This method draws an arc.
DrawBezier, These methods draw a simple and bazier curves.
DrawBeziers, DrawCurve These curvers can be closed, cubic and so on.
DrawEllipse Draws an ellipse or circle.
DrawImage Draws an image.
DrawLine Draws a line.
DrawPath Draws the path (lines with GraphicsPath )
DrawPie Draws the outline of a pie section.
DrawPolygon Draws the outline of a polygon.

[6th CE – DOT NET TECHNOLOGY] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

DrawRectangle Draws the outline of a rectangle.


DrawString Draws a string.
FillEllipse Fills the interior of an ellipse defined by a bounding
rectangle.
FillPath Fills the interior of a path.
FillPie Fills the interior of a pie section.
FillPolygon Fills the interior of a polygon defined by an array of
points.
FillRectangle Fills the interior of a rectangle with a Brush
FillRegion Fills the interior of a Region.

Common Graphics Objects


Pen:

- Used to draw lines and polygons, including rectangles, arcs, and pies.
- Pen objects hold the settings used when drawing lines.
- Example-1 shows how to draw an ellipse on a user control or a form.
Example-1:

private void button1_Click(object sender, EventArgs e)


{
Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Green, 5);
Rectangle myRectangle = new Rectangle(20,20,250, 200);
graphicsObj.DrawEllipse(myPen, myRectangle);
}

[6th CE – DOT NET TECHNOLOGY] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Example-2: Setting Pen properties

private void button1_Click(object sender, EventArgs e)


{
Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Green, 5);
myPen.DashStyle = DashStyle.Dash;
Rectangle myRectangle = new Rectangle(20,20,250, 200);
graphicsObj.DrawEllipse(myPen, myRectangle);
}

Brush:

- Used to fill enclosed surfaces with patterns, colors, or bitmaps.


- Brush objects hold the settings used when filling graphics areas.
- All of the Graphics class's Fill...methods (FillClosedCurve, FillEllipse, etc.) require that
the caller supply a Brush object.
- The supplied Brush object determines how the interior of the figure will be painted.
- Example-1 shows how to draw an ellipse on a user control or a form. It is similar to
Example-1 of Pen class, but it draws a filled ellipse rather than an outline using brush
object.

Example-1:

SolidBrush mybr = new SolidBrush(System.Drawing.Color.Red);


Graphics gr = this.CreateGraphics();
gr.FillEllipse(mybr, new Rectangle(20, 20, 250, 200));

[6th CE – DOT NET TECHNOLOGY] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

mybr.Dispose();
gr.Dispose();

Font:
- Used to describe the font to be used to render text

Color:
- Used to describe the color used to render a particular object.

2. Write windows application in vb.net to draw Rectangle, square, eclipse


also pie chart using GDI+.

Example: Rectangle, square, eclipse

private void button1_Click(object sender, EventArgs e)


{
Graphics g = this.CreateGraphics();

g.DrawLine(Pens.Black, 100, 100, 360, 360);


g.DrawLine(Pens.Black, 900, 100, 635, 360);
g.DrawRectangle(Pens.Red, 300, 100, 400, 400);
g.DrawEllipse(Pens.Blue, 300, 300, 400, 400);
g.DrawEllipse(Pens.Black, 475, 350, 50, 50);

[6th CE – DOT NET TECHNOLOGY] Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Example: Pie chart

Private Sub Form1_Paint() Handles Me.Paint


Dim g As Graphics
g = Me.CreateGraphics
Dim brush As System.Drawing.SolidBrush
Dim rect As Rectangle
brush = New System.Drawing.SolidBrush(Color.Green)
Dim angles() As Single = {0, 43, 79, 124, 169, 252, 331, 360}

Dim colors() As Color = {Color.Red, Color.Cornsilk,Color.Firebrick,


Color.OliveDrab, Color.LawnGreen, Color.SandyBrown, Color.MidnightBlue}

g.Clear(Color.Ivory)

rect = New Rectangle(100, 10, 300, 300)


Dim angle As Integer
For angle = 1 To angles.GetUpperBound(0)
'taking colors from colors array
brush.Color = colors(angle - 1)
'filling the pie with brush color for the angles in angles array
g.FillPie(brush, rect, angles(angle - 1),angles(angle) - angles(angle -
1))

[6th CE – DOT NET TECHNOLOGY] Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Next
'drawing ellipse at outer of rectangle with the black color
g.DrawEllipse(Pens.Black, rect)
End Sub

3. Explain Concept of Visual Inheritance.


Use of visual inheritance:

- In .NET, inheritance is not just limited to designing classes but also extended to
visual designing. So, what does it mean? Well, it means we can use inheritance in
Form designing too, so this kind of usage is called Visual Inheritance.
- Suppose you have a standard form that you want to use frequently across a project
or even throughout your company in VB .NET projects.
- It might have carefully formatted graphics, a standard set of buttons, or a text box
with a standard company disclaimer.
- The whole idea is that there are common elements in a form that you don't want to
have to code over and over every time you use them. Repeating the code for this
form in every project is certainly a waste of time also every time copy the code is not
right solution.
- For that solution just import that form into your projects as an object. That's Visual
Inheritance.
- Inheritance can improve code reuse in your applications and provide them with a
standard appearance and behavior.
- Compile your form as a DLL and then add it to your project as an Inherited Form.
- VB.NET standard does this just fine if you already have such a DLL.

[6th CE – DOT NET TECHNOLOGY] Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Create a new VB .NET project. Add a few buttons or other controls to a Form so you
can recognize it.
- Then select Build Solution from the menu.
- After this is done, Add a new Inherited Form to the Project.
- Now Inherited Form Picker will be opened, add a new form based on it to your
project. This is basically a copy of the first form.

4. Explain Concept of MDI Form in Window Application.

- MDI (Multiple Document Interface) Application is an application in which we can


view and work with several documents at once. Example of an MDI application is
Microsoft Excel. Excel allows us to work with several documents at once.
- In contrast, SDI (Single Document Interface) applications are the applications which
allow us to work with a single document at once. Example of a single document
application is Microsoft Word in which only one document is visible at a time.
- Visual Basic .NET provides great support for creating and working with MDI
applications.
- In general, MDI applications are mostly used by financial services organizations
where the user needs to work with several documents at once.

Creating MDI Applications

- Let's create an MDI application.


- Open a new Windows Application in Visual Basic .NET. The application will open
with a default form, Form1.
- Add another form, Form2 to this application by right-clicking on the project name
in Solution Explorer window and selecting Add->Add Windows Form.

[6th CE – DOT NET TECHNOLOGY] Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- You can add some controls to Form2.


- For this application we will make From1 as the MDI parent window and Form2 as
MDI child window.
- MDI child forms are important for MDI Applications as users interact mostly
through child forms.
- Select Form1 and in its Properties Window under the Windows Style section, set
the property IsMdiContainer to True. Setting it to true designates this form as
an MDI container for the child windows.
- Once you set that property to true the form changes its color.

MDI Forms:
(1) Creating the Parent Form
(2) Creating Child Forms
(3) Accessing Child Forms
(4) Arranging Child Forms

(1) Creating the Parent Form


- You can use the IsMdiContainer property of a form to make it an MDI parent form.
This property holds a Boolean value and can be set at design time or run time.
- The following example shows how to specify a form as an MDI parent and maximize
it for easy use.
private void Form1_Load(object sender, EventArgs e)
{
this.IsMdiContainer = true;
this.WindowState = FormWindowState.Maximized;
}

(2) Creating Child Forms


- You can create child forms by setting the MdiParent property of a form to the name
of the already-created MDI parent.
- The following example shows how to create an MDI child form. This procedure could
be called from the Form_Load procedure, and a New Document menu item.

[6th CE – DOT NET TECHNOLOGY] Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- It uses a global variable to store the number of child windows for use in the caption
of each window.
(3) Accessing Child Forms
- It is common to use menus on the MDI parent form to manipulate parts of the MDI
child forms. When you use this approach, you need to be able to determine which is
the active child form at any point in time.
- The ActiveMdiChild property of the parent form identifies this for you.
- The following example shows how to close the active child form:

(4) Arranging Child Forms

- You can use the LayoutMdi method of the parent form to arrange the child forms in
the main window. This method takes one parameter that can be one of the
following:
MdiLayout.Cascade
MdiLayout.ArrangeIcons
MdiLayout.TileHorizontal
MdiLayout.TileVertical

Example:
Form1 – set property IsMdiContainer = True and write code in form1’s button1_click event

private void button1_Click(object sender, EventArgs e)


{
Form2 fm = new Form2();

fm.MdiParent = this;
fm.Show();

this.LayoutMdi(MdiLayout.TileVertical);

5. Explain all VB.NET common Dialog boxes in details. (Folder Browser,


OpenFile, SaveFile, Font, Color)

1. FolderBrowserDialog

- Add the FoderBrowserdialog control from Dialogs toolbar into the Form.
- Make the design of form as per following figure.

[6th CE – DOT NET TECHNOLOGY] Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

private void button1_Click(object sender, EventArgs e)


{
folderBrowserDialog1.RootFolder =
Environment.SpecialFolder.MyComputer;

folderBrowserDialog1.SelectedPath = "D:/";

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
label1.Text = folderBrowserDialog1.SelectedPath;
}
}

Properties
- RootFolder: To set the root folder to start browsing
- SelectedPath: To get or set the selected folder path.
- ShowNewFolder: Boolean value property to show or not the New Folder
Button in the Dialog Box.

[6th CE – DOT NET TECHNOLOGY] Page 12


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

2. OpenFileDialog

private void button1_Click(object sender, EventArgs e)


{
openFileDialog1.Filter ="Rich Text Format
(*.rtf)|*.rtf|" + "Text Files (*.txt)|*.txt|" + "Word Documents
(*.doc;*.docx)|*.doc;*.docx|" + "All Files(*.*)|" ;

openFileDialog1.FilterIndex = 3 ;

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
}
}

3. SaveFileDialog

- Take the SaveFileDialog control, textbox and button into form, and change the
MultiLine property of TextBox to True.

[6th CE – DOT NET TECHNOLOGY] Page 13


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

private void button1_Click(object sender, EventArgs e)


{
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|All
Files(*.*)|";

if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{

File.WriteAllText(saveFileDialog1.FileName,textBox1.Text,System.
Text.Encoding.Default);
}

4. FontDialog

[6th CE – DOT NET TECHNOLOGY] Page 14


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

private void button1_Click(object sender, EventArgs e)


{
if(fontDialog1.ShowDialog()==DialogResult.OK)
{
textBox1.Font = fontDialog1.Font;
}
}

Properties:

Color: To assign default color to the Font dialog.


Font: To get changes of font in Font dialog.
ShowColor: Boolean Value property to show the colors

5. Color Dialog

private void button1_Click(object sender, EventArgs e)


{
if(colorDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.BackColor = colorDialog1.Color;
}
}

[6th CE – DOT NET TECHNOLOGY] Page 15


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Chapter-8

1. What is ASP.NET? Compare ASP with ASP.NET.


- It is server side technology for developing web application.
- To understand Asp.net first knows ASP and their limitations.
- ASP is purely scripting language and code is not compiled but interpretered. There is
no DLL and EXE generated.
- ASP.NET is not an upgraded version of ASP. It is newly technology.
- It is not compatible with Classic ASP, but ASP.NET may include Classic ASP.

Why ASP.NET better than ASP (Or comparison ASP & ASP.NET)

1. Simple and Easy to develop.


2. Code compiled not interpretered.
3. Better controls than ASP.
4. Controls have events support
5. Better language support
6. Separate Code Behind File
7. Better Authentication and Authorization
8. User accounts & roles
9. Uses ADO.NET not ADO
10. Inbuilt validation controls
11. Debugging Support
12. Easy Configuration
13. Easy deployment

2. ASP.NET Page Life Cycle (Including Events) or Postback


processing Sequence
Page Life Cycle steps:

1. Webpage request comes from browser.


2. IIS received request and Maps the asp.net file extensions (.aspx,.ascx,.asmx,.ashx) to
ASPNET_ISAPI.DLL on Asp.net engine.

6th CE – Dot Net Technology Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

3. If file name extension has not been mapped to asp.net engine, Asp.net will not
receive request. So IIS handles the request & discard the request without processing.
4. If IIS maps file Extension successfully, it load this ASPNET_ISAPI.DLL and pass request
to it.
5. Now ASPNET_ISAPI.DLL pass this request to ASPNET_WP.EXE Asp.net worker process
and now execution start. Then some page level events begins

Page Level Events

1. Page PreInit
This is event fire before the Page Init.
- Check IsPostback property
- Set Master Page dynamically
- Set Theme property of page dynamically
- Recreate Dynamic controls

2. Init
In this method initialization done for all controls

3. Init Complete
It will fire if all initialization completed.

4. Pre Load
Use this event if you want to process the controls or code before the Page load
events.

5. Load
In this events page calls the OnLoad method of this page and recursively does the
same for each child controls until the page & all controls are loaded.
6. Control Events (Postback)

6th CE – Dot Net Technology Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- This event handles specific control events such as Button control’s click event or
TextBox’s Textcahnged event. It is also called Postback.
- Each time you click a button, the page is sent back to the server and this process
repeats itself. The action of submitting a page back to the server is called a
Postback.
- At the beginning of every Postback, the Page. Load event fires, which you can
handle to initialize your page.
7. Pre Render
This is the Last event before the HTML Code generated for the page. Use this
events to make final changes.

8. Render
In this method page object call the render methods of each controls that writes
the controls markup and finally sent to the browser.

9. Unload
This event occur for each control and then for the page. Use this event to do final
clean up for specific control such as closing database connection etc..

6. Now if the page level events ends response with above events sends back to the IIS.
7. And Finally IIS sends the response to the client browser.

3. What is validation in web development? Explain various Controls


for validation in APS.NET with Example.
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 is of two types:


- Client Side
- Serve Side

- Client side validation is good but we have to be dependent on browser and scripting
Language support.
- Client side validation is considered convenient for users as they get instant feedback.
The main advantage is that it prevents a page from being Postback to the server
until the client validation is executed successfully.
- For developer point of view serve side is preferable because it will not fail, it is not

6th CE – Dot Net Technology Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Dependent on browser and scripting language.


- You can use ASP.NET validation, which will ensure client, and server validation. It
work on both end; first it will work on client validation and than on server validation.
- At any cost server validation will work always whether client validation is executed or
not. So you have a safety of validation check.
- For client script .NET used JavaScript. WebUIValidation.js file is used for client
validation by .NET

There are six types of validation controls in ASP.NET

1. RequiredField Validation Control


2. CompareValidator Control
3. RangeValidator Control
4. RegularExpression Validator Control
5. CustomValidator Control
6. ValidationSummary

Validation Control Description


RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the
value of another input control or to a fixed
value
RangeValidator Checks that the user enters a value that falls
between two values
RegularExpressionValidator Ensures that the value of an input control
matches a specified pattern
CustomValidator Allows you to write a method to handle the
validation of the value entered
ValidationSummary Displays a report of all validation errors occurred
in a Web page

Important Common Properties of all validation controls

ControlToValidate The id of the control to validate

Display Legal values are:

- - None (the control is not displayed. Used to show the error


message only in the ValidationSummary control)
- - Static (the control displays an error message if validation fails.
- Space is reserved on the page for the message even if the input
passes validation.

6th CE – Dot Net Technology Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- - Dynamic (the control displays an error message if validation


fails.
- Space is not reserved on the page for the message if the input
passes validation

EnableClientScript A Boolean value that specifies whether client-side

validation is enabled or not


Enabled A Boolean value that specifies whether the validation control is
enabled or not
ErrorMessage The text to display in the ValidationSummary control when
validation fails.

- This text will also be displayed in the validation control if


the Text property is not set

A Boolean value that indicates whether the control specified by


IsValid
ControlToValidate is determined to be valid
T message to display when validation fails
Text

Examples:

(1) RequiredFieldValidator Control

- The RequiredFieldValidator control ensures that the required field is not empty. If
you want any field compulsory then use this validation control.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"


ControlToValidate="TextBox1" ErrorMessage="First Name Required !">

</asp:RequiredFieldValidator>

- Main Property is ControlToValidate and ErrorMessage

6th CE – Dot Net Technology Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(2) RangeValidator Control

- The RangeValidator control verifies that the input value falls within a predetermined
range.
- For example if you want to allow age only 18 to 40 years then Range validator used.
- It has three specific properties:

Properties Description
It defines the type of the data. The available values are: Currency,
Type
Date, Double, Integer, and String.
MinimumValue It specifies the minimum value of the range.
MaximumValue It specifies the maximum value of the range.

<asp:RangeValidator ID="RangeValidator1" runat="server"


ControlToValidate="DropDownList1" ErrorMessage="Only 18 to 40"
MaximumValue="40" MinimumValue="18" Type="Integer">
</asp:RangeValidator>

(3) CompareValidator Control

- The CompareValidator control compares a value of one control with a fixed value or
with a value of another control.
- For Password password and confirm password we can used this validation control.
- It has the following specific properties:

Properties Description

6th CE – Dot Net Technology Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Type It specifies the data type.


ControlToCompare It specifies the value of the input control to compare with.
ValueToCompare It specifies the constant value to compare with.
It specifies the comparison operator, the available values are:
Operator Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,
LessThanEqual, and DataTypeCheck.

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


ControlToCompare="TextBox2" ControlToValidate="TextBox3"
ErrorMessage="Password and Confirm Password Must Match!">
</asp:CompareValidator>

(4) 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.
- There are lots of inbuilt regular expressions available in validation expression
property.
- For E-mail Id, URL validation we can used regular expression validation control.
- This is most powerful validation expression.
- For any kind of validation you can search regular expression on internet and you can
used it. We can used more prefer website http://www.regxlib.com/

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox4" ErrorMessage="E-mail id not
valid" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>

(5) CustomValidator

- The CustomValidator control allows writing specific custom validation for both the
client side and the server side validation.
- If your requirement is not fulfill with available inbuilt validation control then with
CustomValidator control you can write custom code and can use for validation.
- The client side validation is accomplished through the ClientValidationFunction
property. The client side validation routine should be written in a scripting
language, such as JavaScript or VBScript, which the browser can understand.

6th CE – Dot Net Technology Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- The server side validation routine must be called from the control's ServerValidate
event handler. The server side validation routine should be written in any .Net
language, like C# or VB.Net.

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


ControlToValidate="TextBox5" ErrorMessage="Only 10 characters !"
onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

protected void CustomValidator1_ServerValidate(object source,


ServerValidateEventArgs args)
{
if (args.Value.Length > 10)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

(6) 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.

Two main properties.

 ShowSummary : shows the error messages in specified format.


 ShowMessageBox : shows the error messages in a separate window.
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" />

4. Explain Configuration File (Web.config and Machine.config) with


different Tags.

Asp.net configuration is stored in two primary XML based files.


(1) Machine.config : (server or machine configuration file)
(2) Web.config : (Application configuration file)

6th CE – Dot Net Technology Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

1. Machine.config

- Every Asp.net server installation includes a configuration file named Machine.config


and this file is installed as a part of .Net framework installation.
- You can find Machine.config file in, C:\windows\microsoft.net\framework\v2.oxxx
- Machine.config file is used to configure common .net framework setting for all
application on the machine
- It is not a good idea to edit or manipulate the Machine.config file ,If you do not know
what are you doing
- Change to this file can affect all application on your computer
- Because the .net framework supports side by side execution, you find more than one
installation of Machine.config file, if you have installed multiple version of .net.
- Each .net framework installation has its own Machine.config file
- In addition Machine.config file , .net framework install also two more file called
machine.config.default & machine.config.comments
- The machine.config.default file act as backup for Machine.config file
- The machine.config.comments file contains description for all configuration section.

2. Web.config

- Each and every asp.net application has its own configuration settings stored in
web.config file
- The configuration for each web application is unique
- If web application spam’s multiple folders ,each sub folders has its own web.config
file that inherit or overwrites or parents web.config file
- The main diff. between Machine.config & web.config is the file name
- Configuration files divided into multiple sections.
- The root element in xml configuration file is always <configuration>
- Note that the web.config file is case-sensitive, like all XML documents, and starts
every setting with a lowercase letter. This means you cannot write <AppSettings>
instead of <appSettings>.

Advantages of Asp.net configuration file (web.config):

- They are never locked:

You can update web.config settings at any point, even while your application is
running. If there are any requests currently under way, they’ll continue to use the
old settings, while new requests will get the changed settings right away.

6th CE – Dot Net Technology Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- They are easily accessed and replicated:

with appropriate network rights, you can change a web.config file from a remote
computer. You can also copy the web.config file and use it to apply identical settings
to another application or another web server that runs the same application in a
web farm scenario.

- The settings are easy to edit and understand:

The settings in the web.config file are human readable, which means they can be
edited and understood without needing a special configuration tool.

Common Configuration Settings (For Web.config)

1. Connection String:

- The <connectionStrings> section allows you to define the connection information for
accessing a database.
- Connection string information stored either <appSettings/> or
<connectionStrings/> section.
- In asp.net 1.1 all the connection string info was stored in <app setting> section
- Examples , how to store connection string

- Using <app setting>

<configuration>
<appSettings>
<add key="constr" value="datasource=sqlexpress; initial
catalog=test; Integrated security=true"/>
</appSettings>
</configuration>

- Now access it in your application like:

SqlConnection con=New
SqlConnection(ConfigurationSettings.AppSettings["constr"])

- Using <ConnectionStrings>:

<configuration>
<connectionStrings>
<add name="constr" connectionString="datasource=sqlexpress;
initial catalog=test; Integrated security=true"/>

6th CE – Dot Net Technology Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

</connectionStrings>
</configuration>

- Now access it in your application like:

SqlConnection con = New


SqlConnection(ConfigurationManager.ConnectionStrings["constr"]
.ConnectionString)

2. Compilation Settings

<compilation tempDirectory="" debug="true" batch="true"


maxBatchSize="" defaultLanguage="" >
</compilation>

- tempDirectory specifies the directory to use for temporary file storage during
compilation
- You can set compilation debug=true to insert debugging symbols into the compiled
page. And default is False
- Batch specifies whether batch compilation is support or not. And default is True
- maxBatchSize specifies the maximum no. of pages per batched compilation and
default value is 1000
- defaultLanguage specifies the default programming language such as VB or C# to use
in dynamic compilation files. And default is VB.

3. Page Settings

- With this setting we can set the general settings of a page like viewstate, MasterPageFile
and Themes.

<pages enableViewState ="true" masterPageFile="Master1.master"


theme="summer" styleSheetTheme="" >

</pages>

- By using the MasterPageFile and theme attributes, we can specify the master page
and theme for the pages in web application.
- Also we can enable or disable viewstate for particular page.

4. Custom Error Settings

6th CE – Dot Net Technology Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- In asp.net when error is occur then asp.net display the error page with source code and
line number of the error.
- Now if source code and error messages are displayed, it is possible to hack your site
code by hackers.
- So to overcome this problem asp.net provides excellent custom error mechanism.
- The <customErrors> section enables configuration of what to do if/when an unhandled
error occurs during the execution of a request. Specifically,it enables developers to
configure html error pages to be displayed in place of a error.

<customErrors mode="RemoteOnly" defaultRedirect="welcome.html">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

- In this example if error occurs, welcome.html page will be display instead of error.

5. Location Settings

- If you are working with a major project, you have numbers of folders and sub-folders, at
this kind of particular situation, you can have two options to work with.
- First thing is to have a Web.config file for each and every folder(s) and Sub-folder(s).
- And the second one is to have a single Web.config for your entire application.
- If you use the first approach, then you might be in a smoother way.
- But what if you have a single Web.config and you need to configure the sub-folder or
other folder of your application.
- The right solution is to use the "Location" tag of Web.config file.

<location path="Admin">
<system.web>
<pages theme="summer"></pages>
</system.web>
</location>

- Here for Admin pages you can set theme=suumer.

6. Session State Settings

- As we all know, the ASP.NET is stateless and to maintain the state we need to use the
available state management techniques of ASP.NET.
- You can configure state management in web.config file with <sessionState> tag.
- For details see chapter-11 state management.

<sessionState mode="InProc" cookieless="true">


6th CE – Dot Net Technology Page 12
ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

</sessionState>

7. Authentication Settings

- Authentication is the process that determines the identity of users.


- Authentication works in conjunction with authorization.
- After a user has been authenticated, a developer can determine if the identified user has
valid authorization to proceed.
- It is impossible to give <authorization> if no <authentication> has been applied.
- You can use <authentication> mode as shown below.

<configuration>
<system.web>
<authentication mode="[Windows/Forms/Passport/None]">
</authentication>
</system.web>
</configuration>

- You can use authentication mode like windows, Forms, Passport and None

8. Authorization Settings

- <authorization> tag has list of access rules that either allow or deny a particular users.
- We can use <allow> or <deny> tag to create or modify access rules.
- Astrisk(*) means “All Users”
- Question Mark means “All Anonymous users”
- We can use <authorization> section like this:

<authorization>
<allow users="*"/>
<deny users="?"/>
<allow users="ark"/>

<allow roles="admin"/>
<deny roles="member"/>
</authorization>

Windows Authentication

- This is the default authentication mode in ASP.NET.

6th CE – Dot Net Technology Page 13


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Windows based authentication is handled between the windows server where the
Asp.net application resides and the client machine.
- In windows based authentication, request goes directly to IIS to provide basic
authentication process.
- This type of authentication is quite useful in an intranet environment.
- To work with windows based authentication you have to create users & groups.
- You can assign windows authentication like,

<authentication mode="Windows"/>
<authorization>
<allow users ="*" />
</authorization>

Forms Authentication

- Forms authentication allows you to use custom login page with your own code. So end
user can simply enters his username & password into HTML form.
- This authentication mode is based on cookies where the user name and the password are stored
either in a text file or the database.
- After a user is authenticated, the user’s credentials are stored in a cookie for use in that session.
- When the user has not logged in and requests for a page that is insecure, he or she is redirected
to the login page of the application.
- Forms authentication supports both session and persistent cookies.
<configuration>
<system.web>
<authentication mode="Forms"/>
<forms name="login" loginUrl="login.aspx" />
<authorization>
<deny users="?"/>
</authorization>

</system.web>
</configuration>

- Here name is the name of cookie saved use to remember the user from request to
request.
- LoginUrl specifies the URL to which the request is redirected for login if no valid
authentication cookie is found.

Passport Authentication

6th CE – Dot Net Technology Page 14


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Passport authentication is works with Microsoft passport identity system.


- So, if a user has passport account they can login to your site and other passport oriented
sites.
- When your application is enable for passport authentication, the request is actually
redirected to the Microsoft passport site where the user can enter his credentials.
- If the authentication is successful, request is redirected back to your application.
- Very few internet sites uses Microsoft passport authentication services.

9. httpRuntime settings

<httpRuntime enable="true" maxRequestLength="" executionTimeout=""/>

- Enable attributes specifies whether the current Asp.net application is enabled or


disabled.
- maxRequestLength specifies the maximum size of file uploaded accepted by asp.net
runtime. Default is 4096 kb (4 MB). If the Asp.net application require huge files to
upload, it is better to change this setting.
- executionTimeout specifies the timeout option for asp.net request. Default value is “90”
seconds. If you have a asp.net webpage that takes longer than 90 seconds to execute
you can extend the time limit in the configuration.

5. Explain Rich Server Controls


- Rich Controls are: (1)AdRotator (2)Calendar

(1) AdRotator

- Mainly used for advertisement to post various Advertise on website.


- The basic purpose of the AdRotator is to provide a graphic on a page that is chosen
randomly from a group of possible images.
- In other words, every time the page is requested, an image is selected randomly and
displayed.
- The AdRotator stores its list of image files in an XML file. This file uses the format
shown here
- Create XML file in solution explorer like below
<Advertisements>

6th CE – Dot Net Technology Page 15


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

<Ad>
<ImageUrl>Sunset.jpg</ImageUrl>
<NavigateUrl>http://www.kirc.ac.in </NavigateUrl>
<AlternateText>Sunset image</AlternateText>
<Impressions>1</Impressions>
<Keyword>Computer</Keyword>
</Ad>
</Advertisements>

- This example shows a single possible advertisement. To add more advertisements, you
can create multiple <Ad> elements and place them all inside the root <Advertisements>
element.
- After the creating XML file bind it with AdvertisementFile Property of AdRotator control.
Advertisement File Elements:

(2) Calendar

- The Calendar control presents a calendar that you can place in any web page.
- The Calendar control presents a single-month view, as shown in following Figure.

- The user can navigate from month to month using the navigational arrows.
- You can access a date which is selected by user at run time through code.

6th CE – Dot Net Technology Page 16


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Protected Sub Calendar1_SelectionChanged()Handles


Calendar1.SelectionChanged

TextBox1.Text = Calendar1.SelectedDate.ToString();

End Sub

- With this code once you select a date that date should be display in TextBox1
- Calendar control has lots of property try it practically.

Note: Here I explain only Rich server controls. See all common control’s property and try
it practically. Also remember all the important property of each server control.

6th CE – Dot Net Technology Page 17


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)

Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture notes
Chapter-9

1. Concept of MasterPage and Themes in Asp.net.

MasterPage

- For common layout we can use MasterPage throughout the entire application.
- Some developer simply copy and paste the code of this common section to each &
every page. This works but it is not a good practice.

Create MasterPage

Go to Solution Explorer -> Add New Item -> MasterPage

Apply MasterPage to Webpage

You can apply masterpage to web page three way:

1. For Entire Application (Application level)

- In web.config file,

<system.web>
<pages masterPageFile="~/MasterPage2.master">
</pages>
</system.web>

- Modification in web.config file will be affect on entire appliaction.

2. For Specific Folder (Group level)

- In web.config file,
<configuration>
<location path ="Admin">

[6th CE – DOT NET TECHNOLOGY] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

<system.web>
<pages masterPageFile="MasterPage2.master">
</pages>
</system.web>
</location>
</configuration>

3. For Specific page (Page level)

- In Page Directive,

<%@ Page Language="VB" MasterPageFile="~/MasterPage2.master"


AutoEventWireup="false" CodeFile="Default.aspx.vb"
Inherits="_Default" %>

Accessing controls of MasterPage

Button btn = (Button) Master.FindControl("Button1");

btn.BackColor = Drawing.Color.Blue

Programmatically assign MasterPage at Run time

- For that you have to write code in Page_PreInit

Protected Sub Page_PreInit() Handles Me.PreInit

Page.MasterPageFile = "~/MasterPage2.master"

End Sub

Themes

- When you build a web application, it usually has similar look across all pages.
- Generally we use similar fonts, colors and controls across all pages.

[6th CE – DOT NET TECHNOLOGY] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Create Theme

- You can create themes using two files .skin file and .css file
- .skin file is used for only Asp.net server control
- .css file is used for all HTML tags.

Go to Solution Explorer -> Add Asp.net Folder -> Theme

- By right clicking on Theme folder you can create .skin file and .css file as per your
requirement.

Example of .skin file

<asp:TextBox runat="server" BackColor="#FF9900"


BorderColor="Black" BorderStyle="Solid"></asp:TextBox>

<asp:Button runat="server" Text="Submit" BackColor="#990000"


BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
Font-Bold="True" ForeColor="White" />

Example of .css file


body
{
background-color: lightblue;
}

h1
{
color: navy;
margin-left: 20px;
}

- You can apply themes to web page three way:

1. For Entire Application (Application level)

- In web.config file,

<system.web>

[6th CE – DOT NET TECHNOLOGY] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

<pages theme="summer">
</pages>
</system.web>

- Modification in web.config file will be affect on entire appliaction.

2. For Specific Folder (Group level)

- In web.config file,
<configuration>
<location path ="Admin">
<system.web>
<pages theme="winter">
</pages>
</system.web>
</location>
</configuration>

3. For Specific page (Page level)

<%@ Page Language="VB" theme="summer" AutoEventWireup="false"


CodeFile="Default.aspx.vb" Inherits="_Default" %>

Note : you can apply themes to page either by theme or by StylesheetTheme

- Theme overrides explicitly define (local define property) property of control.


- StylesheetTheme not overrides local define property.

Multiple skin options in .skin file

- You can define control’s style in skin file several times


For example,
- We define TextBox style in skin file with style backcolor=blue
- Also we can define TextBox style in skin file with style backcolor=red
- So these multiple skin options identified by SkinId property of each control.

[6th CE – DOT NET TECHNOLOGY] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

<asp:TextBox runat="server" BackColor="#FF9900" SkinId="blue"


BorderColor="Black" BorderStyle="Solid"></asp:TextBox>

<asp:TextBox runat="server" BackColor="#FF9900" SkinId=”red"


BorderColor="Black" BorderStyle="Solid"></asp:TextBox>

How to disable themes for a Page ?

- Set the EnableTheming attribute of the @ Page directive to false

<%@ Page EnableTheming="false" %>

Disable themes for a control

- Set the EnableTheming property of the control to false.

<asp:Calendar id="Calendar1" runat="server" EnableTheming="false" />

[6th CE – DOT NET TECHNOLOGY] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)


Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture notes
Chapter-10

Q-1 Explain state management in .Net.

As we all know HTTP is a stateless protocol. And Asp.net works on stateless


protocol. So once request comes from browser to the server, server generate HTML
format page return to the browser at that time no data store on the server. As for
example, if we enter a text in form and client clicks on submit button, text does not
appear after post back.

Also you require some complex website like banking application it always
recommended to save previous state information otherwise it may be cause harm to
public or banking sector. So it is a big issue to maintain the state of the page and
information for a web application.

To overcome this problem ASP.NET provides some features like View State, Cookies,
Querystring, Session state, Application state

Two Types of State Management Techniques:

(1) Client – Side State Management

A. View state
B. Cookies
C. Query strings
(2) Server – Side State Management
A. session state
B. Application state

[6th CE – DOT NET TECHNOLOGY] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Q-2 Explain Viewstate, Querystring and cookie (Client side state


management) Objects with example.

(A) Viewstate (Page level State management)

- View State is one of the most important and useful client side state management
mechanisms.
- It can store the page value at the time of post back (Sending and Receiving
information from Server) of your page.
- ASP.NET pages provide the Viewstate property as a built-in structure for
automatically storing values between multiple requests for the same page.
- Viewstate information store in HTML hidden fields and automatically sent back to
the server with every Postback. And you can use this information with programming
logic.

Advantages:

- Easy to implement
- No server resources are required
- Its stored in a hidden filed in hashed format .
- Using hidden fields has the advantage that every browser can use this feature, and
the user cannot turn it off.

Disadvantage:-

- It can be performance overhead if we are going to store larger amount of data.,


- Viewstate data bound with specific page only. If we navigate to another page then
viewstate data will be loss.
- Its stored in a hidden filed in hashed format still it can be easily trapped.

The view state could be enabled or disabled for:

For entire application - by setting the EnableViewState property in the <pages>


section of web.config file. <pages EnableViewState=”false”>

For Specific page - by setting the EnableViewState attribute of the Page directive, as

[6th CE – DOT NET TECHNOLOGY] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

<%@ Page Language="C#" EnableViewState="false" %>

For Specific Control - by setting the EnableViewState property of the Control.


TextBox1.EnableViewState=”False”;

For Example, If you want to add data in View State,

ViewState [“kazi”] = "mydata";

You can read the previously stored ViewState as shown here:

TextBox1.Text = ViewState [“kazi”];

In the HTML code you can see the ViewState of the complete page within a hidden
field:

<input type=”hidden” name=”__VIEWSTATE”

value=”/wEPDwUKLTU4NzY5NTcwNw8WAh4HbXlzdGF0ZQUFbXl2YWwWAgIDD2QWAg
IFDw8WAh4EVGV4dAUFbXl2YWxkZGTCdCywUOcAW97aKpcjt1tzJ7ByUA==” />

Example of Viewstate

We can create counter for each time button click.

protected void Page_Load(object sender, EventArgs e)


{
if (IsPostBack == false)
{
ViewState["counter"]=0;
}

}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["counter"] =(int) ViewState["counter"] + 1;

TextBox1.Text = ViewState["counter"].ToString();
}

(B) Query string

[6th CE – DOT NET TECHNOLOGY] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Most significant limitation with viewstate is that it tightly bound to a specific page.
- If the users navigates to another page information is lost.
- There are several solutions for this and one most useful solution is querystring.
- Querystring is used to pass information between client & server.
- Querystring is the poprtion of URL after the question mark.
- Querystring commonly used in search engine.
- Querystring also a useful technique for database application.
- For example, suppose one page is there with the name users.aspx. In this page we
are displaying all the users registered with our application.
- Now if users click on particular users, it will be redirect to the userdetails.aspx page.
So, this page retrieves the UniqueId and looking the particular user in userdetails
table. Here we can get UniqueId from Querystring.

Advantages

- Very Light weight


- Simple and easy to use.

Dis Advantages

- Information is limited & must contain URL legel character.


- Information is clearly visible to the users. So the leading security problem. Some one
change the querystring data & supply new value then program not work properly.
- Different browser has different limit regarding length of URL (Usually 1 to 2k) for
that reason you can not put large amount of information in querystring.
- You can define querystring in HyperLink or in a Response.Redirect statement.
For Example,

Response.Redirect(“showdetails.aspx?id=10”)

Here id is the name of querystring.

- You can retrieve querystring data like,


TextBox1.Text = Request.QueryString[“id”];

[6th CE – DOT NET TECHNOLOGY] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- You can send multiple parameters with querystring.

Response.Redirect(showdetails.aspx?id=10&name=kazi)

For Example,

http://www.localhost.com/Webform2.aspx?id=10&Name=kazi

(C) Cookie

- Cookies are also known by many names, HTTP Cookie, Web Cookie, Browser Cookie,
Session Cookie, etc.
- Cookies are used to store information for later use.
- Cookies are small text file that created on the client’s hard drive Or if they are
temporary it will store in the internet browser’s memory.
- When the user browses the same website in the future, the data stored in the cookie
can be retrieved by the website to notify the user's previous activity.
- Cookies are simple and easy to use.
- Request & Response object is used to work with cookie.
- Important trick to remember is that you can retrieve cookies from REQUEST object
and you can set cookies using RESPONSE object.

Limitation of Cookie

- Size of cookies is limited to 4096 bytes.


- Total 20 cookies can be used on a single website; if you exceed this browser will
delete older cookies.
- End user can stop accepting cookies by browsers, so it is recommended to check the
users’ state and prompt the user to enable cookies.
- Limited to simple string information
- Easily accessible, readable if the user finds & open the corresponding file.

Ways to create Cookie:

Response.Cookies[“kazi”].Value = TextBox1.Text;

Response.Cookies[“kazi”].Expires=DateTime.Now.AddSeconds(15);

[6th CE – DOT NET TECHNOLOGY] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

These all cookies are permanent until the specified time. So the user can access the
cookies in any page directly.

Ways to get/retrieve Cookie:

TextBox1.Text = Request.Cookies[“kazi”].Value;

Deleting the Cookie:

Response.Cookies["kazi"].Expires=DateTime.Now.AddDays(-1);

Q-3 Explain Session state and Application state (Server side state
management) in .Net.

Session state:

- An application which need to store and access some complex information such as
dataset or custom data objects which can not be easily persists with cookie or sent
through Querystring. In this situation you can use Asp.net built in session state
facility.
- Session state is one of the premier features of Asp.net
- It allows storing any type of data in memory on the server.
- The information is protected because it is never transmitted to the client and it is
uniquely bound to specifics session.
- Every client that accesses the application has different session.
- Session state store session specific information and the information is
visible within the session only.
- Asp.net creates unique SessionId for each session.
- When the client presents the SessionId, Asp.net looks up the corresponding session,
retrieves the data from the state server, converts it to live objects and places these
objects into special collection so they can be accessed in code. And this process
takes place automatically.
- SessionId is maintained by either HttpCookie or URL.
- By default SessionId value stored in cookie.

[6th CE – DOT NET TECHNOLOGY] Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Storing, retrieving & remove values from Session

The following code is used for storing a value to session:


Session[“username”] = TextBox1.Text;
To retrieve values from session in any page of application:
Label1.Text = "Welcome: " + Session[“username”];
To remove a value from session:
Session.Remove["username"];

Storing and retrieving objects from Session

We can also store other objects in session. The following example


shows how to store a DataSet in session.

Session["mydata"] = ds;
The following code shows how we to retrieve that DataSet from session:
DataSet ds =(DataSet) Session["mydata"];

- In this way you can store any integer, string data in the session state.
- Session state is creating, when first request comes from browser for
individual users across all web pages.
- Session state is lost in several ways:
1. I the user close and restart browser.
2. If the session times out.
3. If the programmer ends the session by coding.

Session State Configuration

Session state configuration is stored in web.config file.


<configuration>
<system.web>
<sessionState mode="InProc" timeout ="60" cookieless="false">
</sessionState>
</system.web>
</configuration>

Cookieless:

When cookieless=”True” , the SessionId will automatically inserted into url.

[6th CE – DOT NET TECHNOLOGY] Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Timeout:

It specifies the number of minutes asp.net will wait without receiving request.

Modes: (Explain Session State Modes)

In ASP.NET, there are the following session modes available:


1. InProcess
2. StateServer
3. SQLServer
4. Custom
5. Off

1. InProc :

- It is the Default Mode for Session state.


- For the Default mode other two settings have no effect.
- Generally InProc is the best option for most websites.
- In InProc, information is stored in same worker process.
- If you restart your server, the state information will be lost.

2. StateServer

- In StateServer mode, Asp.net will use a separate windows service for


state management.
- When using stateserver setting, you need to specify value for the
StateConnectionString.
- This String identifies TCP/IP address of the computer that is running the
state server service.

[6th CE – DOT NET TECHNOLOGY] Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- This allows you to Host the StateServer on another computer.


- If you do not change this settings, the localhost server is used(127.0.0.1)
- Before using this service, you need to first start it.
- To start it, go to Administrative Tools/Services and find the service
called Asp.net StateService.
- You can manually Start and Stop it.

3. SqlServer

- This setting is used to store session information in SqlServer Database.


- To use this method, you need to have a server with sqlserver installed.
- You need to provide SqlConnectionString that specify Data
Source, UserId, and Passward etc.
- In addition you need to install the special stored procedure and
Temporary session Database.
- These stored procedures take care of storing and retrieving the session
Information.
- Asp.net includes transact.sql script for this purpose called
Installsqlstate.sql.
- It found in the WinNT\MS.Net\Framework\Version\
- You can Run this script using query analyzer and it only needs
to performed once.

[6th CE – DOT NET TECHNOLOGY] Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

4. Custom

Custom mode enables you to specify a custom storage provider.

5. Off

It will disable session state management.

Application State

- Application state creates, when first request comes from browser globally
across all web pages.
- It is very similar to session state.
- Items or value stored in application state never Timeout until the application
or server restarted.
- It stores global objects that can be accessed by any client.
- A common example of the application state is Global counter that tracks how many
times an operation has been performed by the web application’s entire object.
- For example you can create global.ashx event handler that tracks how many
sessions have been created or how many request have been received into
the application.
- You can also use similar logic in the Page_Load event handler to track how
many times a particular page requested by various clients.

protected void Page_Load(object sender, EventArgs e)


{
int count = (int)Application["counter"];

count = count + 1;

Application["counter"] = count;

TextBox1.Text=count.ToString();
}

- Application state is not often used because it is generally inefficient.


- In, previous example, the counter not count accurate in heavy traffic.
- For Example, I two client request the page at the same time, sequence of
events like this.
- 1. User A retrieves current count 100
- 2. User B retrieves current count 100
- 3. User A Sets the current count 101
- 4. User B sets the current count 101

[6th CE – DOT NET TECHNOLOGY] Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- So, one request is Lost because Two clients access the counter at the same time.

- Now, to prevent this problem you need to use Lock() and UnLock() Methods which
explicitly allow only one client to access the value of the same time.

protected void Page_Load(object sender, EventArgs e)


{
//Acquire Exclusive Access

Application.Lock();

int count = (int)Application["counter"];

count = count + 1;

Application["counter"] = count;

//Release exclusive Access

Application.UnLock()

TextBox1.Text=count.ToString();
}

- So, in this way other client can’t access the page until application collection is
released.
- This Drastically Reduce the Performance

[6th CE – DOT NET TECHNOLOGY] Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)

Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture notes
Chapter-11

1. Demonstrate web services with any example?

- Web services are program components that allow you to build distributed, platform
independent application.
- These applications use standard protocol such as HTTP, XML, SOAP and WSDL to
provide various important services.
- Web services uses xml based messaging to send & receive data.
- You can use xml web service to integrate application that are written in different
programming language and also deployed on different platforms.
- In addition you can deploy XML web services within an Intranet as well as Internet.
- One important feature of web services is that a client need not to know the language
in which web service are implemented. The client just need to know the location of
web services and the methods that client can call.
- In web service model both the client & XML Web service are unaware of the
implementation details of each other.
- Now example in which you can implement web services. (calculation of income tax
that paid by customer)
- Web service that computes income tax requires a client application to provide
information such as income, savings and investments.
- A client application can call a method on services and provide necessary information
as arguments in method call. Now data related to method call and arguments is sent
to the web services in XML format using the SOAP protocol over the HTTP transport.
- Also you can find various free web services like sendsmstoindia, sendsmstoword,
currencyconverter etc…
- Also you can implement that kind of web services with your own logic.

2. List Steps to Create and Consume Webservice.

[6th CE – DOT NET TECHNOLOGY] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Creating the Web Sevice:

- A web service is an web application which is basically a class consisting of methods


that could be used by other applications.
- To understand the concept let us create a web service that will calculate addition,
subtraction, multiplication of two inputs.
- The clients will pass two values from webpage and web service will do calculation
and provide correct result.
- This web service will have three methods:

 Default HelloWorld method


 addition Method
 multiplication Method

Take the following steps to create the web service:

Step (1): Select File--> New --> Web Site in Visual Studio, and then select ASP.Net Web
Service.

Step (2): A web service file called Service.asmx and its code behind file, Service.cs is
created in the App_Code directory of the project.

Step (3): The .asmx file has simply a WebService directive on it:

<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs"


Class="Service" %>

Step (4): Open the Service.cs file. Default web service code behind file looks like the
following:

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

[6th CE – DOT NET TECHNOLOGY] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

{
public Service () {

[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}

Step (5): Change the code behind file to add two web methods for getting the addition
and subtraction of two values as shown below:

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService


{
public Service () {

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

[WebMethod]
public int addition(int a, int b)
{
return a + b ;
}

[WebMethod]

[6th CE – DOT NET TECHNOLOGY] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

public int multiplicaton(int a, int b)


{
return a * b;
}
}

Step (6): Running the web service application gives a web service test page, which allows
testing the service methods.

Step (7) : Click on a method name, and check whether it runs properly.

[6th CE – DOT NET TECHNOLOGY] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Consuming the Web Service:

- After a creating a web service, the client can access the services provided by it. This is
known as consuming web services.
- Any applications that have proper permission to access web services can access your
XML web service and consume it services.
- The application that consumes web service is known as web service client.
- To access web service from client application you need to perform following steps.

(1) Add web reference to the web services in the client application.

- To use web services created by other programmer you should know the location of
the web service. Also you can search it via UDDI.
- To discover web service easily, visual studio.net provide a Web Reference for each
xml web service.
- You can Add Web Reference to your project by using Add Web Reference dialog box.
The Add Web Reference dialog box uses the discovery mechanism to locate xml web
services.
- Add Web Reference dialog box requests the URL for web service on site and display
it.

[6th CE – DOT NET TECHNOLOGY] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- After select web service, you click Add Reference button to Add Web Reference in
your project

(2) Generate proxy class for the XML web services.

- When you click the Add Reference button, visual studio download service description
to the local computer and generate a proxy class for the web service.
- The proxy class of web service contains information for calling each web service
method.
- Visual studio uses WSDL (Web service Description Language) to create proxy class.
- The proxy class is described in the .wsdl file.
- You can use wsdl.exe to generate proxy class manually for the web services.

(3) Create an object of the proxy class in the client application.

- After you Add Web Reference and generate proxy class, create an object of the proxy
class in the client application.
- The object of the proxy class allows you to invoke the methods of the web service
and access the result o it.

(4) Access the xml web services by using a proxy object.

- After you create an object of the proxy class, you can easily write code against an xml
web service.
- By this proxy object you can access all methods of web service.
- For Example, let us consuming above web service for addition and multiplication of
two values.

protected void Button1_Click(object sender, EventArgs e)


{
Service obj = new Service();

[6th CE – DOT NET TECHNOLOGY] Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

TextBox3.Text =
obj.addition(Int32.Parse(TextBox1.Text),
Int32.Parse(TextBox2.Text)).ToString();
}

protected void Button2_Click(object sender, EventArgs e)


{
Service obj = new Service();
TextBox3.Text =
obj.multiplicaton(Int32.Parse(TextBox1.Text),
Int32.Parse(TextBox2.Text)).ToString();
}

3. Explain SOAP and WSDL?

WSDL: (Web Service Description Language)

- WSDL is the web service description language that specifies how client interact with
a web service including details like which methods are present in web service, which
parameters and return value each method use, which protocol should be used for
transmission over internet.
- Currently three standards are supported for transmission of web service information:
HTTP GET, HTTP POST and SOAP.
- Asp.net creates WSDL documents for your web services automatically.
- Asp.net can also create a proxy class based on the WSDL document automatically.
- WSDL document contains information for communication between a web service
and client.
- It does not contain any information regarding coding or implementation of your web
service method.

SOAP: (Simple Object Access Protocol )

- SOAP is the default for Asp.net that automatically generates proxy class.
- SOAP works over HTTP but uses special xml-like format for bundling information.
- SOAP enables you to consume complex data structure like dataset or just table of
data.
- SOAP relatively simple and easy to understand.
- Asp.net web service generally uses soap over http using the http post protocol.
- An example of SOAP request (from client to web service) shown below.

[6th CE – DOT NET TECHNOLOGY] Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

SOAP request:

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>

</soap: Envelope>

SOAP response:

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>

</soap:Envelope>

- You can see that the root element is <soap:envelope> which contains the
<soap:body> of the request.
- Inside the body, web method GetStockPrice is being called.
- Now, In response to this request, SOAP output message will be returned.

4. Describe the Process of Webservice communication.

The WSDL and SOAP standards enable you to communicate between client & web
services but they do not show how this communication happens.
- The following three components play role for this:
(1) A custom web services class: That provides some piece of functionality.
(2) A client application: That wants to use this functionality.

[6th CE – DOT NET TECHNOLOGY] Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(3) A proxy class: That acts as a interface between client application & web service class.
A proxy class represents all the web service methods and takes care of communication
with web service by chosen protocol.

Actual process work like this:


1. The client creates an instance of proxy class.
2. The client invoke the method on proxy class, exactly same as normal local class.
3. Now proxy class sends the information to the web server in appropriate format
(usually SOAP) and receives the corresponding response.
4. The proxy class returns the results to the calling code.

- In this scenario, client does not need to aware regarding remote function call made to
web service. You have to just call function in own local code.
- Some limitation occurs during this process like, Not all data types are supported for
method parameters and return value.
- For example you cannot pass many .net class library objects (The dataset is one
exception)
- If error occurs that can interrupt your web method like network problems.

5. Discovering Webservice & UDDI.

- Once you create Webservice, how can client find your Webservice this is the first basic
questions.

[6th CE – DOT NET TECHNOLOGY] Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Clearly, Webservice is available at specific URL address. Once client type this URL
address then all the necessary information is available. So why discovering standard
required?
- Now process described above works great, if you only need to serve a Webservice to
specific clients or inside a single organization.
- If company provides dozens of webservices, how can it communicate with each other to
prospective clients?
- Individually serve Webservice taking time and create inefficiency.

DISCO standard

- When use Disco standard you provide a .disco file that specifies where a webservices is
located.

- Asp.net tools such as visual studio.net can read the discover file and automatically
provide you list of corresponding web services.

- The benefit of a .disco file is that it is clearly used for Webservice (while .html and .aspx
file can contain any kind of content)

- When visual studio.net creates a discovery file, it uses the extension .vsdisco

UDDI (Universal Description Discovery and Integration)

- UDDI is youngest and most rapidly developing standard.

- Using UDDI it is easy for you to locate Webservice on any server.

- It is business registry that lists information about companies.

- The goal of UDDI is to provide collection where business can advertise all the Webservice
they have.

- For example, a company has list of services for business document exchange so you
must have to register it with UDDI service.

- There are three main sections of UDDI

1. White pages, which provide business contact information

2. Yellow pages, which organize xml Webservices into categories

[6th CE – DOT NET TECHNOLOGY] Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

3. Green pages, which provides detailed information about individual services.

- UDDI registry defines complete programming interface that specifies how SOAP message
can be used to retrieve information about business object.

- In other word, UDDI registry is itself a Webservice.

- This standard is still too new to really use, but we can find detailed information at
http://www.uddi.microsoft.com

[6th CE – DOT NET TECHNOLOGY] Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Subject : Dot Net Technology (Department Elective)


Semester : 6th - Branch : CE - Subject Code : 2160711

Lecture notes
Chapter-12

Q-1 Introduction of WPF (Windows Presentation Foundation) and Features

- The Windows Presentation Foundation is Microsoft’s next generation UI framework to


create applications with a rich user experience. It is part of the .NET framework 3.0 and
higher.
- With WPF, you can create a wide range of both standalone and browser-hosted
applications. Some examples are Yahoo! Messenger, New York Times Reader etc.
- The core of WPF is a resolution-independent and vector-based rendering engine that is
built to take advantage of modern graphics hardware.

- WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia


into one single framework. Its vector based rendering engine uses hardware
acceleration of modern graphic cards. This makes the UI faster, scalable and resolution
independent.
- The following illustration gives you an overview of the main new features of WPF

[6th CE – DOT NET TECHNOLOGY] Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- WPF extends the core with a set of application-development features that include
Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and
3-D graphics, animation, styles, templates, documents, media, text, and typography.
- WPF is included in the Microsoft .NET Framework, so you can build applications that
incorporate other elements of the .NET Framework class library.

Features :
Standalone Applications
For standalone applications, you can use the Window class to create windows and
dialog boxes that are accessed from menu bars and tool bars.

Browser-Hosted Applications
For browser-hosted applications, known as XAML browser applications (XBAPs), you can
create pages and page functions that you can navigate between using hyperlinks

Code-Behind
The main behavior of an application is to implement the functionality that responds to
user interactions, including handling events (for example, clicking a menu, tool bar, or
button) and calling business logic and data access logic in response. In WPF, this
behavior is generally implemented in code that is associated with markup. This type of
code is known as code-behind.
Security
Because XBAPs are hosted in a browser, security is important. In particular, a partial-
trust security sandbox is used by XBAPs to enforce restrictions that are less than or
equal to the restrictions imposed on HTML-based applications.

Data Binding
Most applications are created to provide users with the means to view and edit data.
For WPF applications, the work of storing and accessing data is already provided for by
technologies such as Microsoft SQL Server and ADO.NET.After the data is accessed and
loaded into an application's managed objects, the hard work for WPF applications
begins.
Graphics
WPF introduces an extensive, scalable, and flexible set of graphics features that have
the following benefits:
- Resolution-independent and device-independent graphics.
- Improved precision.
- Advanced graphics and animation support.
- Hardware acceleration.

3-D Rendering

[6th CE – DOT NET TECHNOLOGY] Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

WPF also includes 3-D rendering capabilities that integrate with 2-D graphics to allow
the creation of more exciting and interesting UIs.

Animation
WPF animation support lets you make controls grow, shake, spin, and fade, to create
interesting page transitions, and more. You can animate most WPF classes, even custom
classes.

Media
One way to convey rich content is through the use of audiovisual media. WPF provides
special support for images, video, and audio.

Images
Images are common to most applications, and WPF provides several ways to use them.

Video and Audio


The Media Element control is capable of playing both video and audio, and it is flexible
enough to be the basis for a custom media player.

Text and Typography


To facilitate high-quality text rendering, WPF offers the following features:
• OpenType font support.
• ClearType enhancements.
• High performance that takes advantage of hardware acceleration.
• Integration of text with media, graphics, and animation.
• International font support and fallback mechanisms.

Documents :
WPF has native support for working with three types of documents: flow documents,
fixed documents, and XMLPaper Specification (XPS) documents. WPF also provides the
services to create, view, manage, annotate, package,and print documents.

Packaging
The WPF System.IO.Packaging APIs allow your applications to organize data, content,
and resources into single, portable, easy-to-distribute, and easy-toaccess ZIP
documents. Digital signatures can be included to authenticate items that are contained
in a package and to verify that the signed item was not tampered with or modified. You
can also encrypt packages by using rights management in order to restrict access to
protected information.

Triggers

[6th CE – DOT NET TECHNOLOGY] Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Although the main purpose of XAML markup is to implement an application's


appearance, you can also use XAML to implement some aspects of an application's
behavior. One example is the use of triggers to change an application's appearance
based on user interactions.

Themes and Skins


WPF, however, does not integrate directly with Windows themes. Because the
appearance of WPF is defined by templates, WPF includes one template for each of the
well-known Windows themes, including Aero (Windows Vista), Classic (Microsoft
Windows 2000), Luna (Microsoft Windows XP), and Royale (Microsoft Windows XP
Media Center Edition 2005). These themes are packaged as resource dictionaries that
are resolved if resources are not found in an application.

Printing
The .NET Framework includes a printing subsystem that WPF augments with support for
enhanced print system control.

Q-2 Introduction of WCF (Windows Presentation Foundation) and Features:


Windows Communication Foundation (WCF) is a framework for building service-
oriented applications. Using WCF, you can send data as asynchronous messages from
one service endpoint to another. A service endpoint can be part of a continuously
available service hosted by IIS, or it can be a service hosted in an application. An
endpoint can be a client of a service that requests data from a service endpoint. The
messages can be as simple as a single character or word sent as XML, or as complex as a
stream of binary data. A few sample scenarios include:

 A secure service to process business transactions.


 A service that supplies current data to others, such as a traffic report or other
monitoring service.
 A chat service that allows two people to communicate or exchange data in real time.
 A dashboard application that polls one or more services for data and presents it in a
logical presentation.
 Exposing a workflow implemented using Windows Workflow Foundation as a WCF
service.
 A Silverlight application to poll a service for the latest data feeds.

- While creating such applications was possible prior to the existence of WCF, WCF makes
the development of endpoints easier than ever. In summary, WCF is designed to offer a
manageable approach to creating Web services and Web service clients.

Features of WCF

[6th CE – DOT NET TECHNOLOGY] Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

 Service Orientation
Service-oriented architecture (SOA) is the reliance on Web services to send and receive
data. The services have the general advantage of being loosely-coupled instead of hard-
coded from one application to another. A loosely-coupled relationship implies that any
client created on any platform can connect to any service as long as the essential
contracts are met.

 Interoperability
WCF implements modern industry standards for Web service interoperability.

 Multiple Message Patterns


Messages are exchanged in one of several patterns. The most common pattern is the
request/reply pattern, where one endpoint requests data from a second endpoint. The
second endpoint replies. There are other patterns such as a one-way message in which a
single endpoint sends a message without any expectation of a reply. A more complex
pattern is the duplex exchange pattern where two endpoints establish a connection and
send data back and forth, similar to an instant messaging program.

 Service Metadata
WCF supports publishing service metadata using formats specified in industry standards
such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically
generate and configure clients for accessing WCF services. Metadata can be published
over HTTP and HTTPS or using the Web Service Metadata Exchange standard.

 Data Contracts
Because WCF is built using the .NET Framework, it also includes code-friendly methods
of supplying the contracts you want to enforce. One of the universal types of contracts
is the data contract. In essence, as you code your service using Visual C# or Visual Basic,
the easiest way to handle data is by creating classes that represent a data entity with
properties that belong to the data entity. WCF includes a comprehensive system for
working with data in this easy manner. Once you have created the classes that
represent data, your service automatically generates the metadata that allows clients to
comply with the data types you have designed.

 Security
Messages can be encrypted to protect privacy and you can require users to authenticate
themselves before being allowed to receive messages. Security can be implemented
using well-known standards such as SSL or WS-Secure Conversation.

 Multiple Transports and Encodings


Messages can be sent on any of several built-in transport protocols and encodings. The
most common protocol and encoding is to send text encoded SOAP messages using is
the Hyper Text Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively,

[6th CE – DOT NET TECHNOLOGY] Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages
can be encoded as text or using an optimized binary format. Binary data can be sent
efficiently using the MTOM standard. If none of the provided transports or encodings
suit your needs you can create your own custom transport or encoding.

 Reliable and Queued Messages


WCF supports reliable message exchange using reliable sessions implemented over WS-
Reliable Messaging and using MSMQ.

 Durable Messages
A durable message is one that is never lost due to a disruption in the communication.
The messages in a durable message pattern are always saved to a database. If a
disruption occurs, the database allows you to resume the message exchange when the
connection is restored. You can also create a durable message using the Windows
Workflow Foundation (WF).

 Transactions
WCF also supports transactions using one of three transaction models: WS-Atomic
Ttransactions, the APIs in the System.Transactions namespace, and Microsoft
Distributed Transaction Coordinator.

 AJAX and REST Support


REST is an example of an evolving Web 2.0 technology. WCF can be configured to
process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be
extended to support specific XML formats, such as ATOM (a popular RSS standard), and
even non-XML formats, such as JavaScript Object Notation (JSON).

 Extensibility
The WCF architecture has a number of extensibility points. If extra capability is required,
there are a number of entry points that allow you to customize the behavior of a
service.

[6th CE – DOT NET TECHNOLOGY] Page 6

You might also like