Dot Net - Chapter-1 - Combine
Dot Net - Chapter-1 - Combine
Lecture Notes
Chapter-1
- 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.
Responsibility of CLR :
- 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.
- Type checker will verify types used in the application with CTS or CLS
standards supported by CLR, this provides type safety.
- The CLR supports structured exception handling to allow you to build robust,
maintainable code.
Implications of CLR :
- 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.
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.
- It is the large range of predefined classes that are designed to integrate with common
language runtime (CLR).
- 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…
2. Define Following.
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:
Add Class library project from visual studio 2008 new project. Suppose name is dlltest
Create class file and one method that return simple string
sn –k “C:\keyname.snk”
This will create a strong key and save it to the location C:\keyname.snk
Go to the assemblyinfo.vb file of your project. Open this file. Add this Line in file
<Assembly: AssemblyKeyFile("C:\keyname.snk")>
gacutil -I "C:\[PathToBinDirectoryInVSProject]\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.
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());
}
}
}
Lecture Notes
Chapter-2,3
- 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
Public: When Members of a class are declared as public, then they can be accessed
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
System.Console.WriteLine("Hello World!");
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.
Default Constructor:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
oopdemo obj = new oopdemo();
Console.ReadLine();
}
}
class oopdemo
{
public oopdemo()
{
Console.WriteLine("Hello Constructor");
}
}
}
Parameterized Constructor:
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");
}
Static Constructor:
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.
Console.ReadLine();
}
}
}
Output:
Destructor:
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
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
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
namespace methodoverriding
{
class BaseClass
{
public virtual string YourCity()
{
return "INDIA";
}
}
{
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
namespace methodoverriding
{
abstract class BaseClass
{
public abstract string YourCity();
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
Output : Londan
Abstract:
Override:
Inheritance
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.
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();
c1.volume();
Console.ReadLine();
}
}
class rectangle
{
public void area()
{
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
{
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();
}
}
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");
}
}
}
Property:
- 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.
- 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}
Read and Write (2) Read Only (3) Static (4) Interface property (5) Auto-implemented
Console.ReadLine();
}
}
class Class1
{
private string myname;
}
set
{
myname = value;
}
}
}
Console.ReadLine();
}
}
class Class1
{
private string myname="A R Kazi";
}
}
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;
get
{
return number;
}
}
}
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]);
}
Console.ReadLine();
}
}
class Class1
{
string[] name = new string[3];
public string this[int index]
{
set
{
name[index] = value;
}
get
{
return (name[index]);
}
}
}
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.
- 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);
{
}
}
Output
C# String Function :
Examples:
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string firstname="kazi azhar";
string lastname="kalol";
Console.WriteLine(firstname.Clone());
Console.WriteLine(firstname.CompareTo(lastname));
//Compare two string value and returns 0 for true and 1 for false
Console.WriteLine(firstname.Contains("az"));
Console.WriteLine(firstname.EndsWith("r"));
Console.WriteLine(firstname.Equals(lastname));
Console.WriteLine(firstname.GetHashCode());
Console.WriteLine(firstname.GetType());
Console.WriteLine(firstname.IndexOf("z"));
Console.WriteLine(firstname.ToLower());
Console.WriteLine(firstname.ToUpper());
Console.WriteLine(firstname.Insert(0, "Hello"));
Console.WriteLine(firstname.LastIndexOf("z"));
Console.WriteLine(firstname.Length);
Console.WriteLine(firstname.Remove(7));
Console.WriteLine(firstname.Replace('a','m'));
Console.WriteLine(firstname.Substring(2,5));
//Returns substring
Console.WriteLine(firstname.Trim());
Console.ReadLine();
}
}
}
Output
- 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:
- 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:
Description
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 :
- 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.
Syntax : ArrayList.add(object)
object : The Item to be add the ArrayList
ArrayList arr;
arr.Add("Item1");
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");
Syntax : ArrayList.Remove(object)
object : The Item to be add the ArrayList
arr.Remove("item2")
Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)
Syntax : ArrayList.Sort()
Example:
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:
Syntax : Stack.Push(Object)
Object : The item to be inserted.
Stack days = new Stack ();
days.Push("Sunday");
Syntax : Stack.Contains(Object)
Object : The specified Object to be search
days.Contains("Tuesday");
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)
days.Enqueue("SunDay");
days.Enqueue("MonDay");
days.Enqueue("TueDay");
days.Enqueue("WedDay");
days.Enqueue("ThuDay");
days.Enqueue("FriDay");
Label1.Text = days.Dequeue().ToString();
}
Output:
- 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.
- You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception.
Exception Classes in C#
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();
}
}
Lecture notes
Chapter-4
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
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.
2. Maintainability:
3. Programmability:
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.
- 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.
- ADO wasn't really designed for cross-language use. It was aimed primarily at VB
programmers.
- While ADO.Net supports multiple languages.
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.
(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
(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
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.
<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:
Insert code:
con.Open();
int i= cmd.ExecuteNonQuery();
if (i > 0)
{
Response.Write("Record Inserted Successfully!");
}
con.Close();
TextBox1.Text = "";
}
Update:
Update Code:
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Response.Write("Record Update Successful !");
}
con.Close();
TextBox1.Text = "";
}
Delete:
Delete code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["co
nstr"].ConnectionString);
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Response.Write("Record Deleted Successful !");
}
con.Close();
TextBox1.Text = "";
}
Show Records:
adap.Fill(ds, "emp");
GridView1.DataSource = ds.Tables["emp"];
GridView1.DataBind();
con.Close();
}
Dataset DataReader
2 Support multiple tables from different Support single table based on a single sql
database. query of database
10. What is a Typed and UnTyped Dataset in ADO.NET? Why do we use a Typed
DataSet?
Typed Dataset
UnTyped Dataset
- 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.
Note: See all these control in details with all its property and how to bind it with
Database.
Lecture notes
Chapter-5,6,7
1. System.Drawing Namespace
Classes Description
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.
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
3. System.Drawing.Drawing2D Namespace
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
- It also defines a class PropertyItem, which let you store and retrieve information
about the image files.
5. System.Drawing.Printing Namespace
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
- 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.
- 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:
Brush:
Example-1:
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.
g.Clear(Color.Ivory)
Next
'drawing ellipse at outer of rectangle with the black color
g.DrawEllipse(Pens.Black, rect)
End Sub
- 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.
- 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.
MDI Forms:
(1) Creating the Parent Form
(2) Creating Child Forms
(3) Accessing Child Forms
(4) Arranging Child Forms
- 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:
- 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
fm.MdiParent = this;
fm.Show();
this.LayoutMdi(MdiLayout.TileVertical);
1. FolderBrowserDialog
- Add the FoderBrowserdialog control from Dialogs toolbar into the Form.
- Make the design of form as per following figure.
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.
2. OpenFileDialog
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.
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName,textBox1.Text,System.
Text.Encoding.Default);
}
4. FontDialog
Properties:
5. Color Dialog
Chapter-8
Why ASP.NET better than ASP (Or comparison ASP & ASP.NET)
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
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)
- 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.
- 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
Examples:
- The RequiredFieldValidator control ensures that the required field is not empty. If
you want any field compulsory then use this validation control.
</asp:RequiredFieldValidator>
- 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.
- 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
(4) RegularExpressionValidator
<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.
- 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.
(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.
1. Machine.config
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>.
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.
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 in the web.config file are human readable, which means they can be
edited and understood without needing a special configuration tool.
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
<configuration>
<appSettings>
<add key="constr" value="datasource=sqlexpress; initial
catalog=test; Integrated security=true"/>
</appSettings>
</configuration>
SqlConnection con=New
SqlConnection(ConfigurationSettings.AppSettings["constr"])
- Using <ConnectionStrings>:
<configuration>
<connectionStrings>
<add name="constr" connectionString="datasource=sqlexpress;
initial catalog=test; Integrated security=true"/>
</connectionStrings>
</configuration>
2. Compilation Settings
- 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>
- 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.
- 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.
- 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>
- 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>
7. Authentication Settings
<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
- 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
9. httpRuntime settings
(1) AdRotator
<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.
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.
Lecture notes
Chapter-9
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
- In web.config file,
<system.web>
<pages masterPageFile="~/MasterPage2.master">
</pages>
</system.web>
- In web.config file,
<configuration>
<location path ="Admin">
<system.web>
<pages masterPageFile="MasterPage2.master">
</pages>
</system.web>
</location>
</configuration>
- In Page Directive,
btn.BackColor = Drawing.Color.Blue
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.
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.
- By right clicking on Theme folder you can create .skin file and .css file as per your
requirement.
h1
{
color: navy;
margin-left: 20px;
}
- In web.config file,
<system.web>
<pages theme="summer">
</pages>
</system.web>
- In web.config file,
<configuration>
<location path ="Admin">
<system.web>
<pages theme="winter">
</pages>
</system.web>
</location>
</configuration>
Lecture notes
Chapter-10
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
A. View state
B. Cookies
C. Query strings
(2) Server – Side State Management
A. session state
B. Application state
- 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:-
For Specific page - by setting the EnableViewState attribute of the Page directive, as
In the HTML code you can see the ViewState of the complete page within a hidden
field:
value=”/wEPDwUKLTU4NzY5NTcwNw8WAh4HbXlzdGF0ZQUFbXl2YWwWAgIDD2QWAg
IFDw8WAh4EVGV4dAUFbXl2YWxkZGTCdCywUOcAW97aKpcjt1tzJ7ByUA==” />
Example of Viewstate
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["counter"] =(int) ViewState["counter"] + 1;
TextBox1.Text = ViewState["counter"].ToString();
}
- 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
Dis Advantages
Response.Redirect(“showdetails.aspx?id=10”)
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
Response.Cookies[“kazi”].Value = TextBox1.Text;
Response.Cookies[“kazi”].Expires=DateTime.Now.AddSeconds(15);
These all cookies are permanent until the specified time. So the user can access the
cookies in any page directly.
TextBox1.Text = Request.Cookies[“kazi”].Value;
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.
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.
Cookieless:
Timeout:
It specifies the number of minutes asp.net will wait without receiving request.
1. InProc :
2. StateServer
3. SqlServer
4. Custom
5. Off
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.
count = count + 1;
Application["counter"] = count;
TextBox1.Text=count.ToString();
}
- 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.
Application.Lock();
count = count + 1;
Application["counter"] = count;
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
Lecture notes
Chapter-11
- 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.
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:
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 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)]
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public int addition(int a, int b)
{
return a + b ;
}
[WebMethod]
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.
- 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.
- After select web service, you click Add Reference button to Add Web Reference in
your project
- 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.
- 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.
- 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.
TextBox3.Text =
obj.addition(Int32.Parse(TextBox1.Text),
Int32.Parse(TextBox2.Text)).ToString();
}
- 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 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.
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.
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.
(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.
- 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.
- Once you create Webservice, how can client find your Webservice this is the first basic
questions.
- 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
- 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.
- UDDI registry defines complete programming interface that specifies how SOAP message
can be used to retrieve information about business object.
- This standard is still too new to really use, but we can find detailed information at
http://www.uddi.microsoft.com
Lecture notes
Chapter-12
- 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
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.
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
Printing
The .NET Framework includes a printing subsystem that WPF augments with support for
enhanced print system control.
- 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
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.
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.
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.
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.
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.