Dataset: Sort data in a Dataset: DataView
// Prerequisites: SqlConnection, SqlDataAdapter, DataSet, DataGrid objects
// Pass SQL connection with connection string
// initialize data adapter passing the query and connection object
// call fill method of data adapter with dataset object
// initialize dataview from tables propeties from dataset
// call Sort method of DataView
// Specify dataview object at the data source for datagrid
// call the bind method of datagrid
SqlConnection cn;
cn=new SqlConnection(ConnectionString);
SqlDataAdapter da;
DataSet ds=new DataSet();
da=new SqlDataAdapter("select emp_id, fname, lname from employee",cn);
da.Fill(ds);
DataView dtView = ds.Tables[0].DefaultView;
dtView.Sort = "fname ASC";
DataGrid1.DataSource=dtView;
DataGrid1.DataBind();
Wednesday, July 25, 2007
Tuesday, July 24, 2007
using Keyword: Two uses of using keyword
using: Keyword
• Defines a scope, outside of which an object/objects will be disposed
• using is also used to specify the namespace like: using System.Xml
• using statement allows the programmer to specify when objects that use resources should release them
• The object provided to the using statement must implement the Idisposable interface
• Idisposable interface provides Dispose method, which should release object’s resources
• Example:
using (SqlConnection connection = new SqlConnection(connectionString))
{
// using ensures connection object is disposed when control exits using
//block
}
• Defines a scope, outside of which an object/objects will be disposed
• using is also used to specify the namespace like: using System.Xml
• using statement allows the programmer to specify when objects that use resources should release them
• The object provided to the using statement must implement the Idisposable interface
• Idisposable interface provides Dispose method, which should release object’s resources
• Example:
using (SqlConnection connection = new SqlConnection(connectionString))
{
// using ensures connection object is disposed when control exits using
//block
}
Web.Config: Encrypt Sections Programatically
Web.Config: Encrypt Configuration Section programatically:
Configuration config = Configuration.GetWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.Sections[“ConnectionStrings”];
section.ProtectSection(“DataProtectionConfigurationProvider”);
config.Update();
Alternate Code:
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(‘sectionNameHere’);
if(section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(‘providerName’);
config.Save();
}
Configuration config = Configuration.GetWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.Sections[“ConnectionStrings”];
section.ProtectSection(“DataProtectionConfigurationProvider”);
config.Update();
Alternate Code:
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(‘sectionNameHere’);
if(section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(‘providerName’);
config.Save();
}
Web.Config: Encrypt Sections using Aspnet_regiis
Web.Config: Encrypting Configuration Sections through Aspnet_regiis
• Use the IIS Registration tool (Aspnet_regiis.exe) to encrypt or decrypt sections of a Web Configuration file
• Tool is located in: windows\Microsoft.NET\Framework\versionNumber\
• ASP.net will automatically decrypt the information when web.config is processed
• System.Configuration classes can also be used
• Syntax for Encrypting:
aspnet_regiis –pe “connectionStrings” –app “/SampleApplication” –prov “RSAProtectedConfigurationProvider”
• Syntax for Decrypting:
aspnet_regiis –pd “connectionStrings” –app “/SampleApplication”
• Use the IIS Registration tool (Aspnet_regiis.exe) to encrypt or decrypt sections of a Web Configuration file
• Tool is located in: windows\Microsoft.NET\Framework\versionNumber\
• ASP.net will automatically decrypt the information when web.config is processed
• System.Configuration classes can also be used
• Syntax for Encrypting:
aspnet_regiis –pe “connectionStrings” –app “/SampleApplication” –prov “RSAProtectedConfigurationProvider”
• Syntax for Decrypting:
aspnet_regiis –pd “connectionStrings” –app “/SampleApplication”
XML: Basics, Attributes Collection
XML: Process XML Data In-Memory: System.XML
• DOM is an in-memory tree representation of an XML document.
• XMLDocument, XpathDocument, XpathNavigator classes allow construction of XML documents, load and access data, modify and save the changes
• XpathDocument class is read-only based on Xpath data model
• XpathNavigator class offers several editing options and navigation capabilities using a cursor model
Accessing Attributes in the DOM:
• Attributes are properties of the element, not children of the element
• When the current node is an element, use the HasAttribute method to see if there are any attributes associated with the element
• Some important methods for retrieving XML data:
• XmlElement.GetAttribute, GetAttributeNode: Get attributes as collection
• XmlElement.Attributes property to retrieve all the attributes
• XMLAttributeCollection.Count to get the number of attributes
• DOM is an in-memory tree representation of an XML document.
• XMLDocument, XpathDocument, XpathNavigator classes allow construction of XML documents, load and access data, modify and save the changes
• XpathDocument class is read-only based on Xpath data model
• XpathNavigator class offers several editing options and navigation capabilities using a cursor model
Accessing Attributes in the DOM:
• Attributes are properties of the element, not children of the element
• When the current node is an element, use the HasAttribute method to see if there are any attributes associated with the element
• Some important methods for retrieving XML data:
• XmlElement.GetAttribute, GetAttributeNode: Get attributes as collection
• XmlElement.Attributes property to retrieve all the attributes
• XMLAttributeCollection.Count to get the number of attributes
Monday, July 23, 2007
ADO.net DataAdapter Update Code Listing
Code Listing: Updating through DataAdapter
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = @CategoryName " +
"WHERE CategoryID = @CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"@CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"@CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = @CategoryName " +
"WHERE CategoryID = @CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"@CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"@CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
Web.Config: Read ConnectionStrings from Web.Config
Read Connection String from Web.Config:
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(“/WebsiteRoot”);
System.Configuration.ConnectionStringSettings connString;
if(0< rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
{
connString = rootWebConfig.ConnectionStrings.ConnectionStrings[“NorthwindConnectionString”];
if(null != connString)
Console.WriteLine(“Northwind conn string = \” {0}\”, connString.ConnectionString);
else
Console.WriteLine(“Conn string not found..”);
}
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(“/WebsiteRoot”);
System.Configuration.ConnectionStringSettings connString;
if(0< rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
{
connString = rootWebConfig.ConnectionStrings.ConnectionStrings[“NorthwindConnectionString”];
if(null != connString)
Console.WriteLine(“Northwind conn string = \” {0}\”, connString.ConnectionString);
else
Console.WriteLine(“Conn string not found..”);
}
.net Framework : JIT Just in time compilation
JIT Compilation: Just in time:
•JIT compiler connverts MSIL to a native code
•Native code is CPU specific that runs on the same computer architecture as the JIT compiler
•JIT compilation takes into account the fact that some code may never get called during the execution
•Rather then converting entire MSIL into native code, it converts the MSIL as needed during the execution and stores the native code so that it is accessible for subsequent calls
•JIT compiler connverts MSIL to a native code
•Native code is CPU specific that runs on the same computer architecture as the JIT compiler
•JIT compilation takes into account the fact that some code may never get called during the execution
•Rather then converting entire MSIL into native code, it converts the MSIL as needed during the execution and stores the native code so that it is accessible for subsequent calls
Reflection: Basics, Code Listing
Reflection:
• Reflection provides objects that encapsulate assemblies, modules and types
• Reflection can be used to dynamically create an object of the class
• Bind an object to a class, or get type from an object
• Also invoke the object’s methods and access its field and properties
Uses:
• Use Assembly to load and define assembly
• Load modules that are listed in the assemly manifest
• See inside a module to find out assembly that contains the module and classes inside that module
• Classes in System.Reflection.Emit allow to build types at runtime
Viewing Type Information:
• System.Type class is central to reflection. CLR runtime creates the Type for a loaded type when reflection requests it
• Use Assembly.GetType or GetTypes to obtain Type objects from assemblies that have not been loaded
Code Listing: Reflection:
using System;
using System.Reflection;
class ListMembers
{
public static void Main(Stringp[] args)
{
Type t = typeof(System.String);
Console.WriteLine(“Listing public constructors of the {0} type ”, t);
ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine(“Constructors”);
PrintMembers(ci);
}
public static void PrintMembers(MemberInfo[] ms)
{
foreach(MemberInfo m in ms)
{
Console.WriteLine(“{0}{1}”, “ “, m);
}
Console.WriteLine();
}
}
• Reflection provides objects that encapsulate assemblies, modules and types
• Reflection can be used to dynamically create an object of the class
• Bind an object to a class, or get type from an object
• Also invoke the object’s methods and access its field and properties
Uses:
• Use Assembly to load and define assembly
• Load modules that are listed in the assemly manifest
• See inside a module to find out assembly that contains the module and classes inside that module
• Classes in System.Reflection.Emit allow to build types at runtime
Viewing Type Information:
• System.Type class is central to reflection. CLR runtime creates the Type for a loaded type when reflection requests it
• Use Assembly.GetType or GetTypes to obtain Type objects from assemblies that have not been loaded
Code Listing: Reflection:
using System;
using System.Reflection;
class ListMembers
{
public static void Main(Stringp[] args)
{
Type t = typeof(System.String);
Console.WriteLine(“Listing public constructors of the {0} type ”, t);
ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine(“Constructors”);
PrintMembers(ci);
}
public static void PrintMembers(MemberInfo[] ms)
{
foreach(MemberInfo m in ms)
{
Console.WriteLine(“{0}{1}”, “ “, m);
}
Console.WriteLine();
}
}
Steps in getting data: Theory
Steps in Getting Data from the Database:
1. Create the data connection object
2. Create the Data adapter object
3.Create the dataset object
4.Invoke methods on adapter object to fill or update the data set
5.Use data binding to display the data from the data set
1. Create the data connection object
2. Create the Data adapter object
3.Create the dataset object
4.Invoke methods on adapter object to fill or update the data set
5.Use data binding to display the data from the data set
Sunday, July 22, 2007
Threading: Basics, Code Listing
Threading:
• A thread is the basic unit to which the OS allocates processor time
• Namespace: System.Threading
• A .net program has minimum of two threads, main and garbage collector
Code Listing: Threading
using System;
using System.Threading;
public class Worker
{
public void DoWork()
{
while(! _shouldStop) { Console.WriteLine(“Worker thread working...”); }
Console.WriteLine(“Worker thread terminating...”);
}
public void RequestStop()
{
_shouldStop = true;
}
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
Worker workerobject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
workerThread.Start();
Console.WriteLine(“Main thread:starting worker thread...”);
while(workerThread.IsAlive);
Thread.Sleep(1);
workerObject.RequestStop();
workerThread.Join();
Console.WriteLine(“Main Thread: Worker thread terminated...”);
}
}
• A thread is the basic unit to which the OS allocates processor time
• Namespace: System.Threading
• A .net program has minimum of two threads, main and garbage collector
Code Listing: Threading
using System;
using System.Threading;
public class Worker
{
public void DoWork()
{
while(! _shouldStop) { Console.WriteLine(“Worker thread working...”); }
Console.WriteLine(“Worker thread terminating...”);
}
public void RequestStop()
{
_shouldStop = true;
}
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
Worker workerobject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
workerThread.Start();
Console.WriteLine(“Main thread:starting worker thread...”);
while(workerThread.IsAlive);
Thread.Sleep(1);
workerObject.RequestStop();
workerThread.Join();
Console.WriteLine(“Main Thread: Worker thread terminated...”);
}
}
Object Pooling
ObjectPooling:
• Avoid the overhead of creating objects from scratch
• When an object is activated, it is pulled from the pool, on deactivation, it is placed back
• Pooling can be configured by applying the ObjectPoolingAttribute to a class
• ObjectPoolingAttribute derives from System.EnterpriseServices.ServicedComponent class
• Object pooling allows controlling the number of connections used
• Object pooling enforces minimums and maximums, precaution needed when defining maximum
Code Listing: ObjectPooling
[ObjectPooling(Enabled=true; MinPoolSize=2; MaxPoolSize=5; CreationTimeout=20000)]
public class TestObjectPooling : ServicedComponent
{
public void Perform() {}
protected override void activate() {}
protected override void Deactivate() {}
protected override bool CanBePooled()
{
return true;
}
}
• Avoid the overhead of creating objects from scratch
• When an object is activated, it is pulled from the pool, on deactivation, it is placed back
• Pooling can be configured by applying the ObjectPoolingAttribute to a class
• ObjectPoolingAttribute derives from System.EnterpriseServices.ServicedComponent class
• Object pooling allows controlling the number of connections used
• Object pooling enforces minimums and maximums, precaution needed when defining maximum
Code Listing: ObjectPooling
[ObjectPooling(Enabled=true; MinPoolSize=2; MaxPoolSize=5; CreationTimeout=20000)]
public class TestObjectPooling : ServicedComponent
{
public void Perform() {}
protected override void activate() {}
protected override void Deactivate() {}
protected override bool CanBePooled()
{
return true;
}
}
DCOM: Theory
DCOM:
• Allows creation of objects distributed across a network
• DCOM provides a protocol for invoking that object’s methods, and secure access to the object
• DCOM provides a wrapper around COM, and hence it is backward compatible
• DCOM uses Remote Procedure Call
• Protocol gets registered just prior to use rather then at initialization
• To convey alive status of client, periodic pinging is used
• In DCOM, multiple QueryInterfaces are all clustered into one call
DCOM Call Security:
• Authentication: Prevent false clients from impersonating the true client
• Authorization: Client’s actions are appropriate
• Data integrity: Ensure data was not tampered during transit
• Data privacy: Ensure only authorized users can access it
• Allows creation of objects distributed across a network
• DCOM provides a protocol for invoking that object’s methods, and secure access to the object
• DCOM provides a wrapper around COM, and hence it is backward compatible
• DCOM uses Remote Procedure Call
• Protocol gets registered just prior to use rather then at initialization
• To convey alive status of client, periodic pinging is used
• In DCOM, multiple QueryInterfaces are all clustered into one call
DCOM Call Security:
• Authentication: Prevent false clients from impersonating the true client
• Authorization: Client’s actions are appropriate
• Data integrity: Ensure data was not tampered during transit
• Data privacy: Ensure only authorized users can access it
COM: Reference Counting, IUnknown, AddRef, Release
Reference Counting: COM
• COM does not remove an unreference object automatically
• Programmer is supposed to remove the unused object
• Programmer decides to remove on the basis of reference count
• COM uses IUnknown methods AddRef and Release to manage reference count
• AddRef is called whenever a client receives an interface pointer
• Release: when client has finished using the interface pointer, it must call Release
• COM does not remove an unreference object automatically
• Programmer is supposed to remove the unused object
• Programmer decides to remove on the basis of reference count
• COM uses IUnknown methods AddRef and Release to manage reference count
• AddRef is called whenever a client receives an interface pointer
• Release: when client has finished using the interface pointer, it must call Release
Interop: Convert COM Library to Metdata, tlbimp.exe
Generate Interop Assemblies from type Libraries: Tlbimp.exe
• Tlbimp.exe is a command-line tool that converts the coclasses and interfaces contained in a COM type library to metadata
• This tool creates an interop assembly and namespace for the type information automatically
• Once the metadata is available, managed clients can create instances of COM type and call its methods just as if they were a .net instance
• Syntax of Type Library Importer or Tlbimp.exe
tlbimp
Example: tlbimp somedllfile.dll /out: renamed.dll
• Tlbimp.exe is a command-line tool that converts the coclasses and interfaces contained in a COM type library to metadata
• This tool creates an interop assembly and namespace for the type information automatically
• Once the metadata is available, managed clients can create instances of COM type and call its methods just as if they were a .net instance
• Syntax of Type Library Importer or Tlbimp.exe
tlbimp
Example: tlbimp somedllfile.dll /out: renamed.dll
COM: Com Callable Wrapper

COM Callable Wrapper: CCW
• When a COM client calls a .net object, the CLR creates the managed object and a CCW for the object
• Unable to reference a .net object directly, COM client uses the CCW as a proxy for the managed object
• The runtime created only one CCW for the object, regardless of the number of COM clients requesting the CCW as a proxy for the managed object
• CCW are invisible to other classes running within the .net framework
• Their primary purpose is to marshal calls between managed and unmanaged code
• CCW also manage the object identity and object lifetime of the managed objects they wrap
Points to remember: Misc
App_code directory is a new feature, it was not present in ASP.net 1.0 and 1.1
The System Namespace is the root namespace for fundamental types in the .net framework
System Namespace includes classes that represent the base data types used by all application
All types derive from the System.Object base type
A type can implement any number of interfaces
To implement an interface, a type must implement all the virtual members of that interface
Passing a structure by reference is equivalent to passing an object by value
A cookie without an expiration date is a session cookie
The System Namespace is the root namespace for fundamental types in the .net framework
System Namespace includes classes that represent the base data types used by all application
All types derive from the System.Object base type
A type can implement any number of interfaces
To implement an interface, a type must implement all the virtual members of that interface
Passing a structure by reference is equivalent to passing an object by value
A cookie without an expiration date is a session cookie
Webservices : Basics Code Listing
Web Services or webservices
Creating Webservice in Visual Studio:
1. Visual Studio installed templates, select ASP.net Web Service
2. Save it giving a name TemperatureWebService
3. Right click application name, add new item, select Web service, name it Convert
4. Two files are created, Convert.cs and Convert.asmx
5. Add following code in Convert.cs
[System.Web.Services.WebMethod()]
public double FahrenheitToCelsius(double Fahrenheit)
{
return((FahrenheitToCelsius - 32) *5)
}
[System.Web.Services.WebMethod()]
public double CelsiusToFahrenheit(double Celsius)
{
return ((Celsius * 9) / 5) +32;
}
Creating Webservice in Visual Studio:
1. Visual Studio installed templates, select ASP.net Web Service
2. Save it giving a name TemperatureWebService
3. Right click application name, add new item, select Web service, name it Convert
4. Two files are created, Convert.cs and Convert.asmx
5. Add following code in Convert.cs
[System.Web.Services.WebMethod()]
public double FahrenheitToCelsius(double Fahrenheit)
{
return((FahrenheitToCelsius - 32) *5)
}
[System.Web.Services.WebMethod()]
public double CelsiusToFahrenheit(double Celsius)
{
return ((Celsius * 9) / 5) +32;
}
String: Keyword Basics
• string is an alias for String in the .net framework
• Equality operators == and != are used to compare the values of string objects not references
• Use of @ symbol in string handling:
To assign a string that has quotation marks use @:
Like this: @”good morning”
Or: To include slashes: @”C:\temp\bin”;
• Use of equality operators:
string a = “hello”; string b = “h”;
b = b + “ello”;
Console.Writeline(a==b); // output is true
Console.Writeline((object)a == (object)b); // output is false
• First is true as contents of strings are same/equivalent
• Second is false, as a and b do not refer to the same string instance
• Equality operators == and != are used to compare the values of string objects not references
• Use of @ symbol in string handling:
To assign a string that has quotation marks use @:
Like this: @”good morning”
Or: To include slashes: @”C:\temp\bin”;
• Use of equality operators:
string a = “hello”; string b = “h”;
b = b + “ello”;
Console.Writeline(a==b); // output is true
Console.Writeline((object)a == (object)b); // output is false
• First is true as contents of strings are same/equivalent
• Second is false, as a and b do not refer to the same string instance
Object keyword: Code Listing
Code Listing: object
using System;
class SampleClass
{
public int i = 10;
}
class MainClass
{
static void Main()
{
object a;
a =1; // example of boxing
Console.Writeline(a);
Console.Writeline(a.GetType());
Console.Writeline(a.ToString());
a = new SampleClass();
SampleClass classRef;
classRef = (SampleClass)a;
Console.Writeline(classRef.i);
}
}
using System;
class SampleClass
{
public int i = 10;
}
class MainClass
{
static void Main()
{
object a;
a =1; // example of boxing
Console.Writeline(a);
Console.Writeline(a.GetType());
Console.Writeline(a.ToString());
a = new SampleClass();
SampleClass classRef;
classRef = (SampleClass)a;
Console.Writeline(classRef.i);
}
}
Object : Keyword: Basics, Boxed, Unboxed
• object is an alias for Object in the .net framework
• All types, predefined, userdefined, reference types, value types, inherit directly or indirectly from Object
• It is possible to assign values of any type to variables of type object
• When a variable of value type is converted to object, it is said to be boxed
• When a variable of type object is converted to a value type, it is said to be unboxed
• All types, predefined, userdefined, reference types, value types, inherit directly or indirectly from Object
• It is possible to assign values of any type to variables of type object
• When a variable of value type is converted to object, it is said to be boxed
• When a variable of type object is converted to a value type, it is said to be unboxed
Delegate : Code Listing
Code Listing: Delegate:
using System;
// Declare delegate
delegate void SampleDelegate(string message);
class MainClass
{
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with a named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method
SampleDelegate d2 = delegate(string message)
{
Console.Writeline(message);
};
//invoke delegate d1
d1(“hello”);
// invoke delegate d2
d2(“world”);
}
}
using System;
// Declare delegate
delegate void SampleDelegate(string message);
class MainClass
{
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with a named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method
SampleDelegate d2 = delegate(string message)
{
Console.Writeline(message);
};
//invoke delegate d1
d1(“hello”);
// invoke delegate d2
d2(“world”);
}
}
Interface: Keyword: Basics
• An interface contains only signatures of methods, delegates or events
• Implementation of the interface is done by the class that implements the interface
• An interface can inherit from one or more base interfaces
• When a base type list contains a base class and interfaces, the base type class must come first in the list
• A class that implements an interface can explicitly implement members of that interface
• Implementation of the interface is done by the class that implements the interface
• An interface can inherit from one or more base interfaces
• When a base type list contains a base class and interfaces, the base type class must come first in the list
• A class that implements an interface can explicitly implement members of that interface
Delegate : Keyword: Basics
• Syntax: public delegate void TestDelegate(String message);
• Used to declare a reference type that can be used to encapsulate named or an anonymous method
• Delegates are similar to function pointers but are type safe and thread secure
• Delegates are the basis for Events
• For use with named methods, a delegate must be instantiated with a method that has an acceptable signature
• For use with anoymous methods, the delegate and the code to be associated with it are declared together
• Used to declare a reference type that can be used to encapsulate named or an anonymous method
• Delegates are similar to function pointers but are type safe and thread secure
• Delegates are the basis for Events
• For use with named methods, a delegate must be instantiated with a method that has an acceptable signature
• For use with anoymous methods, the delegate and the code to be associated with it are declared together
Class: keyword, Generic Class
• Declared using keyword: class
• Only single inheritance is allowed in C#
• Class can implement more then one interface
• A class can inherit as well as implement an interface at one time
• Syntax: class ImplDerivedClass: BaseClass, Iface1()
• Access levels protected and private are only allowed on nested classes
• Types declared inside a class without an access modifier default to private
Generic Classes:
• Generic classes encapsulate operations that are not specific to a particular data type
• Most common use of such classes are in collections like linked lists, hash tables, stacks where general operations are performed regardless of data type
• Only single inheritance is allowed in C#
• Class can implement more then one interface
• A class can inherit as well as implement an interface at one time
• Syntax: class ImplDerivedClass: BaseClass, Iface1()
• Access levels protected and private are only allowed on nested classes
• Types declared inside a class without an access modifier default to private
Generic Classes:
• Generic classes encapsulate operations that are not specific to a particular data type
• Most common use of such classes are in collections like linked lists, hash tables, stacks where general operations are performed regardless of data type
Char: Keyword
• Range: U+0000 to U+ffff
• Size: Unicode 16-bit character
• Constants of char type can be written as character literals, hexadecimal escape sequence, or Unicode representation
• All the following are valid assignments:
char char1 = ‘Z’
char char2 = ‘\x0058’
char char3 = (char)88
char char4 = ‘\u0058’
• Size: Unicode 16-bit character
• Constants of char type can be written as character literals, hexadecimal escape sequence, or Unicode representation
• All the following are valid assignments:
char char1 = ‘Z’
char char2 = ‘\x0058’
char char3 = (char)88
char char4 = ‘\u0058’
Byte: keyword
• Range: 0 to 255
• This causes compilation error: byte x =10, y=20; due to automatic conversion to int
• There is a predefined implicit conversion from byte to short, ushort, int, uint, long, ulong, float, double, decimal
• No implcit conversion from floating-point types to byte
• This causes compilation error: byte x =10, y=20; due to automatic conversion to int
• There is a predefined implicit conversion from byte to short, ushort, int, uint, long, ulong, float, double, decimal
• No implcit conversion from floating-point types to byte
Enum: keyword, Code Listing
Enum:
• enum is a distinct type consisting of a set of named constants called the enumerator list
• Every enumeration type has an underlying type, which can be any integral type EXCEPT char
• Default underlying type of the enumeration is int
• enums start with 0 advancing by 1, can be forced to start with 1 or custom value
• Default : enum days{Sat, Sun, Mon, Tue, Wed, Thu, Fri};
• Cusotm setting: enum days{Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
• Default value of an enum E is the value produced by the expression (E)0
• Typecasting needed for assigment: int x = (int)days.Sun;
• enum is a distinct type consisting of a set of named constants called the enumerator list
• Every enumeration type has an underlying type, which can be any integral type EXCEPT char
• Default underlying type of the enumeration is int
• enums start with 0 advancing by 1, can be forced to start with 1 or custom value
• Default : enum days{Sat, Sun, Mon, Tue, Wed, Thu, Fri};
• Cusotm setting: enum days{Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
• Default value of an enum E is the value produced by the expression (E)0
• Typecasting needed for assigment: int x = (int)days.Sun;
Dictionary: keyword, Code Listing
• Provides a mapping from a set of keys to set of values
• Each addition to the dictionary consists of a value and its associated key
• Dictionary class is implemented as a HashTable
• Key must be unique
• Initial capacity of a dictionary is 3, reallocation happens as new elements are added
• Declaration: Dictionary dictName = new Dictionary();
• ContainsKey: myDict.ContainsKey(“keyHere”);
• Loop Contents:
foreach(KeyValuePair kvp in myDict)
{
Console.WriteLine(kvp.Key, kvp.Value);
}
• Each addition to the dictionary consists of a value and its associated key
• Dictionary class is implemented as a HashTable
• Key must be unique
• Initial capacity of a dictionary is 3, reallocation happens as new elements are added
• Declaration: Dictionary
• ContainsKey: myDict.ContainsKey(“keyHere”);
• Loop Contents:
foreach(KeyValuePair
{
Console.WriteLine(kvp.Key, kvp.Value);
}
ArrayList: keyword, Code Listing
ArrayList:
• ArrayList implements IList interface
• Size can be increased dynamically as required
• Not guaranteed to be sorted
• Default initial capacity is 0, as elements are added, capacity is increased through reallocation
• Capacity can be decreased through TrimToSize or setting Capacity property
• To guarantee ThreadSafety of the ArrayList, all operations must be done through the wrapper returned by the Synchronized method
Code Listing:ArrayList
ArrayList myAL = new ArrayList();
myAL.Add(“Hello”);
myAL.Add(“World”);
myAL.Add(“!!!”);
Console.WriteLine(myAL.Count);
Console.WriteLine(myAL.Capacity);
PrintValues(myAL);
public static void PrintValues(IEnumerable myList )
{
foreach(Object obj in mylist)
Console.Write(obj);
Console.WriteLine();
}
• ArrayList implements IList interface
• Size can be increased dynamically as required
• Not guaranteed to be sorted
• Default initial capacity is 0, as elements are added, capacity is increased through reallocation
• Capacity can be decreased through TrimToSize or setting Capacity property
• To guarantee ThreadSafety of the ArrayList, all operations must be done through the wrapper returned by the Synchronized method
Code Listing:ArrayList
ArrayList myAL = new ArrayList();
myAL.Add(“Hello”);
myAL.Add(“World”);
myAL.Add(“!!!”);
Console.WriteLine(myAL.Count);
Console.WriteLine(myAL.Capacity);
PrintValues(myAL);
public static void PrintValues(IEnumerable myList )
{
foreach(Object obj in mylist)
Console.Write(obj);
Console.WriteLine();
}
Array: keyword, Code Listing
Array:
• An element is a value in an array
• Rank means the dimensions of array
• Lower bound is the starting index of the array
• Array.Copy handles typecasting automatically, allows copying between different types of arrays
Code Listing:Array.Copy
int[] intarray = new int[5] {1,2,3,4,5};
Object[] objarray = new Object[5] {26,27,28};
// Copy first two elements from int array to object array:
Array.Copy(intarray, objarray,2);
• An element is a value in an array
• Rank means the dimensions of array
• Lower bound is the starting index of the array
• Array.Copy handles typecasting automatically, allows copying between different types of arrays
Code Listing:Array.Copy
int[] intarray = new int[5] {1,2,3,4,5};
Object[] objarray = new Object[5] {26,27,28};
// Copy first two elements from int array to object array:
Array.Copy(intarray, objarray,2);
Hashtable: Basics: Code Listing
HashTable:
• Represents a collection of key/value pairs that are organized based on the hash code of the key
• Namespace: Systems.Collection
• Each element is a key/value stored in a DictionaryEntry object
• Value can be null, but key can not
• Objects used as keys must override the Object.GetHashCode and Object.Equals
• Key object must be immutable
• Default initial capacity of HashTable is zero
• Not safe for mutli-threaded access
Code Listing: HashTable
using System;
using System.Collections;
class Example
{
public static void Main()
{
HashTable openwith = new HashTable();
openwith.Add(“txt”,”notepad.exe”);
openwith.Add(“bmp”,”paint.exe”);
try
{
openwith.Add(“txt”,”winword.exe”);
}
catch
{
Console.Writeline(“Key \”txt\” already exists..”);
}
ICollection valuecol = openwith.Values;
foreach(string s in valuecol)
{
Console.Writeline(“Value = ” s);
}
}
}
• Represents a collection of key/value pairs that are organized based on the hash code of the key
• Namespace: Systems.Collection
• Each element is a key/value stored in a DictionaryEntry object
• Value can be null, but key can not
• Objects used as keys must override the Object.GetHashCode and Object.Equals
• Key object must be immutable
• Default initial capacity of HashTable is zero
• Not safe for mutli-threaded access
Code Listing: HashTable
using System;
using System.Collections;
class Example
{
public static void Main()
{
HashTable openwith = new HashTable();
openwith.Add(“txt”,”notepad.exe”);
openwith.Add(“bmp”,”paint.exe”);
try
{
openwith.Add(“txt”,”winword.exe”);
}
catch
{
Console.Writeline(“Key \”txt\” already exists..”);
}
ICollection valuecol = openwith.Values;
foreach(string s in valuecol)
{
Console.Writeline(“Value = ” s);
}
}
}
Out: Keyword: Basics, Code listing
CodeListing:Out
class OutExample
{
static void Method(out int i)
{
i=44;
}
static voic Main()
{
int val; // val not initialized before use
Method(out val) // val is now 44
}
}
class OutExample
{
static void Method(out int i)
{
i=44;
}
static voic Main()
{
int val; // val not initialized before use
Method(out val) // val is now 44
}
}
Ref keyword: Basics, Code Listing
Ref:
Ref is used to pass parameters by reference
Any changes made to the parameter in the method will be reflected in the variable
ref parameter must be initialized before its use
Out:
Out is used to pass parameters by reference
Parameter not required to be initialized before use
Any changes made to the parameter in the method will be reflected in the variable
CodeListing:Ref
class RefExample
{
static void Method(ref int i)
{
i=44;
}
static voic Main()
{
int val=0;
Method(ref val) // val is now 44
}
}
Ref is used to pass parameters by reference
Any changes made to the parameter in the method will be reflected in the variable
ref parameter must be initialized before its use
Out:
Out is used to pass parameters by reference
Parameter not required to be initialized before use
Any changes made to the parameter in the method will be reflected in the variable
CodeListing:Ref
class RefExample
{
static void Method(ref int i)
{
i=44;
}
static voic Main()
{
int val=0;
Method(ref val) // val is now 44
}
}
Checked and Unchecked Keyword
Checked:
Checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations
Expressions insode a Checked block can throw a compile time error in event of an overflow of expression has constants, else System.OverflowException is thrown
Unchecked:
Expressions inside an unchecked block do not throw exception
Unchecked keyword is used to suppress overflow checking
Result is truncated to fit into destination type to avoid overflow
Code Listing: Unchecked
unchecked
{
int val = 2147483123 * 2;
}
This will cause an overflow, as result wont fit in int
No error/exception is reported and result is truncated to fit in int
Checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations
Expressions insode a Checked block can throw a compile time error in event of an overflow of expression has constants, else System.OverflowException is thrown
Unchecked:
Expressions inside an unchecked block do not throw exception
Unchecked keyword is used to suppress overflow checking
Result is truncated to fit into destination type to avoid overflow
Code Listing: Unchecked
unchecked
{
int val = 2147483123 * 2;
}
This will cause an overflow, as result wont fit in int
No error/exception is reported and result is truncated to fit in int
HttpHandler: Creating A Synch Handler: Code Listing
Creating a Synch HttpHandler
Creating a handler for extension .sample
Class must implement the ProcessRequest method and the IsReusable property
Handler must be registered in web.config as under:
configuration system.web httpHandlers
add verb=”*” path=”*.sample” type=”HelloWorldHandler”
httpHandlers system.web configuration
In IIS, right click app directory -> Properties -> Virtual Directory -> Configuration
Mappings -> Click Add, enter Aspnet_isapi.dll, Extension:.sample, clear verify
Code Listing: HttpHandler (Synch)
using System.Web;
public class HelloWorldHandler:IhttpHandler
{
public HelloWorldHandler(){}
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
Response.Write(html);
Response.Write(“body”);
Response.Write(“Hello World, you requested a resource with extension .sample”);
Response.Write(“/body”);
Response.Write(/html);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Creating a handler for extension .sample
Class must implement the ProcessRequest method and the IsReusable property
Handler must be registered in web.config as under:
configuration system.web httpHandlers
add verb=”*” path=”*.sample” type=”HelloWorldHandler”
httpHandlers system.web configuration
In IIS, right click app directory -> Properties -> Virtual Directory -> Configuration
Mappings -> Click Add, enter Aspnet_isapi.dll, Extension:.sample, clear verify
Code Listing: HttpHandler (Synch)
using System.Web;
public class HelloWorldHandler:IhttpHandler
{
public HelloWorldHandler(){}
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
Response.Write(html);
Response.Write(“body”);
Response.Write(“Hello World, you requested a resource with extension .sample”);
Response.Write(“/body”);
Response.Write(/html);
}
public bool IsReusable
{
get
{
return false;
}
}
}
HttpHandler: Basics Types
To create a Synchronous HttpHandler, create a class that implements the IhttpHandler interface
For Asynchronous, implement IhttpAsyncHandler, BeginProcessRequest and EndProcessRequest
Custom file extensions must be registered with IIS and ASP.net
Extension ashx is already registered with IIS and ASP.net
Asynch Http handlers allows to start an external process and then continue the process of handler without waiting for the external process to finish
For Asynchronous, implement IhttpAsyncHandler, BeginProcessRequest and EndProcessRequest
Custom file extensions must be registered with IIS and ASP.net
Extension ashx is already registered with IIS and ASP.net
Asynch Http handlers allows to start an external process and then continue the process of handler without waiting for the external process to finish
Remoting
Remoting:
Used to create distributed applications
Namespace: System.Runtime.Remoting
Important classes: RemotingConfiguration, RemotingServices, ObjRef
RemotingConfiguration Class:
Contains static methods for interfacing with configuration settings
RemotingServices:
Provides methods to help in using and publishing remoted objects
Marshal method provides the functionality to store relevant information required to activate and communicate with a remote object
This information is stored in an instance of ObjRef class
Unmarshal creates a proxy for a remote object, that can be used like any other local object, without the need of any remoting subdivisions
Used to create distributed applications
Namespace: System.Runtime.Remoting
Important classes: RemotingConfiguration, RemotingServices, ObjRef
RemotingConfiguration Class:
Contains static methods for interfacing with configuration settings
RemotingServices:
Provides methods to help in using and publishing remoted objects
Marshal method provides the functionality to store relevant information required to activate and communicate with a remote object
This information is stored in an instance of ObjRef class
Unmarshal creates a proxy for a remote object, that can be used like any other local object, without the need of any remoting subdivisions
String and StringBuilder
Difference: String & String Builder:
String object is immutable
A new string object is created whenever a string object is modified
System.Text.StringBuilder can be used for strings that are repeatedly modified
StringBuilder sb = new StringBuilder(), sb.Append(“text”);
StringBuilder Methods:
Append: Add to end of text
AppendFormat: Append with format specifications
AppendLine: Append with a linefeed
EnsureCapacity: Set the minimum size of StringBuilder
Remove: Removes specified range of characters
Replace: Replace one string from other
String object is immutable
A new string object is created whenever a string object is modified
System.Text.StringBuilder can be used for strings that are repeatedly modified
StringBuilder sb = new StringBuilder(), sb.Append(“text”);
StringBuilder Methods:
Append: Add to end of text
AppendFormat: Append with format specifications
AppendLine: Append with a linefeed
EnsureCapacity: Set the minimum size of StringBuilder
Remove: Removes specified range of characters
Replace: Replace one string from other
Response.Redirect
Response.Redirect:
Defined in HttpResponse namespace
HttpResponse.Redirect(String) – Redirects a client to a new URL and specifies the new URL
HttpResponse.Redirect(String, Boolean) – Redirects, Specifies new URL with current page processing termination permission
Defined in HttpResponse namespace
HttpResponse.Redirect(String) – Redirects a client to a new URL and specifies the new URL
HttpResponse.Redirect(String, Boolean) – Redirects, Specifies new URL with current page processing termination permission
Server.Transfer
Server.Transfer:
+ Transfers a user to a URL or webform, without changing URL on client browser
+ Can not be used to send the user to an external site
+ Has a second parameter ‘preserveForm’, if true, it maintains form variables in the page from which the transfer initiates
+If textbox1 value on page 1 is needed on page2, it can be done by Request.Form(“textbox.Text”)
+ Transfers a user to a URL or webform, without changing URL on client browser
+ Can not be used to send the user to an external site
+ Has a second parameter ‘preserveForm’, if true, it maintains form variables in the page from which the transfer initiates
+If textbox1 value on page 1 is needed on page2, it can be done by Request.Form(“textbox.Text”)
Authentication: Forms Authentication: Code Listing
Code Listing: FormsAuthentication
if(FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
else
{
txtPassword.Text = “”;
if(System.Convert.ToInt32(ViewState[“Tries”]) >1 )
Response.Redirect(“Denied.htm”);
else
ViewState[“Tries”] = System.Convert.ToInt32(ViewState[“Tries”]) + 1;
}
Authenticate method checks the username and password against the user’s list found in the element of the web.config
if(FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
else
{
txtPassword.Text = “”;
if(System.Convert.ToInt32(ViewState[“Tries”]) >1 )
Response.Redirect(“Denied.htm”);
else
ViewState[“Tries”] = System.Convert.ToInt32(ViewState[“Tries”]) + 1;
}
Authenticate method checks the username and password against the user’s list found in the
Authentication: Forms Authentication: Class
Class: FormsAuthentication
Namespace: System.Web.Security
Assembly: System.Web (in system.web.dll)
Forms authentication enables username and password validation for Web applications that do not require windows authentication
Once a user is authenticated, forms authentication maintains an authentication ticket in a cookie or in the URL
FormsAuthentication Public Properties:
DefaultURL: URL that user is redirected when no redirect URL is specified
LoginURL : URL to the login page
SlidingExpiration: Enable/Disable sliding expiration
FormsCookieName: Name of the cookie used to store the forms auth ticket
RedirectFromLoginPage: Sends user to requested URL after authentication
RedirectToLoginPage: Redirects to login URL
SignOut: Removes authentication ticket from the browser
Namespace: System.Web.Security
Assembly: System.Web (in system.web.dll)
Forms authentication enables username and password validation for Web applications that do not require windows authentication
Once a user is authenticated, forms authentication maintains an authentication ticket in a cookie or in the URL
FormsAuthentication Public Properties:
DefaultURL: URL that user is redirected when no redirect URL is specified
LoginURL : URL to the login page
SlidingExpiration: Enable/Disable sliding expiration
FormsCookieName: Name of the cookie used to store the forms auth ticket
RedirectFromLoginPage: Sends user to requested URL after authentication
RedirectToLoginPage: Redirects to login URL
SignOut: Removes authentication ticket from the browser
Authentication: Forms Authentication: Web.Config Settings
Authentication: User Authentication: Basics
Authenticating Users: MCSD Book Chapter 8: Pages 413-470:
Three major ways to authenticate and authorize users within an ASP.net web application:
Windows Authentication
Forms Authentication
Passport Authentication
All three authentication methods use the classes found in System.Web.Security
Three major ways to authenticate and authorize users within an ASP.net web application:
Windows Authentication
Forms Authentication
Passport Authentication
All three authentication methods use the classes found in System.Web.Security
Web.config : Important Elements
web.config important elements:
?xml version="1.0"
configuration
appSettings
add key="keyName" value="valueHere"
appSettings
connectionStrings
system.web
compilation debug="false"
authentication mode="Forms|Windows|Passport|None"
forms loginUrl="Logon.aspx" name="FormsAuthCookie"
credentials passwordFormat=”Clear|SHA1|MD5”
forms
authorization
allow users|roles|verbs
deny users="?"
authorization
caching
cache
outputCache
outputCacheSettings
caching
httpCookies domain=”String”
httpOnlyCookies =”true|false”
requireSSL = “true|false"
sessionState
mode=”Off|InProc|StateServer|SQLServer|Custom”
timeout=”minutes”
cookieName=”identifier” cookieless=”true|false|AutoDetect|UseCookies|UseUri|UseDeviceProfile”
sessionState
httpHandlers
add verb=”*” path=”*.vsproj” type=”System.Web.HttpForbiddenHandler”
remove
clear
httpHandlers
urlMappings enabled=”true|false”
add
clear
remove
urlMappings
trace enabled="true|false"
localOnly="true|false"
pageOutput="true|false"
requestLimit="integer"
mostRecent="true|false"
writeToDiagnosticsTrace="true|false"
traceMode="SortByTime|SortByCategory"
customErrors
mode="On|Off|RemoteOnly" defaultRedirect="GenericErrorPage.htm">
error statusCode="403" redirect="err404.htm"
error statusCode="404" redirect="err403.htm"
customErrors>
globalization enableClientBasedCulture="true|false"
requestEncoding="any valid encoding string"
responseEncoding="any valid encoding string"
fileEncoding="any valid encoding string"
responseHeaderEncoding = "any valid encoding string"
resourceProviderFactoryType = string
enableBestFitResponseEncoding = "true|false"
culture="any valid culture string"
uiCulture="any valid culture string"
system.web
configuration
?xml version="1.0"
configuration
appSettings
add key="keyName" value="valueHere"
appSettings
connectionStrings
system.web
compilation debug="false"
authentication mode="Forms|Windows|Passport|None"
forms loginUrl="Logon.aspx" name="FormsAuthCookie"
credentials passwordFormat=”Clear|SHA1|MD5”
forms
authorization
allow users|roles|verbs
deny users="?"
authorization
caching
cache
outputCache
outputCacheSettings
caching
httpCookies domain=”String”
httpOnlyCookies =”true|false”
requireSSL = “true|false"
sessionState
mode=”Off|InProc|StateServer|SQLServer|Custom”
timeout=”minutes”
cookieName=”identifier” cookieless=”true|false|AutoDetect|UseCookies|UseUri|UseDeviceProfile”
sessionState
httpHandlers
add verb=”*” path=”*.vsproj” type=”System.Web.HttpForbiddenHandler”
remove
clear
httpHandlers
urlMappings enabled=”true|false”
add
clear
remove
urlMappings
trace enabled="true|false"
localOnly="true|false"
pageOutput="true|false"
requestLimit="integer"
mostRecent="true|false"
writeToDiagnosticsTrace="true|false"
traceMode="SortByTime|SortByCategory"
customErrors
mode="On|Off|RemoteOnly" defaultRedirect="GenericErrorPage.htm">
error statusCode="403" redirect="err404.htm"
error statusCode="404" redirect="err403.htm"
customErrors>
globalization enableClientBasedCulture="true|false"
requestEncoding="any valid encoding string"
responseEncoding="any valid encoding string"
fileEncoding="any valid encoding string"
responseHeaderEncoding = "any valid encoding string"
resourceProviderFactoryType = string
enableBestFitResponseEncoding = "true|false"
culture="any valid culture string"
uiCulture="any valid culture string"
system.web
configuration
Web.Config: Read Web.Config programatically Code Listing
using System.Configuration;
System.Web.Configuration.UrlMappingsSection urlMaps = (System.Web.Configuration.UrlMappingsSection)
System.Web.Configuration.WebConfigurationManager.GetSection(“system.web/urlMappings”);
Bool urlMappingsEnabled = urlMaps.IsEnabled;
System.Web.Configuration.UrlMappingsSection urlMaps = (System.Web.Configuration.UrlMappingsSection)
System.Web.Configuration.WebConfigurationManager.GetSection(“system.web/urlMappings”);
Bool urlMappingsEnabled = urlMaps.IsEnabled;
Configuration API: Access/Modify Configuration information
The following two configuration management tools that use Configuration API are included in .net framework 2.0
ASP.net MMC Snap-in: Used to simplify administrative tasks, provides an integrated view of local configuration data from all levels
Web Site Adminsitration Tool: Used to manage configuration settings for local and remote applications, including hosted site
Classes for getting a Configuration object:
ConfigurationManager: Used in Client Application
WebConfigurationManager: Used in Web Application
Reading/Writing Configuration information:
Use GetSection(path) / GetSectionGroup method to read configuration information
The process that reads the information must have appropriate permissions
Use Save method to save modified configuration files
ASP.net MMC Snap-in: Used to simplify administrative tasks, provides an integrated view of local configuration data from all levels
Web Site Adminsitration Tool: Used to manage configuration settings for local and remote applications, including hosted site
Classes for getting a Configuration object:
ConfigurationManager: Used in Client Application
WebConfigurationManager: Used in Web Application
Reading/Writing Configuration information:
Use GetSection(path) / GetSectionGroup method to read configuration information
The process that reads the information must have appropriate permissions
Use Save method to save modified configuration files
Unamanaged Code: Exception Handling
Exception Handling in Unmanaged Code:
Declare the unmanaged procedure with the SetLastError field set to True/true
Check the returned value from the umanaged procedure
If 0 is returned, get exception code using Marshal object’s GetLastWin32Error method
Declare the unmanaged procedure with the SetLastError field set to True/true
Check the returned value from the umanaged procedure
If 0 is returned, get exception code using Marshal object’s GetLastWin32Error method
Unamanaged Code: Marshalling
.net framework uses a unified type system that is different from the types defined in the win32 API
When an unmanaged procedure is called from a .net assembly, the CLR collects the parameters and converts their types in a process called Marshalling
When an unmanaged procedure is called from a .net assembly, the CLR collects the parameters and converts their types in a process called Marshalling
Unamanaged Code: Use of pInvoke, steps
Platform Invoke or pinvoke:
The process of executing native code from within a .net assembly is called platform invoke
Pinvoke is used to call the Win32 API directly
Also used to access procedures compiled to native code for performance reasons
Steps to use pinvoke:
Import the System.Runtime.InteropServices namespace
Declare the unmanaged procedure using the DLLImport attribute or the declare statement
Map the data types of the procedures parameters to the equivalent .net types
Call the unmanaged procedure and test its return value for success
If the procedure did not succeed, handle the exception using the Marshal object’s GetLastWin32Error method
The process of executing native code from within a .net assembly is called platform invoke
Pinvoke is used to call the Win32 API directly
Also used to access procedures compiled to native code for performance reasons
Steps to use pinvoke:
Import the System.Runtime.InteropServices namespace
Declare the unmanaged procedure using the DLLImport attribute or the declare statement
Map the data types of the procedures parameters to the equivalent .net types
Call the unmanaged procedure and test its return value for success
If the procedure did not succeed, handle the exception using the Marshal object’s GetLastWin32Error method
Managed Code: Unmanaged Code: Basics
Managed and Unmanaged Code:
ASP.net web applications run under the control of the CLR.
The CLR controls how the application’s assembly executes, allocates and recovers memory
Therefore, ASP.net applications are said to use managed code
In contrast, most other Win Executables use unmanaged code, because the executable itself determines how memory is used
Examples of unmanaged code are: MS Win32 API, legacy DLLs and Exe’s in using pre .net compilers
ASP.net web applications run under the control of the CLR.
The CLR controls how the application’s assembly executes, allocates and recovers memory
Therefore, ASP.net applications are said to use managed code
In contrast, most other Win Executables use unmanaged code, because the executable itself determines how memory is used
Examples of unmanaged code are: MS Win32 API, legacy DLLs and Exe’s in using pre .net compilers
Email, Mail, SMTP: Send email Code Listing
Code Listing: Sending Mail:
using System.Web.Mail;
MailMessage msgMail = new MailMessage();
msgMail.From = txtFrom.txt;
msgMail.To = txtTo.Text;
msgMail.Subject = txtSubject.Text;
msgMail.Body = txtMessage.Text;
SmtpMail.Send(msgMail);
using System.Web.Mail;
MailMessage msgMail = new MailMessage();
msgMail.From = txtFrom.txt;
msgMail.To = txtTo.Text;
msgMail.Subject = txtSubject.Text;
msgMail.Body = txtMessage.Text;
SmtpMail.Send(msgMail);
Browser: Check scripting, cookies support
Script for checking cookie, scripting support:
Cookies: if(Request.Browser.Cookies)
JavaScript Support: if(Request.Browser.JavaScript)
VBScript Support: if(Request.Browser.VBScript)
Cookies: if(Request.Browser.Cookies)
JavaScript Support: if(Request.Browser.JavaScript)
VBScript Support: if(Request.Browser.VBScript)
State Management : Cookies create/save GUID
Code Listing: Using GUID to save Globally Unique ID in a Cookie:
HttpCookie cookUserID = new Request.Cookies[“UserID”];
if(cookUserID == null)
cookUserID = new HttpCookie(“UserID”, System.Guid.NewGuid().ToString());
cookUserID.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookUserID);
HttpCookie cookUserID = new Request.Cookies[“UserID”];
if(cookUserID == null)
cookUserID = new HttpCookie(“UserID”, System.Guid.NewGuid().ToString());
cookUserID.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookUserID);
State Management : Cookies Code Listing Store User Info
Code Listing: Create, read, store information in a cookie
private void Page_Load(object sender, System.EventArgs e)
{
// Check if Cookies are accepted
if(Request.Browser.Cookie)
{
if(Request.Cookies[“LastVisit”]==null)
{
// Create the Cookie
HttpCookie cookLastVisit = new HttpCookie(“LastVisit”,DateTime.Now.ToString());
// Set the expiration
cookLastVisit.Expires = DateTime.Now.AddDays(1);
// Add to Cookies collection
Response.Cookies.Add(cookLastVisit);
// Display message
lblMessage.Text = “This is your first visit”;
}
else
{
// Get the Cookie
HttpCookie cookLastVisit = Request.Cookies[“LastVisit”];
lblMessage.Text = “You last visited this page on: ” + cookLastVisit.Value;
Response.Cookies[“LastVisit”].Value = DateTime.Now.ToString();
Response.Cookies[“LastVisit”].Expires = DateTime.Now.AddDays(1);
}
}
else { lblMessage.Text = “Your browser does not accept cookies”; }
}
private void Page_Load(object sender, System.EventArgs e)
{
// Check if Cookies are accepted
if(Request.Browser.Cookie)
{
if(Request.Cookies[“LastVisit”]==null)
{
// Create the Cookie
HttpCookie cookLastVisit = new HttpCookie(“LastVisit”,DateTime.Now.ToString());
// Set the expiration
cookLastVisit.Expires = DateTime.Now.AddDays(1);
// Add to Cookies collection
Response.Cookies.Add(cookLastVisit);
// Display message
lblMessage.Text = “This is your first visit”;
}
else
{
// Get the Cookie
HttpCookie cookLastVisit = Request.Cookies[“LastVisit”];
lblMessage.Text = “You last visited this page on: ” + cookLastVisit.Value;
Response.Cookies[“LastVisit”].Value = DateTime.Now.ToString();
Response.Cookies[“LastVisit”].Expires = DateTime.Now.AddDays(1);
}
}
else { lblMessage.Text = “Your browser does not accept cookies”; }
}
State Management : Cookies Steps to store information
Steps in storing User information on Cookies
Check whether client supports cookies, using the Browser object Cookies property
Check cookie already exists, using Request object Cookies collection
Create a new if not found, using the HttpCookie class
Set the cookie object’s value and expiration properties
Add the cookie object to the Response object’s Cookies collection
Check whether client supports cookies, using the Browser object Cookies property
Check cookie already exists, using Request object Cookies collection
Create a new if not found, using the HttpCookie class
Set the cookie object’s value and expiration properties
Add the cookie object to the Response object’s Cookies collection
State Management : Cookies Concepts, Limit: 4096 bytes, Expires
Approaches in Cookie based user identification:
Store all the user information on the cookie, used when information is generic
Store the identification key only, retrieve other information from server using the key
Cookie names are case sensitive and can save upto 4096 bytes of information
Set Expires to DateTime.MaxValue for a permanent cookie
To remove: Response.Cookies[“CookieName”].Expires = DateTime.Now;
Store all the user information on the cookie, used when information is generic
Store the identification key only, retrieve other information from server using the key
Cookie names are case sensitive and can save upto 4096 bytes of information
Set Expires to DateTime.MaxValue for a permanent cookie
To remove: Response.Cookies[“CookieName”].Expires = DateTime.Now;
Cache: Code Listing: Cache data from stored procedure
Code Listing: Cache Data from a Stored Procedure
public DataSet dsOrders = new DataSet();
private void btnGetOrders_Click(object sender, System.EventArgs e)
{
DataSet dsOrders = new DataSet();
// if not already cached, cache it...
if(Cache[drpCustlist.SelectedItem.Value]==null)
CacheOrders()
else
// get it from Cache
dsOrders = (DataSet)Cache[drpCustList.SelectedItem.Value];
grdOrders.DataBind();
}
void CacheOrders()
{
SqlConnection connNWind = new SqlConnection(NWindDSN);
SqlCommand cmdOrders = new SqlCommand(“CustOrdersOrders”,connNWind);
cmdOrders.Parameters.
Add(new SqlParameter(“@CustomerID”,drpCustList.SelectedItem.Value));
cmdOrders.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adptOrders = new SqlDataAdapter(cmdOrders);
try
{
adptOrders.Fill(dsOrders);
}
catch(Exception ex)
{
Response.Write(“An error occurred: “ + ex.Message);
}
Cache.Add(drpCustList.SelectedItem.Value, dsOrders, null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),CacheItemPriority, Default, null);
}
public DataSet dsOrders = new DataSet();
private void btnGetOrders_Click(object sender, System.EventArgs e)
{
DataSet dsOrders = new DataSet();
// if not already cached, cache it...
if(Cache[drpCustlist.SelectedItem.Value]==null)
CacheOrders()
else
// get it from Cache
dsOrders = (DataSet)Cache[drpCustList.SelectedItem.Value];
grdOrders.DataBind();
}
void CacheOrders()
{
SqlConnection connNWind = new SqlConnection(NWindDSN);
SqlCommand cmdOrders = new SqlCommand(“CustOrdersOrders”,connNWind);
cmdOrders.Parameters.
Add(new SqlParameter(“@CustomerID”,drpCustList.SelectedItem.Value));
cmdOrders.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adptOrders = new SqlDataAdapter(cmdOrders);
try
{
adptOrders.Fill(dsOrders);
}
catch(Exception ex)
{
Response.Write(“An error occurred: “ + ex.Message);
}
Cache.Add(drpCustList.SelectedItem.Value, dsOrders, null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),CacheItemPriority, Default, null);
}
Cache: Cache Performance Counters
Cache Performance Counters:
ASP.net provides three categories of cache performance counters:
Cache Total Counters
Cache API Counters
Output Cache Counters
Performance counters available in each of the categories:
Entries
Hits
Misses
Hit Ratio
Turnover Ratio
ASP.net provides three categories of cache performance counters:
Cache Total Counters
Cache API Counters
Output Cache Counters
Performance counters available in each of the categories:
Entries
Hits
Misses
Hit Ratio
Turnover Ratio
Cache: Cache Application Data
using System.Web.Caching
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Cache[“NewItem”] = “Some string data”;
Cache.Add(“New Item”,”Some data”,null,Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),CacheItemPriority.Default, null);
Cache.Insert(“NewItem”,”Some string data”);
}
}
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Cache[“NewItem”] = “Some string data”;
Cache.Add(“New Item”,”Some data”,null,Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),CacheItemPriority.Default, null);
Cache.Insert(“NewItem”,”Some string data”);
}
}
Cache: Cache Location
Cache Location: Where items are cached
OutputCache directive’s location atribute and the HttpCachePolicy object’s SetCacheability property determine the location
By default, ASP.net caches responses at any available location that accepts cache items
Location values can be: Any, Client, Server, None, DownStream, ServerAndClient
OutputCache directive’s location atribute and the HttpCachePolicy object’s SetCacheability property determine the location
By default, ASP.net caches responses at any available location that accepts cache items
Location values can be: Any, Client, Server, None, DownStream, ServerAndClient
Cache: Response.Cache Code Listing
Code Listing: Response.Cache
private void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(5));
Response.Cache.VaryByParams[“None”] = true;
Response.Cache.SetCacheability(HttpCacheability.Public);
}
This is same as:
<%@ OutputCache Duration=”5” VaryByParams=”None” Location=”Any” %>
private void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(5));
Response.Cache.VaryByParams[“None”] = true;
Response.Cache.SetCacheability(HttpCacheability.Public);
}
This is same as:
<%@ OutputCache Duration=”5” VaryByParams=”None” Location=”Any” %>
Cache: HttpCachePolicy Response object
Response object Cache returns a HttpCachePolicy object
HttpCachePolicy object is similar to OutputCache
Following is a list of attributes of HttpCachePolicy
HttpCachePolicy members:
VaryByParams
VaryByHeaders
SetVaryByCustom
SetExpires
SetSlidingExpiration
SetCacheability Location
SetAllowResponseInBrowserHistory
AddValidationCallback
SetRevalidation
SetValidUntilExpires
HttpCachePolicy object is similar to OutputCache
Following is a list of attributes of HttpCachePolicy
HttpCachePolicy members:
VaryByParams
VaryByHeaders
SetVaryByCustom
SetExpires
SetSlidingExpiration
SetCacheability Location
SetAllowResponseInBrowserHistory
AddValidationCallback
SetRevalidation
SetValidUntilExpires
Cache: VaryByCustom Modify Global.asax
VaryByCustom:
VaryByCustom allows caching different responses based on a custom string
To use VaryByCustom, override GetVaryByCustomString method in Global.asax
VaryByCustom:Global.asax
Following is a part of application’s global.asax file:
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if(arg == “appName”)
return “appname=” + context.Request.Browser.Browser;
else
return “”;
}
VaryByCustom allows caching different responses based on a custom string
To use VaryByCustom, override GetVaryByCustomString method in Global.asax
VaryByCustom:Global.asax
Following is a part of application’s global.asax file:
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if(arg == “appName”)
return “appname=” + context.Request.Browser.Browser;
else
return “”;
}
Cache: VaryByHeader
%@
OutputCache Duration=”120” VaryByParam=”None” VaryByHeader=”Accept-Language” %
This directive causes a different response to be cached based on accept-language header
Accept-Language is an attribute of Request.
Request.Headers.GetValues(“Accept-Language”)
OutputCache Duration=”120” VaryByParam=”None” VaryByHeader=”Accept-Language” %
This directive causes a different response to be cached based on accept-language header
Accept-Language is an attribute of Request.
Request.Headers.GetValues(“Accept-Language”)
Cache: Caching multiple responses from one page
Cache multiple responses from a single web form: Using VaryByParam
OutputCache has two required directives, Duration and VaryByParam
VaryByParam lets caching multiple responses from single web form based on varying HTTP POST or query string parameters
Setting VaryByParam as none, causes only one response to be cached, regardless of parameters
OutputCache has two required directives, Duration and VaryByParam
VaryByParam lets caching multiple responses from single web form based on varying HTTP POST or query string parameters
Setting VaryByParam as none, causes only one response to be cached, regardless of parameters
Saturday, July 21, 2007
Cache: Basics OutputCache Directive
Use the OutputCache page directive to cache a web form in the server’s memory
This directive’s Duration attribute controls how long the page is cached
@ OutputCache Duration=”60” VaryByParam=”None” %
The first time any user requests this web form, the server loads the response in memory, and retains the response for 60 seconds
Any subsequent requests during that time recieve the cached response
On expiry, a new response is generated for next 60 seconds
This directive’s Duration attribute controls how long the page is cached
@ OutputCache Duration=”60” VaryByParam=”None” %
The first time any user requests this web form, the server loads the response in memory, and retains the response for 60 seconds
Any subsequent requests during that time recieve the cached response
On expiry, a new response is generated for next 60 seconds
Controls Collection: Basics and Code Listing
Locate controls on a web page using Controls Collection:
Loop through the Controls collection of the container control
The collection is of type ControlColletion, and return type is Control
Code Listing: Controls Collection
public void Button1_Click(object sender, System.EventArgs e)
{
string txtVal = “”;
foreach(Control c in Page.Controls)
{
foreach(Control childc in c.controls)
{
If(childc is TextBox)
{
txtVal += ((TextBox)childc).Text + “,”;
}
}
}
if(txtVal != “”)
{
Label1.Text = txtVal;
}
}
Loop through the Controls collection of the container control
The collection is of type ControlColletion, and return type is Control
Code Listing: Controls Collection
public void Button1_Click(object sender, System.EventArgs e)
{
string txtVal = “”;
foreach(Control c in Page.Controls)
{
foreach(Control childc in c.controls)
{
If(childc is TextBox)
{
txtVal += ((TextBox)childc).Text + “,”;
}
}
}
if(txtVal != “”)
{
Label1.Text = txtVal;
}
}
.net Framework : MSIL Basics and App Compilation
Application compilation and execution:
.net application code is compiled into Microsoft Intermediate Languge (MSIL) and stored in a file called an assembly
At run time, the assembly is compiled into its final state by the CLR
MSIL: Microsoft Intermediate Language
• When compiling the managed code, the compiler translates the source code into MSIL
• MSIL is a CPU-independent set of instructions that can be efficiently converted into native code
• MSIL includes instructions for loading, sorting, initializing and calling mehods on objects
• Before code can be run, MSIL must be converted to CPU-specific code, usually by a JIT or Just In Time compiler
• CLR supports one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT compiled and run on any supported architecture
• When a Compiler produces MSIL, it also produces metadata
• Metadata describes the types in the code, their definition, signatures, references, data used at runtime
• MSIL and metadata are contained in a portable executable file
• The runtime located and extracts metadata from the file during the runtime
.net application code is compiled into Microsoft Intermediate Languge (MSIL) and stored in a file called an assembly
At run time, the assembly is compiled into its final state by the CLR
MSIL: Microsoft Intermediate Language
• When compiling the managed code, the compiler translates the source code into MSIL
• MSIL is a CPU-independent set of instructions that can be efficiently converted into native code
• MSIL includes instructions for loading, sorting, initializing and calling mehods on objects
• Before code can be run, MSIL must be converted to CPU-specific code, usually by a JIT or Just In Time compiler
• CLR supports one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT compiled and run on any supported architecture
• When a Compiler produces MSIL, it also produces metadata
• Metadata describes the types in the code, their definition, signatures, references, data used at runtime
• MSIL and metadata are contained in a portable executable file
• The runtime located and extracts metadata from the file during the runtime
.net Framework : Common Type System CTS
Common Type System CTS
Defines how types are declared, used and managed in the runtime
Important part in runtime’s support for the cross-language integration
Provides an object oriented model that supports the complete implementation of many
CTS supports two general categories of types:
a. Value types
b. Reference types
Value types directly contain their data
Value types can be built-in, user defined or enumerations
Value types are allocated on the stack
Reference types store a reference to the value’s memory address
Reference types are allocated on the heap
Reference types can be self-describing types,pointer or interface types
Value types have their own copy of data, hence a change in one doesnt affect others
Multiple reference types can refer to single object
Defines how types are declared, used and managed in the runtime
Important part in runtime’s support for the cross-language integration
Provides an object oriented model that supports the complete implementation of many
CTS supports two general categories of types:
a. Value types
b. Reference types
Value types directly contain their data
Value types can be built-in, user defined or enumerations
Value types are allocated on the stack
Reference types store a reference to the value’s memory address
Reference types are allocated on the heap
Reference types can be self-describing types,pointer or interface types
Value types have their own copy of data, hence a change in one doesnt affect others
Multiple reference types can refer to single object
.net Framework : Application Domain
Application Domain:
App domain prevents fault in one application affecting another application
Individual applications can be stopped without stopping the entire process
App domain allows enables user to unload the code running in a single application
Individual assemblies/types can not be unloaded, only a complete domain can be unloaded
CLR maintains isolation by preventing code access from one application to another
This isolation is maintained by preventing direct calls between objects in different application domains
Objects that are passed between domains are either copied or accessed by proxy
When object is accessed through a proxy, such a call is a remote call
App domain provides configuration settings such as app version policies, remote assembly location
App domain also manages permissions granted to the code which runs inside it
App domain prevents fault in one application affecting another application
Individual applications can be stopped without stopping the entire process
App domain allows enables user to unload the code running in a single application
Individual assemblies/types can not be unloaded, only a complete domain can be unloaded
CLR maintains isolation by preventing code access from one application to another
This isolation is maintained by preventing direct calls between objects in different application domains
Objects that are passed between domains are either copied or accessed by proxy
When object is accessed through a proxy, such a call is a remote call
App domain provides configuration settings such as app version policies, remote assembly location
App domain also manages permissions granted to the code which runs inside it
.net Framework : Class Library
Class Library:
Comprehensive object oriented collection of reuseable types
To facilitate interoperatibility between the languages, the .net framework types are CLS compliant
Comprehensive object oriented collection of reuseable types
To facilitate interoperatibility between the languages, the .net framework types are CLS compliant
.net Framework : CLR
The CLR is the foundation of the .net framework. Runtime does the following:
Manages the code at runtime
Provides Memory Management
Thread Management
Remoting
Enforces strict type safety
Code that targets the runtime is known as managed code
Manages the code at runtime
Provides Memory Management
Thread Management
Remoting
Enforces strict type safety
Code that targets the runtime is known as managed code
Web Custom Server Control: Interfaces used
Interfaces implemented in control development:
System.Web.UI.NamingContainer
System.Web.UI.IPostBackDataHandler
System.Web.UI.IPostBackEventHandler
System.Web.UI.NamingContainer
System.Web.UI.IPostBackDataHandler
System.Web.UI.IPostBackEventHandler
Web Custom Server Control: Control Class
Control Class
Control class defines the methods, properties common to all server controls
That includes method/events that govern control execution lifecycle
Major properties such as: ID, UniqueID, Parent, ViewState
Control does not have any UI specific features
To author UI-less controls, derive from Control class
WebControl Class:
Derives from Control and provides additional methods/properties for UI
Properties include ForeColor, BackColor, Font, BorderStyle
Control class defines the methods, properties common to all server controls
That includes method/events that govern control execution lifecycle
Major properties such as: ID, UniqueID, Parent, ViewState
Control does not have any UI specific features
To author UI-less controls, derive from Control class
WebControl Class:
Derives from Control and provides additional methods/properties for UI
Properties include ForeColor, BackColor, Font, BorderStyle
Web Custom Server Control: Key Concepts
An asp.net control class derives from System.Web.UI.Control
Override Render/RenderContents method to provide control output
The two base classes for controls are:
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
To use the custom control on a webpage, it must be registered, either on the webpage or in web.config
Registering on page:
%@Register TagPrefix=”aspSample” NameSpace=”nameSpace.name”%
Registering a control in web.config
system.web pages controls
add tagPrefix=”aspSample” namespace=”nameSpace.name”add
controls pages system.web
To use a custom control on a webpage: Create a bin folder in site’s root
Copy the control assembly (dll) in bin folder
Override Render/RenderContents method to provide control output
The two base classes for controls are:
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
To use the custom control on a webpage, it must be registered, either on the webpage or in web.config
Registering on page:
%@Register TagPrefix=”aspSample” NameSpace=”nameSpace.name”%
Registering a control in web.config
system.web pages controls
add tagPrefix=”aspSample” namespace=”nameSpace.name”add
controls pages system.web
To use a custom control on a webpage: Create a bin folder in site’s root
Copy the control assembly (dll) in bin folder
Web Custom Server Control: Theory
Web Custom Controls are compiled components that run on server
They can include all design time features of standard asp.net server controls
Support visual studio design features such as properties window, toolbox etc.
They can include all design time features of standard asp.net server controls
Support visual studio design features such as properties window, toolbox etc.
Web User Control: Basics Register Directive
A web user control is similar to a complete web forms page
It has GUI as well as a code-behind
Extension of a user control is ascx
User control doesnt have html,body and form tags, hosting page should provide these
To use a web user control, drag and drop the ascx file onto a webform in design mode
Dropping user control on the page causes following:
a. A new @Register directive gets added:
<@ Register src = “ControlName.ascx” TagName=”ControlName” TagPrefix=”uc1”>
b. Element for the user control:
uc1:ControlName id=”ControlName1” Runat=”Server”
It has GUI as well as a code-behind
Extension of a user control is ascx
User control doesnt have html,body and form tags, hosting page should provide these
To use a web user control, drag and drop the ascx file onto a webform in design mode
Dropping user control on the page causes following:
a. A new @Register directive gets added:
<@ Register src = “ControlName.ascx” TagName=”ControlName” TagPrefix=”uc1”>
b. Element for the user control:
uc1:ControlName id=”ControlName1” Runat=”Server”
Assembly : Satellite Assembly Loading Resource Files
using.System.Resources;
protected ResourceManager gStrings = new
ResourceManager(“projName.resourcefilename”,typeof(Satellite).Assembly);
protected ResourceManager gStrings = new
ResourceManager(“projName.resourcefilename”,typeof(Satellite).Assembly);
Assembly : Satellite Assembly, Creating Resource File
Project -> Add new item -> Assembly resource file -> Name the file
A file with extension resx gets created
A tabular structure appears with following columns:
name, value, comment, type, mimetype
Naming: Recommended way is: formname.elementname like webform1.btnOk
A file with extension resx gets created
A tabular structure appears with following columns:
name, value, comment, type, mimetype
Naming: Recommended way is: formname.elementname like webform1.btnOk
Assembly : Satellite Assembly, Resource File Type
Fallback: strings.resx – Executable assembly
Language Specific: file.langcode.resx – Exists within subfolder of bin
Culture Specific: file.langcode-regioncode.resx – bin\es-MX\
Language Specific: file.langcode.resx – Exists within subfolder of bin
Culture Specific: file.langcode-regioncode.resx – bin\es-MX\
Assembly : Using Satellite Assembly
Set the id and runat attributes for all UI elements including html tags like p etc. like: h1 id=”head1” runat=”server” Heading h1
Create a fallback resource file containing default strings to display
Create a resource file for each language that contains translated strings
Name resource file like: strings.en.resx
Create resource file for each specific culture: strings.ex-MX.resx
Write code to load the resources for the web form using the resource manager class
Create a fallback resource file containing default strings to display
Create a resource file for each language that contains translated strings
Name resource file like: strings.en.resx
Create resource file for each specific culture: strings.ex-MX.resx
Write code to load the resources for the web form using the resource manager class
Assembly : Satellite Assembly
Satellite Assemblies: MCSD Book Pg 757
Satellite assemblies are assembly files (dll) that contain localized resources for an application
Each satellite assembly file contains the resources for one culture
An application may have many satellite assemblies
Web applications project use satellite assemblies to store the translated strings, graphics and other culture specific resources
To create these assemblies, Resource Manager is used
At run time, the web application loads the translated strings into the web form based on current thread’s CurrentUICulture property
Satellite assemblies are assembly files (dll) that contain localized resources for an application
Each satellite assembly file contains the resources for one culture
An application may have many satellite assemblies
Web applications project use satellite assemblies to store the translated strings, graphics and other culture specific resources
To create these assemblies, Resource Manager is used
At run time, the web application loads the translated strings into the web form based on current thread’s CurrentUICulture property
Assembly : Creating a Shared Assembly
Create a new “Class Library” project in Visual Studio
In Class1.cs add a public method that returns int or string
Compile the code to get a dll file in debug/bin folder
Start sn tool, generate key as: sn –k C:\mykey.snk
In Visual Studio, edit AssemblyInfo.cs file by adding reference to key file
Add reference to the key by adding [assembly: AssemblyKeyFile(“C:\mykey.snk”)]
Recompile the code and dll will be signed using the key provided
Install assembly to GAC using gacutil –I “C:\path\to\dll\dllfile.dll”
Test the assembly bu adding its dll’s reference in a project
Add it in using directive using namespace.className;
In Class1.cs add a public method that returns int or string
Compile the code to get a dll file in debug/bin folder
Start sn tool, generate key as: sn –k C:\mykey.snk
In Visual Studio, edit AssemblyInfo.cs file by adding reference to key file
Add reference to the key by adding [assembly: AssemblyKeyFile(“C:\mykey.snk”)]
Recompile the code and dll will be signed using the key provided
Install assembly to GAC using gacutil –I “C:\path\to\dll\dllfile.dll”
Test the assembly bu adding its dll’s reference in a project
Add it in using directive using namespace.className;
Assembly : Private Shared
Assembly which is used only by a single application is called a private assembly
Private assembly must reside in the same folder in which the client app is installed
Assemblies that provide generic functionality reside in Global Assembly Cache
GAC is a special disk folder, located in WinNT\Assembly
Private assembly must reside in the same folder in which the client app is installed
Assemblies that provide generic functionality reside in Global Assembly Cache
GAC is a special disk folder, located in WinNT\Assembly
Assembly : Naming
Assembly name consists of four parts:
a. Short name – Name of PE file without the extension
b. Culture – As a convention library/process assemblies should be culture neutral
c. Version –major.minor.build.revision Used only if assembly has a strong name
d. Public key token
a. Short name – Name of PE file without the extension
b. Culture – As a convention library/process assemblies should be culture neutral
c. Version –major.minor.build.revision Used only if assembly has a strong name
d. Public key token
Assembly : Manifest
Assembly Manifest:
Data structure which stores information about an assembly
This information is stored within the assembly file (DLL/Exe) itself
This information includes version information, list of constituent files etc.
Data structure which stores information about an assembly
This information is stored within the assembly file (DLL/Exe) itself
This information includes version information, list of constituent files etc.
Assembly : Basics, Types, Assembly Manifest
Partially compiled code library for use in deployment, versioning and security
An assembly is a portable executable file (PE)
Types of Assemblies:
a. Process Assembly - Exe
b. Library Assembly – DLL
A library may have DLL or Exe as extension
Assembly also contains metadata that is known as assembly manifest
Code in an assembly is compiled into MSIL which is then compiled into machine langauge by CLR
An assembly may contain multiple files
Code file in an assembly are called modules
Assembly may contain code modules/files written in different languages
Visual Studio allows assemblies that can have modules written in one language
An assembly is a portable executable file (PE)
Types of Assemblies:
a. Process Assembly - Exe
b. Library Assembly – DLL
A library may have DLL or Exe as extension
Assembly also contains metadata that is known as assembly manifest
Code in an assembly is compiled into MSIL which is then compiled into machine langauge by CLR
An assembly may contain multiple files
Code file in an assembly are called modules
Assembly may contain code modules/files written in different languages
Visual Studio allows assemblies that can have modules written in one language
Globalization Culture : Adjust to current culture at run time
Adjusting to Current Culture at Run Time: Thread.CurrentCulture
By default, web applications run on the server using a neutral culture
When a culture attribute is set in web.config, ASP.net assigns that culture to all the the threads running for that web application
Threads are basic unit to which the server allocates processor time
ASP.net maintains multiple threads for a web application within the aspnet_wp.exe worker process
Culture can be set at runtime using the Thread class’ CurrentCulture property
Code Listing: Culture change using Thread
using System.Globalization;
using System.Threading;
private void Page_Load(object sender, System.EventArgs e)
{
sLang = Request.UserLanguages[0];
Thread.CurrentThread.CurrentCulture = new CultureInfo(sLang);
}
By default, web applications run on the server using a neutral culture
When a culture attribute is set in web.config, ASP.net assigns that culture to all the the threads running for that web application
Threads are basic unit to which the server allocates processor time
ASP.net maintains multiple threads for a web application within the aspnet_wp.exe worker process
Culture can be set at runtime using the Thread class’ CurrentCulture property
Code Listing: Culture change using Thread
using System.Globalization;
using System.Threading;
private void Page_Load(object sender, System.EventArgs e)
{
sLang = Request.UserLanguages[0];
Thread.CurrentThread.CurrentCulture = new CultureInfo(sLang);
}
Globalization Culture : Get user culture at run time
Code Listing: Culture
Getting user culture at runtime:
private void Page_Load(object sender, EventArgs e)
{
if(!isPostBack)
{
string sLang = Request.UserLanguages[0];
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + “: “ + CurrentCulture.Name;
}
}
Getting user culture at runtime:
private void Page_Load(object sender, EventArgs e)
{
if(!isPostBack)
{
string sLang = Request.UserLanguages[0];
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + “: “ + CurrentCulture.Name;
}
}
Globalization Culture UICulture Basics Web.Config Settings
For an ASP.net page, two culture properties can be set: Culture and UICulture
Culture refers to information such as date, number, currency etc.
UICulture refers to resources that are to be loaded from the page
Found in: System.Globalization
Globalization settings in the web.config:
globalization uiculture = “es”
culture = “es-MX”
requestEncoding = “utf-8”
responseEncoding=”utf-8”
Globalization for individual pages:
%@ Page UICulture = “es” Culture = “es-MX” %
Globalization for a page from browser settings:
%@ Page UICulture = auto Culture = auto %
Culture refers to information such as date, number, currency etc.
UICulture refers to resources that are to be loaded from the page
Found in: System.Globalization
Globalization settings in the web.config:
globalization uiculture = “es”
culture = “es-MX”
requestEncoding = “utf-8”
responseEncoding=”utf-8”
Globalization for individual pages:
%@ Page UICulture = “es” Culture = “es-MX” %
Globalization for a page from browser settings:
%@ Page UICulture = auto Culture = auto %
State Management : Profile Properties enable/disable in web.config
Enable the profile feature in web.config file
Configure the profile feature by defining a list of properties whose values need to be maintained
Web.config section:
profile
properties
group name = “address”
add name = “street”
add name = “city”
group
add name=”PostalCode”
type = “String|Int32|DateTime|StringCollection...”
serializeAs = “String|binary|xml...”
allowAnonymous = “true|false”
defaultValue= “”
readOnly = “true|false”
provider = “”
customProviderData = “”/>
properties
profile
Store data to Profile from server control: Profile.PostalCode = txtPostalCode.Text;
Read data from Profile: weatherInfo = GetWeatherInfo( Profile.PostalCode );
Configure the profile feature by defining a list of properties whose values need to be maintained
Web.config section:
profile
properties
group name = “address”
add name = “street”
add name = “city”
group
add name=”PostalCode”
type = “String|Int32|DateTime|StringCollection...”
serializeAs = “String|binary|xml...”
allowAnonymous = “true|false”
defaultValue= “”
readOnly = “true|false”
provider = “”
customProviderData = “”/>
properties
profile
Store data to Profile from server control: Profile.PostalCode = txtPostalCode.Text;
Read data from Profile: weatherInfo = GetWeatherInfo( Profile.PostalCode );
State Management : Session State Modes : SQLServer in Web.Config
configuration
system.web
sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;"
system.web
configuration
system.web
sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;"
system.web
configuration
State Management : Session State Web.Config ReadOnly
Specify ReadOnly in web.config
configuration
system.web
pages enableSessionState="ReadOnly"
system.web
configuration
configuration
system.web
pages enableSessionState="ReadOnly"
system.web
configuration
State Management : Session State Read Write Values
Add Object to the Session State:
HttpSessionState.Session.Add(name, Value)
Assign a value to a Session object
HttpSessionState.Session["UserName”] = “Sg”;
Reading from a session object:
string userName = HttpSessionState.Session["UserName”].ToString();
Remove an object from session:
HttpSessionState.Remove(objName);
Clear the session
Session.Abandon() or Session.Clear()
Session.Abandon : Calls Session_End will be fired
Session.Clear : Just clears the session data without killing it
Enable/Disable Session state at Page Level:
Page Level : <%@ Page EnableSessionState=”False” %>
Page Level ReadOnly : <%@ Page EnableSessionState=”ReadOnly” %>
HttpSessionState.Session.Add(name, Value)
Assign a value to a Session object
HttpSessionState.Session["UserName”] = “Sg”;
Reading from a session object:
string userName = HttpSessionState.Session["UserName”].ToString();
Remove an object from session:
HttpSessionState.Remove(objName);
Clear the session
Session.Abandon() or Session.Clear()
Session.Abandon : Calls Session_End will be fired
Session.Clear : Just clears the session data without killing it
Enable/Disable Session state at Page Level:
Page Level : <%@ Page EnableSessionState=”False” %>
Page Level ReadOnly : <%@ Page EnableSessionState=”ReadOnly” %>
State Management : Session State Web.Config settings
Specifying State Mode in Web.Config
configuration
system.web
sessionState mode=”StateServer”
stateConnectionString=”tcpip=SampleStateServer:42424”
cookieless=”false” timeout=”20”
system.web
configuration
configuration
system.web
sessionState mode=”StateServer”
stateConnectionString=”tcpip=SampleStateServer:42424”
cookieless=”false” timeout=”20”
system.web
configuration
State Management : Session State Modes : InProc StateServer SQLServer
InProc : Stores session state on web server, this is default mode
Stores the data in ASP.net worker process
Session state is stored in the application domain memory space
State lost if aspnet_wp.exe recycles or application domain restarts
StateServer : Stores in a separate process called ASP.net state service.
Preserves information in event of web application restart
Service is independent of IIS and can run on a separate server
State service is like any other NT service with own process and memory
SQLServer : Stores in SQL Server database
Custom: Enables to use a custom data storage
Off : Session state is disabled
Stores the data in ASP.net worker process
Session state is stored in the application domain memory space
State lost if aspnet_wp.exe recycles or application domain restarts
StateServer : Stores in a separate process called ASP.net state service.
Preserves information in event of web application restart
Service is independent of IIS and can run on a separate server
State service is like any other NT service with own process and memory
SQLServer : Stores in SQL Server database
Custom: Enables to use a custom data storage
Off : Session state is disabled
State Management : Session State
ASP.net session state identifies requests received from the same browser during a limited period of time as a session
Provides the ability to persist variable values for the duration of that session
Session variables can be accessed/modified using the session property
Set a session value: Session[“FirstName”] = FirstName.Text;
Provides the ability to persist variable values for the duration of that session
Session variables can be accessed/modified using the session property
Set a session value: Session[“FirstName”] = FirstName.Text;
State Management : Application State Code Listing
Code Listing: Application State
This code goes into Global.asaxWrite a value to Application State
Application["Message"] = "Welcome to the Contoso site.";
Application["PageRequestCount"] = 0;
Read a value from the Application stateApplication.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1; Application.UnLock();
This code goes into Global.asaxWrite a value to Application State
Application["Message"] = "Welcome to the Contoso site.";
Application["PageRequestCount"] = 0;
Read a value from the Application stateApplication.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1; Application.UnLock();
State Management : Application State Basics
Application state is a data repository available to all classes in an asp.net application Stored in memory on the server
Applies to all users and all sessions
Useful to store often used data that is not user specific
Stored as an instance of HttpApplicationState
HttpApplicationState class can be accessed anytime during the application lifetime
New instance of this class is created everytime user accesses a URL resource
Application state is free-threaded, synchronization support is thus necessary
Applies to all users and all sessions
Useful to store often used data that is not user specific
Stored as an instance of HttpApplicationState
HttpApplicationState class can be accessed anytime during the application lifetime
New instance of this class is created everytime user accesses a URL resource
Application state is free-threaded, synchronization support is thus necessary
State Management : Viewstate Code Listing
Read data from Viewstate (Code listing)
arrayList = new ArrayList();
arrayList = (ArrayList)ViewState["arrayListInViewState"];
this.GridView1.DataSource = arrayList;
this.GridView1.DataBind();
To check if a value exists in Viewstate: if (ViewState["color"] == null)
arrayList = new ArrayList();
arrayList = (ArrayList)ViewState["arrayListInViewState"];
this.GridView1.DataSource = arrayList;
this.GridView1.DataBind();
To check if a value exists in Viewstate: if (ViewState["color"] == null)
State Management : Viewstate Basics
Viewstate
In web forms, viewstate is sent by the server as a hidden variable in a form, as part of every response to the client
Stores values per control by key name, like a hashtable
Serializes and Deserializes saved data into a hidden form field on the client
Returned to the server by the client as a part of a postback as a hidden client
Viewstate data is not encrypted, only Base64 encoded
To make viewstate more secure use page attribute called EnableViewStateMac
Viewstate can be written only after init event is fired for a page request
Data can be read from anytime from Viewstate but not after page enters rendering mode
To turn-off viewstate: <%@Page EnableViewState = “false” %>
Datatypes supported by Viewstate
Strings
Integer
Boolean Values
Array Objects
ArrayList Objects
Hash Tables
Custom types
In web forms, viewstate is sent by the server as a hidden variable in a form, as part of every response to the client
Stores values per control by key name, like a hashtable
Serializes and Deserializes saved data into a hidden form field on the client
Returned to the server by the client as a part of a postback as a hidden client
Viewstate data is not encrypted, only Base64 encoded
To make viewstate more secure use page attribute called EnableViewStateMac
Viewstate can be written only after init event is fired for a page request
Data can be read from anytime from Viewstate but not after page enters rendering mode
To turn-off viewstate: <%@Page EnableViewState = “false” %>
Datatypes supported by Viewstate
Strings
Integer
Boolean Values
Array Objects
ArrayList Objects
Hash Tables
Custom types
State Management : Query String Code Listing
Code Listing: QueryString
Build QueryString:
string url = "QueryStringRecipient.aspx?";
url += "Item=" + lstItems.SelectedItem.Text + "&";
url += "Mode=" + chkDetails.Checked.ToString();
Response.Redirect(url);
Read QueryString:
lblInfo.Text = "Item: " + Request.QueryString["Item"];
lblInfo.Text += "
Show Full Record: ";
lblInfo.Text += Request.QueryString["Mode"];
Build QueryString:
string url = "QueryStringRecipient.aspx?";
url += "Item=" + lstItems.SelectedItem.Text + "&";
url += "Mode=" + chkDetails.Checked.ToString();
Response.Redirect(url);
Read QueryString:
lblInfo.Text = "Item: " + Request.QueryString["Item"];
lblInfo.Text += "
Show Full Record: ";
lblInfo.Text += Request.QueryString["Mode"];
State Management : Cookies Code Listing
Code Listing: Cookie
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("
The cookie has been written.");
State Management Techniques
State management provides means of preserving data on both per-page and application wide basis
Techniques of State Management
Client side state management
Viewstate
Control State
Hidden Fields
Cookies
Query Strings
Server side state management
Application State
Session State
Profile properties
Techniques of State Management
Client side state management
Viewstate
Control State
Hidden Fields
Cookies
Query Strings
Server side state management
Application State
Session State
Profile properties
Validation Controls : Custom Validator Code Listing
Code Listing: Custom Validator
%@ Page Language="C#" %
script runat="server"
void valComments_ServerValidateObject source, ServerValidateEventArgs args)
{
if (args.Value.Length > 10)
args.IsValid = false;
else
args.IsValid = true;
}
/script
head id="Head1" runat="server"
title Show CustomValidator /title
head body
form id="form1" runat="server"
div
asp:label id="lblComments" text="Comments:" associatedcontrolid="txtComments" runat="server"
asp: TextBox id="txtComments" TextMode="MultiLine"
Columns="30" Rows="5" Runat="server"
asp:CustomValidator id="valComments" ControlToValidate="txtComments"
Text="(Comments must be less than 10 characters)" OnServerValidate="valComments_ServerValidate" Runat="server"
asp:button id="btnSubmit" text="Submit" runat="server"
/div
/form
/body
/html
%@ Page Language="C#" %
script runat="server"
void valComments_ServerValidateObject source, ServerValidateEventArgs args)
{
if (args.Value.Length > 10)
args.IsValid = false;
else
args.IsValid = true;
}
/script
head id="Head1" runat="server"
title Show CustomValidator /title
head body
form id="form1" runat="server"
div
asp:label id="lblComments" text="Comments:" associatedcontrolid="txtComments" runat="server"
asp: TextBox id="txtComments" TextMode="MultiLine"
Columns="30" Rows="5" Runat="server"
asp:CustomValidator id="valComments" ControlToValidate="txtComments"
Text="(Comments must be less than 10 characters)" OnServerValidate="valComments_ServerValidate" Runat="server"
asp:button id="btnSubmit" text="Submit" runat="server"
/div
/form
/body
/html
Validation Controls Basics, Common Properties and Types
Validation Controls Basics:
All validation controls inherit from the base class BaseValidator
Validation Controls always perform validation on the server
Always use Page.IsValid, client side validation fails if scripting is turned off
Properties common to all validators are:
ControlToValidate
ErrorMessage
IsValid
Validate
Display
None: Dont display error message
Static: Reserve space for the error message
Dynamic: Auto add space when validation fails
Types of Validation Controls:
RequiredFieldValidation
CompareValidator
RangeValidator
RegularExpressionValidator
CustomValidator
All validation controls inherit from the base class BaseValidator
Validation Controls always perform validation on the server
Always use Page.IsValid, client side validation fails if scripting is turned off
Properties common to all validators are:
ControlToValidate
ErrorMessage
IsValid
Validate
Display
None: Dont display error message
Static: Reserve space for the error message
Dynamic: Auto add space when validation fails
Types of Validation Controls:
RequiredFieldValidation
CompareValidator
RangeValidator
RegularExpressionValidator
CustomValidator
Data Controls DataGrid DataList Repeater
DataGrid
Display text and controls in colums and rows
DataGrid Controls have built-in formatting, sorting and paging capabilities
Namespace: System.Web.UI.WebControls
Each row in the DataGrid control represents a record in the data source
AutoGenerateColumns is by default true
DataGrid has following column types:
· BoundColumn: Default column type, displays item in the field as text
· ButtonColumn: Command button for each column
· EditCommandColumn: Column with editing commmand
· HyperLinkColumn: Displays contents as hyperlink
· Template Column: Allows template and custom controls
DataList:
Display rows of text and controls using a template to control appearence
DataList Controls have built-in formatting and selection capabilities
Repeater:
Display rows of other controls using a template to control appearence
Has no built-in capabilities found in the DataGrid and DataList controls
Display text and controls in colums and rows
DataGrid Controls have built-in formatting, sorting and paging capabilities
Namespace: System.Web.UI.WebControls
Each row in the DataGrid control represents a record in the data source
AutoGenerateColumns is by default true
DataGrid has following column types:
· BoundColumn: Default column type, displays item in the field as text
· ButtonColumn: Command button for each column
· EditCommandColumn: Column with editing commmand
· HyperLinkColumn: Displays contents as hyperlink
· Template Column: Allows template and custom controls
DataList:
Display rows of text and controls using a template to control appearence
DataList Controls have built-in formatting and selection capabilities
Repeater:
Display rows of other controls using a template to control appearence
Has no built-in capabilities found in the DataGrid and DataList controls
ADO.net ExecuteNonQuery Code Listing
private static void CreateCommand(string queryString, string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
ADO.net ExecuteReader Code Listing Stored Procedure Code Listing
Code Listing: Stored Procedure
Code Listing: ExecuteReader
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader(); // Data is accessible through the DataReader object here.
sqlConnection1.Close();
Code Listing: ExecuteReader
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader(); // Data is accessible through the DataReader object here.
sqlConnection1.Close();
ADO.net Executing Command ExecuteScalar, ExecuteNonQuery ExecuteReader
Each data provider included with the .net framework has its own command object
Every command object inherits from class DbCommand
Providers and their command objects are as under:
OLE DB : OleDbCommand
SQL Server : SqlCommand
ODBC Command : OdbcCommand
Oracle : OracleCommand
Methods common to these providers are:
ExecuteReader : Returns a DataReader object
ExecuteScalar : Returns a single scalar value
ExecuteScalar is used to retrieve a single value (like avg, max, min)
ExecuteNonQuery : Execute a command that does not return any value
ExecuteNonQuery returns no rows
It returns the number of rows affected
Used for Update, Insert, Delete
ExecuteXMLReader : Returns an XMLReader
Every command object inherits from class DbCommand
Providers and their command objects are as under:
OLE DB : OleDbCommand
SQL Server : SqlCommand
ODBC Command : OdbcCommand
Oracle : OracleCommand
Methods common to these providers are:
ExecuteReader : Returns a DataReader object
ExecuteScalar : Returns a single scalar value
ExecuteScalar is used to retrieve a single value (like avg, max, min)
ExecuteNonQuery : Execute a command that does not return any value
ExecuteNonQuery returns no rows
It returns the number of rows affected
Used for Update, Insert, Delete
ExecuteXMLReader : Returns an XMLReader
ADO.net DataReader Codelisting Retrieving multiple result sets
Code Listing: Data Reader Retrieving multiple result sets using DataReader
static void RetrieveMultipleResults(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM dbo.Categories;" +
"SELECT EmployeeID, LastName FROM dbo.Employees", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.HasRows)
{
Console.WriteLine("\t{0}\t{1}", reader.GetName(0), reader.GetName(1));
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0), reader.GetString(1));
}
reader.NextResult();
}
}
}
static void RetrieveMultipleResults(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM dbo.Categories;" +
"SELECT EmployeeID, LastName FROM dbo.Employees", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.HasRows)
{
Console.WriteLine("\t{0}\t{1}", reader.GetName(0), reader.GetName(1));
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0), reader.GetString(1));
}
reader.NextResult();
}
}
}
ADO.net DataReader Basics Methods and Properties
The DataReader provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially
Good choice when working with a large amount of data
DataReader must be closed if Command object returns value
If multiple sets are returned, the DataReader provides the NextResult to iterate
Important Methods/Properties of DataReader Class:
Public Properties:
1. Relations: Get the collection of relations that link tables
2. Tables: Get the collection of tables in the dataset
3. IsInitialized : Gets a value that indicates whether the dataset is initialized
Public Methods:
1. AcceptChanges : Commit all changes since last upload or AcceptChanges call
2. Clear : Clear all rows of in the dataset
3. Equals : Determine if two objects are similar
4. GetXML : Get XML representation of data in the dataset
5. RejectChanges: Rollback changes made since last upload or AcceptChanges call
Good choice when working with a large amount of data
DataReader must be closed if Command object returns value
If multiple sets are returned, the DataReader provides the NextResult to iterate
Important Methods/Properties of DataReader Class:
Public Properties:
1. Relations: Get the collection of relations that link tables
2. Tables: Get the collection of tables in the dataset
3. IsInitialized : Gets a value that indicates whether the dataset is initialized
Public Methods:
1. AcceptChanges : Commit all changes since last upload or AcceptChanges call
2. Clear : Clear all rows of in the dataset
3. Equals : Determine if two objects are similar
4. GetXML : Get XML representation of data in the dataset
5. RejectChanges: Rollback changes made since last upload or AcceptChanges call
ADO.net DataAdapter Members and Methods
DataAdapter Members and Methods:
Public Properties:
1. TableMappings: Gets a collection that provides the master mapping between source and data table
Public Methods:
1. Fill: Adds or refreshes rows in dataset
2. GetFillParameters: Gets the parameters set by the user
3. Update: Calls the respective insert, update or delete statements
Public Properties:
1. TableMappings: Gets a collection that provides the master mapping between source and data table
Public Methods:
1. Fill: Adds or refreshes rows in dataset
2. GetFillParameters: Gets the parameters set by the user
3. Update: Calls the respective insert, update or delete statements
ADO.net DataAdapter DataSet Code Listing
Code Listing: DataAdapter
Code Listing: DataSet
SqlDataAdapter custAdapter =
new SqlDataAdapter( "SELECT * FROM dbo.Customers", customerConnection);
OleDbDataAdapter ordAdapter =
new OleDbDataAdapter( "SELECT * FROM Orders", orderConnection);
DataSet customerOrders = new DataSet();
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
DataRelation relation =
customerOrders.Relations.Add("CustOrders",
customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}
Code Listing: DataSet
SqlDataAdapter custAdapter =
new SqlDataAdapter( "SELECT * FROM dbo.Customers", customerConnection);
OleDbDataAdapter ordAdapter =
new OleDbDataAdapter( "SELECT * FROM Orders", orderConnection);
DataSet customerOrders = new DataSet();
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
DataRelation relation =
customerOrders.Relations.Add("CustOrders",
customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}
ADO.net DataReader Codelisting
Code Listing: DataReader
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT CategoryID, CategoryName FROM dbo.Categories;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader[0], reader[1]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static private string GetConnectionString()
{
return "Data Source=(local);Initial Catalog=Northwind;" + "Integrated Security=SSPI";
} }
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT CategoryID, CategoryName FROM dbo.Categories;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader[0], reader[1]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static private string GetConnectionString()
{
return "Data Source=(local);Initial Catalog=Northwind;" + "Integrated Security=SSPI";
} }
ADO.net DataAdapter Basics
A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet
The DataAdapter also resolves the changes made to the DataSet back to the data source
It uses the Connection object of the .net framework data provider to connect to a data source
It used Command object to retrieve data from and resolve changes to the data source
Mainly used properties of DataAdapter
SelectCommand, UpdateCommand, InsertCommand, DeleteCommand
Fill is used to populate the dataset with the results of SelectCommand
Fill arguments are a DataSet and DataTable objects
The DataAdapter also resolves the changes made to the DataSet back to the data source
It uses the Connection object of the .net framework data provider to connect to a data source
It used Command object to retrieve data from and resolve changes to the data source
Mainly used properties of DataAdapter
SelectCommand, UpdateCommand, InsertCommand, DeleteCommand
Fill is used to populate the dataset with the results of SelectCommand
Fill arguments are a DataSet and DataTable objects
ADO.net DataSet Basics
The Dataset:
Dataset is explicitly designed for data access independent of data source
Thus, can be used with a variety of data sources
Disconnected object type
Contains a collection of one or more DataTable objects made up of rows, columns with constraints
DataSet is a memory-resident representation of data
Represents a complete set of data, including related tables, constraints etc.
DataSet can persist and reload its contents as XML, and schema as XSD
Typed Dataset:Tables and columns that are a part of [pending]
Dataset is explicitly designed for data access independent of data source
Thus, can be used with a variety of data sources
Disconnected object type
Contains a collection of one or more DataTable objects made up of rows, columns with constraints
DataSet is a memory-resident representation of data
Represents a complete set of data, including related tables, constraints etc.
DataSet can persist and reload its contents as XML, and schema as XSD
Typed Dataset:Tables and columns that are a part of [pending]
ADO.net Components
ADO.net Components has two main components:
1. .net framework data providers
2. The dataset
1. .net framework data providers:
Components that have been explicitly designed for data manipulation
Provides fast-forward only, read only access to data
Connection object: Provides connectivity to a data source
Command object: Enables access to database commands
DataReader object: Provides a high-performance stream of data
DataAdapter: Provides the bridge between the dataset and data source
Uses command object to execute SQL commands at the data source to load the dataset with data and also to synch the changes
.net framework has following data providers serving various database products
SQL Server: System.Data.SqlClient
OLE DB: System.Data.OleDB
ODBC: System.Data.ODBC
Oracle: System.Data.OracleClient (ver. 8.1.7 or later )
1. .net framework data providers
2. The dataset
1. .net framework data providers:
Components that have been explicitly designed for data manipulation
Provides fast-forward only, read only access to data
Connection object: Provides connectivity to a data source
Command object: Enables access to database commands
DataReader object: Provides a high-performance stream of data
DataAdapter: Provides the bridge between the dataset and data source
Uses command object to execute SQL commands at the data source to load the dataset with data and also to synch the changes
.net framework has following data providers serving various database products
SQL Server: System.Data.SqlClient
OLE DB: System.Data.OleDB
ODBC: System.Data.ODBC
Oracle: System.Data.OracleClient (ver. 8.1.7 or later )
ADO.net Diagram
Lock Keyword Code Listing
The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock
Code Listing: Lock
// statements_lock2.cs
using System;
using System.Threading;
class Account
{
int balance;
Random r = new Random();
public Account(int initial) { balance = initial; }
int Withdraw(int amount)
{
// This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
}
// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (this)
{
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Amount to Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0; // transaction rejected
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}
class Test
{
public static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account (1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}
Code Listing: Lock
// statements_lock2.cs
using System;
using System.Threading;
class Account
{
int balance;
Random r = new Random();
public Account(int initial) { balance = initial; }
int Withdraw(int amount)
{
// This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
}
// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (this)
{
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Amount to Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0; // transaction rejected
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}
class Test
{
public static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account (1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}
Fixed Keyword
Prevents relocation of a variable by the garbage collector
Fixed statement is only permitted in an unsafe context
The fixed statement sets a pointer to a managed variable and pins that variable during the execution of statement
Fixed statement is only permitted in an unsafe context
The fixed statement sets a pointer to a managed variable and pins that variable during the execution of statement
Tracing
Tracing is a technique for recording events
Tu enable tracing at different levels, do as under:
Application level: Application’s web.config, set Enabled to true
Page level: @Page directive, Trace attribute to True in web form’s html
Write trace to a file: web.config PageOutput=”False”, trace is written to Trace.axd in application’s root folder
Customizing Tracing:
element include a RequestLimit attribute to specify how many page requests to write to trace file
Writing messages to trace log using Write and Warn method
Code Listing: Tracing
Code Listing: Trace
using System.Diagnostics;
private void Page_Error(object sender, System.EventArgs e )
{
if(Trace.IsEnabled)
{
string strMessage;
if(Request.Browser.AOL)
strMessage = “AOL Browser”;
else
strMessage = ”Non AOL Browser”;
Trace.Warn(“Error”, strMessage, Server.GetLastError());
}
Server.ClearError();
Response.Redirect(“Trace.aspx”);
}
Tu enable tracing at different levels, do as under:
Application level: Application’s web.config, set
Page level: @Page directive, Trace attribute to True in web form’s html
Write trace to a file: web.config
Customizing Tracing:
Writing messages to trace log using Write and Warn method
Code Listing: Tracing
Code Listing: Trace
using System.Diagnostics;
private void Page_Error(object sender, System.EventArgs e )
{
if(Trace.IsEnabled)
{
string strMessage;
if(Request.Browser.AOL)
strMessage = “AOL Browser”;
else
strMessage = ”Non AOL Browser”;
Trace.Warn(“Error”, strMessage, Server.GetLastError());
}
Server.ClearError();
Response.Redirect(“Trace.aspx”);
}
Error Pages : Page level and web.config
Page Level error pages - @Page directive ErrorPage
<%@ Page errorPage=”errpage.aspx””%>
Application wide error pages – Web.config customErrors section
More about customErrors section:
customErrors mode attribute must be set to On to view the error pages while debugging the application on local machine
Setting the mode to RemoteOnly (the default) will display the designated error pages when the application is accessed from client computers, but not when application is accessed locally
customErrors settings in the web.config apply only to resource types that ASP.net considers to be part of the web application
Custom error page will not be displayed when a page with .htm is accessed, to handle such scenarios use IIS settings
<%@ Page errorPage=”errpage.aspx””%>
Application wide error pages – Web.config customErrors section
More about customErrors section:
customErrors mode attribute must be set to On to view the error pages while debugging the application on local machine
Setting the mode to RemoteOnly (the default) will display the designated error pages when the application is accessed from client computers, but not when application is accessed locally
customErrors settings in the web.config apply only to resource types that ASP.net considers to be part of the web application
Custom error page will not be displayed when a page with .htm is accessed, to handle such scenarios use IIS settings
Exception Handling : Server Object Exception Handling Events
Server object’s Exception Handling events:
GetLastError: Get the last exception that occurred on the server
ClearError: Clear the last error
Code Listing:GetLastError
CodeListing:ClearError
Exception ex = Server.GetLastError();
Session[“Error”] = ex.Message;
Server.ClearError();
Server.Transfer(“ErrorEvents.aspx”);
GetLastError: Get the last exception that occurred on the server
ClearError: Clear the last error
Code Listing:GetLastError
CodeListing:ClearError
Exception ex = Server.GetLastError();
Session[“Error”] = ex.Message;
Server.ClearError();
Server.Transfer(“ErrorEvents.aspx”);
Exception Handling : Error Events
Error Events:
Another way of excpetion handling is through web object’s built-in error events.
Error events allow exception handling for an entire object in a single, centralized location – the error event procedure
When an unhandled exception occurs in a web application, ASP.net fires the following error events:
Page_Error: Errors occuring on the page, this event procedure resides in the Web form
Global_Error: Exception occurring at Application level. Resides in Global.asax
Appication_Error: Exception occurring at Application level. Resides in Global.asax
Another way of excpetion handling is through web object’s built-in error events.
Error events allow exception handling for an entire object in a single, centralized location – the error event procedure
When an unhandled exception occurs in a web application, ASP.net fires the following error events:
Page_Error: Errors occuring on the page, this event procedure resides in the Web form
Global_Error: Exception occurring at Application level. Resides in Global.asax
Appication_Error: Exception occurring at Application level. Resides in Global.asax
Exception Handling : Try-Catch-Finally
A common usage of catch and finally together is to obtain and use resources in the try block
Deal with exceptional events in catch block
Release the resources in finally block
using System;
public class EHClass
{
public static void Main ()
{
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch(NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
catch
{
Console.WriteLine("Caught exception #2.");
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
Output:
Executing the try statement. System.NullReferenceException: Attempted to dereference a null object reference. at EHClass.Main() Caught exception #1. Executing finally block.
Deal with exceptional events in catch block
Release the resources in finally block
using System;
public class EHClass
{
public static void Main ()
{
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch(NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
catch
{
Console.WriteLine("Caught exception #2.");
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
Output:
Executing the try statement. System.NullReferenceException: Attempted to dereference a null object reference. at EHClass.Main() Caught exception #1. Executing finally block.
Exception Handling : Try-Finally
Finally block contains exception handler and cleanup code
Finally block executes regardless of how try block exited
Code listing: Try-Finally
This program generates System.InvalidCastException but also prints value of i
using System;
public class TestTryFinally
{
public static void Main()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
finally
{
Console.Write("i = {0}", i);
}
}
}
Finally block executes regardless of how try block exited
Code listing: Try-Finally
This program generates System.InvalidCastException but also prints value of i
using System;
public class TestTryFinally
{
public static void Main()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
finally
{
Console.Write("i = {0}", i);
}
}
}
Exception Handling : Try-Catch
Try-Catch statement consists of a try block followed by one or more catch clauses
Try block contains the guarded code block that may cause the exception
Catch block can be used without arguments, in which case it catches any type of exception
Catch block generally has an object argument derived from System.Exception class, in which case it handles a particular type of exception
It is possible to have multiple catch clauses in one try-catch statement
Order of catch statements is important when multiple catches are present
Code Listing: Try-Catch
using System;
class MyClass
{
public static void Main()
{
MyClass x = new MyClass();
try
{
string s = null;
x.MyFn(s);
}
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
}
}
public void MyFn(string s)
{
if (s == null)
throw new ArgumentNullException();
}
}
Try block contains the guarded code block that may cause the exception
Catch block can be used without arguments, in which case it catches any type of exception
Catch block generally has an object argument derived from System.Exception class, in which case it handles a particular type of exception
It is possible to have multiple catch clauses in one try-catch statement
Order of catch statements is important when multiple catches are present
Code Listing: Try-Catch
using System;
class MyClass
{
public static void Main()
{
MyClass x = new MyClass();
try
{
string s = null;
x.MyFn(s);
}
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
}
}
public void MyFn(string s)
{
if (s == null)
throw new ArgumentNullException();
}
}
Exception Handling : Throw
Throw:
Thrown exception is an object whose class is derived from System.Exception
When an exception is thrown, program looks for the catch statement that handles the exception
Code Listing: Throw
using System;
public class ThrowTest
{
public static void Main()
{
string s = null;
if (s == null)
{
throw(new ArgumentNullException());
}
Console.Write("The string s is null"); // not executed
}
}
Thrown exception is an object whose class is derived from System.Exception
When an exception is thrown, program looks for the catch statement that handles the exception
Code Listing: Throw
using System;
public class ThrowTest
{
public static void Main()
{
string s = null;
if (s == null)
{
throw(new ArgumentNullException());
}
Console.Write("The string s is null"); // not executed
}
}
Volatile Keyword Codelisting
A volatile declaration indicates that a field can be modified in a program by OS, Hardware (mouse, modem) or a thread
System reads the current value of the volatile object at the point it is requested
Value of the object is written immediately on assignment
Usually used for a field that is accessed by multiple threads without using the lock statement
Code Listing: Volatile
// csharp_volatile.cs
class Test
{
public volatile int i;
Test(int _i)
{
i = _i;
}
public static void Main()
{
}
}
System reads the current value of the volatile object at the point it is requested
Value of the object is written immediately on assignment
Usually used for a field that is accessed by multiple threads without using the lock statement
Code Listing: Volatile
// csharp_volatile.cs
class Test
{
public volatile int i;
Test(int _i)
{
i = _i;
}
public static void Main()
{
}
}
Virtual Keyword Codelisting
Declare a method/property virtual to be able to change the implementation in a derived class
By default methods are non-virtual
Virtual cannot be used with static, abstract and override
It is an error to use virtual modifier on a static property
Code Listing: Virtual
using System;
class TestClass
{
public class Dimensions
{
public const double pi = Math.PI;
protected double x, y;
public Dimensions() {}
public Dimensions (double x, double y)
{
this.x = x;
this.y = y;
}
public virtual double Area()
{
return x*y;
}
}
public class Circle: Dimensions
{
public Circle(double r): base(r, 0) { }
public override double Area()
{
return pi * x * x;
}
}
class Sphere: Dimensions
{
public Sphere(double r): base(r, 0) {}
public override double Area()
{
return 4 * pi * x * x;
}
}
class Cylinder: Dimensions
{
public Cylinder(double r, double h): base(r, h) { }
public override double Area()
{
return 2*pi*x*x + 2*pi*x*y;
}
}
public static void Main()
{
double r = 3.0, h = 5.0;
Dimensions c = new Circle(r);
Dimensions s = new Sphere(r);
Dimensions l = new Cylinder(r, h);
// Display results:
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
}
}
By default methods are non-virtual
Virtual cannot be used with static, abstract and override
It is an error to use virtual modifier on a static property
Code Listing: Virtual
using System;
class TestClass
{
public class Dimensions
{
public const double pi = Math.PI;
protected double x, y;
public Dimensions() {}
public Dimensions (double x, double y)
{
this.x = x;
this.y = y;
}
public virtual double Area()
{
return x*y;
}
}
public class Circle: Dimensions
{
public Circle(double r): base(r, 0) { }
public override double Area()
{
return pi * x * x;
}
}
class Sphere: Dimensions
{
public Sphere(double r): base(r, 0) {}
public override double Area()
{
return 4 * pi * x * x;
}
}
class Cylinder: Dimensions
{
public Cylinder(double r, double h): base(r, h) { }
public override double Area()
{
return 2*pi*x*x + 2*pi*x*y;
}
}
public static void Main()
{
double r = 3.0, h = 5.0;
Dimensions c = new Circle(r);
Dimensions s = new Sphere(r);
Dimensions l = new Cylinder(r, h);
// Display results:
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
}
}
Static Keyword Codelisting
A static member belongs to a class and not to an object of the class
Static modifier can be used with fields, methods, properties, operators, events and constructors
A static member cannot be referenced through an instance
There is only one copy of a static member amongst all instances
Use of this is not allowed with static members
Code listing: Static Members
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;
}
}
To refer x:
MyBaseC.MyStruct.x
Static modifier can be used with fields, methods, properties, operators, events and constructors
A static member cannot be referenced through an instance
There is only one copy of a static member amongst all instances
Use of this is not allowed with static members
Code listing: Static Members
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;
}
}
To refer x:
MyBaseC.MyStruct.x
Sealed Keyword Code Listing
A sealed class cannot be inherited
Use the sealed modifier in class declaration to prevent inheritance
It is an error to use sealed class as base class
Not permitted to use abstract modifier with the sealed class
Structs are implicitly sealed, hence not allowing inheritance
Code Listing: Sealed Class
// cs_sealed_keyword.cs
// Sealed classes
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Use the sealed modifier in class declaration to prevent inheritance
It is an error to use sealed class as base class
Not permitted to use abstract modifier with the sealed class
Structs are implicitly sealed, hence not allowing inheritance
Code Listing: Sealed Class
// cs_sealed_keyword.cs
// Sealed classes
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Override : Code Listing
// cs_override_keyword.cs
// Calling overriden methods from the base class
using System;
class TestClass
{
public class Square
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double Area()
{
return x*x;
}
}
class Cube: Square
{
// Constructor:
public Cube(double x): base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (6*(base.Area()));
}
}
public static void Main()
{
double x = 5.2;
Square s = new Square(x);
Square c = new Cube(x);
Console.WriteLine("Area of Square = {0:F2}", s.Area());
Console.WriteLine("Area of Cube = {0:F2}", c.Area());
}
}
// Calling overriden methods from the base class
using System;
class TestClass
{
public class Square
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double Area()
{
return x*x;
}
}
class Cube: Square
{
// Constructor:
public Cube(double x): base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (6*(base.Area()));
}
}
public static void Main()
{
double x = 5.2;
Square s = new Square(x);
Square c = new Cube(x);
Console.WriteLine("Area of Square = {0:F2}", s.Area());
Console.WriteLine("Area of Cube = {0:F2}", c.Area());
}
}
Override Keyword
An Override provides a new implementation of a member inherited from a base class
Method overridden by an override declaration is known as the overridden base method
Overridden base method must have the same signature as the override method
Overridden base method must be abstract, virtual or override
Both the override method and the virtual method should have same access identifier
Method overridden by an override declaration is known as the overridden base method
Overridden base method must have the same signature as the override method
Overridden base method must be abstract, virtual or override
Both the override method and the virtual method should have same access identifier
Extern Keyword Code Listing
Used to indicate that method is implemented outside the C# code
It is an error to use abstract and extern to modify the same member
Since extern method provides no implementation, there is no method body
E.g.: public static extern int extMethod(int x);
Code Listing: Using extern with User32.dll
using System;
using System.Runtime.InteropServices;
class MyClass
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
public static int Main()
{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return MessageBox(0, myString, "My Message Box", 0);
}
}
It is an error to use abstract and extern to modify the same member
Since extern method provides no implementation, there is no method body
E.g.: public static extern int extMethod(int x);
Code Listing: Using extern with User32.dll
using System;
using System.Runtime.InteropServices;
class MyClass
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
public static int Main()
{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return MessageBox(0, myString, "My Message Box", 0);
}
}
Delegate : Code Listing
public class SimpleDelegate : System.Web.UI.Page
{
delegate bool MathDelegate(int x);
private void Page_Load(object sender, System.EventArgs e)
{
int MyNumber = 42;
Response.Write(“Using Delegates..”);
Response.Write(“The number ” + MyNumber.ToString());
// Call AboutNumber to invoke IsEven
AboutNumber(new MathDelegate(IsEven), MyNumber);
Response.Write(“ even and it ”);
//Call AboutNumber to invoke IsPrime
AboutNumber(new MathDelegate(IsPrime), MyNumber);
Response.Write( “ prime ” );
}
// Invoke the delegate
void AboutNumber(MathDelegate Func, int x)
{
if(Func(x)) Response.Write( “ is ” );
else Response.Write( “ is not ” );
}
// Procedures invoked through MathDelegate
bool IsEven( int x )
{
if( x % 2 == 0) return false;
else return true;
}
bool IsPrime( int x )
{
for(int i = 2; i > (x/2); i++)
if( x % i == 0 )
return false;
return true;
}
}
{
delegate bool MathDelegate(int x);
private void Page_Load(object sender, System.EventArgs e)
{
int MyNumber = 42;
Response.Write(“Using Delegates..”);
Response.Write(“The number ” + MyNumber.ToString());
// Call AboutNumber to invoke IsEven
AboutNumber(new MathDelegate(IsEven), MyNumber);
Response.Write(“ even and it ”);
//Call AboutNumber to invoke IsPrime
AboutNumber(new MathDelegate(IsPrime), MyNumber);
Response.Write( “ prime ” );
}
// Invoke the delegate
void AboutNumber(MathDelegate Func, int x)
{
if(Func(x)) Response.Write( “ is ” );
else Response.Write( “ is not ” );
}
// Procedures invoked through MathDelegate
bool IsEven( int x )
{
if( x % 2 == 0) return false;
else return true;
}
bool IsPrime( int x )
{
for(int i = 2; i > (x/2); i++)
if( x % i == 0 )
return false;
return true;
}
}
Event : Steps to create and use an event
Create or identify a delegate
If you are defining your own event, you must also ensure that there is a delegate to use with the event keyword
Create a class that contains:
1. An event created from the delegate
2. Optional. A method that verifies that an instance of the delegate declared with the event keyword exists
3. Method that calls the event
Define one or more classes that connect methods to the event. These classes will include:
a. Associate one or more methods using the += and -= operators, with the event base class
b. The definition of the method(s) that will be associated with the event
Use the event
a. Create an object of the class that contains the event declaration
b. Create an object of the class that contains the event definition, using the constructor that was defined
If you are defining your own event, you must also ensure that there is a delegate to use with the event keyword
Create a class that contains:
1. An event created from the delegate
2. Optional. A method that verifies that an instance of the delegate declared with the event keyword exists
3. Method that calls the event
Define one or more classes that connect methods to the event. These classes will include:
a. Associate one or more methods using the += and -= operators, with the event base class
b. The definition of the method(s) that will be associated with the event
Use the event
a. Create an object of the class that contains the event declaration
b. Create an object of the class that contains the event definition, using the constructor that was defined
Delegates
Delegates are types used to invoke one or more methods where the actual method invoked is determined at run time.
This provides a safe way for derived objects to subscribe to events provided by their base class.
Delegates also provide a way for programs to respond to asynchronous procedures
Delegates provide a way to invoke methods by their address rather than by their name
This provides a safe way for derived objects to subscribe to events provided by their base class.
Delegates also provide a way for programs to respond to asynchronous procedures
Delegates provide a way to invoke methods by their address rather than by their name
Event
Used to specify a delegate that will be called upon the occurrence of some event in the code.
Delegate can have one or more associated methods that will be called when code indicates that event has occurred
Event in one program can be made available to another programs under CLR
When an object generates an event, it must send the event out. The way the events are dispatched is through use of delegates
Differences: Const and ReadOnly
Differences Const and ReadOnly:
Initialization:
Const: Can only be initialized at declaration of the field
ReadOnly: Initialized either at declaration or in a constructor
Compile/Run time:
Const: Const field is a Compile time constant
ReadOnly: ReadOnly is a run-time constant
Public static readonly uint tmr = (uint) DateTime.Now.Ticks;
Initialization:
Const: Can only be initialized at declaration of the field
ReadOnly: Initialized either at declaration or in a constructor
Compile/Run time:
Const: Const field is a Compile time constant
ReadOnly: ReadOnly is a run-time constant
Public static readonly uint tmr = (uint) DateTime.Now.Ticks;
Subscribe to:
Posts (Atom)