Thursday, August 30, 2007

GridView

  • GridView provides a tabular grid-like view of the contents of a data source
  • The GridView is designed to leverage the new data source object model, and it works best when bound to a data source control via the DataSourceID property
  • A Grid can have delcared and auto generated columns at the same time
  • Auto-generated columns are not added to the Columns collection
  • The GridView doesn't support the AllowCustomPaging property found in DataGrid
  • Compared to the DataGrid control, the GridView provides an extended eventing model; pre/post pairs of events, with cancelling and more
  • It is declared as:

    public class Gridview : CompositeDataBoundControl, IcallbackContainer, ICallbackEventHandler

Properties of GridView Control

AllowPaging, AllowSorting

Support for Paging, Sorting

AutoGenerateColumns

Default is true

AutoGeneratexxxButton

Delete, Edit and Select buttons can be displayed with each reord

DataMember

Specifies which table to be bind from the DataSource

DataSource/DataSourceID

Indicates the bound data source control

EnableSortingAnd PagingCallbacks

 

SortDirection

 

SortExpression

 

UseAccessibleHeader

 
  • GridView has some Style properties like AlternatingRowStyle, EditRowStyle, HeaderStyle, FooterStyle, PagerStyle, RowStyle, SelectedRowStyle
  • GridView appearence properties include BackImageUrl, Caption, GridLines, PagerSettings, ShowFooter
  • Templating properties are EmptyDataTemplate and PagerTemplate
  • State Properties include: DataKeyNames, DataKeys, PageCount, SelectedIndex, SelectedRow, SelectedValue

Events Fired by the GridView Control

PageIndexChanging, PageIndexChanged

RowDeleting, RowDeleted

RowCancellingEdit

RowEditing

RowCommand

RowUpdating, RowUpdated

RowCreated

SelectedIndexChanging SelectedIndexChanged

RowDataBound

Sorting, Sorted


 

Configuring Columns

  • Columns can Programatically be defined as:


     

    BoundField field = new BoundField();

    Field.DataField = "companyname";

    Field.HeaderText = "Company Name";

    grid.ColumnFields.Add(field);


 

  • Columns can be Declaratively defines as:


     

    <columns>

    <asp:boundfield datafield="customerid" headertext="ID"/>

    </columns>

Column Types in GridView

  • GridView supports following types of columns
    • BoundField
    • ButtonField, CheckBoxField
    • CommandField
    • HyperLinkField, ImageField, TemplateField

Templated Fields

  • A TemplateField column gives each row in the grid a personalized UI that is completely defined by the page developer
  • Templates can be defined for various rendering stages, including the default view, in-place editing, header etc
  • Declared as:

    <asp:templateField headertext ="Product" >

    <itemTemplate>

    <b><%# Eval("productname")%></b> <br/>

    available in <%# Eval("quantityperunit")%>

    </itemtemplate>

    </asp:templateField>


 

Sorting Data

  • The GridView doesn't implement a sorting algorithm; instead, it relies on the data source control (or the page, if bound to an enumerable object) to provide sorted data
  • To enable the GridView's sorting capabilities, set AllowSorting property to true

Executing an Operation on a Given Row

  • A RowCommand event handler is required to handle row operations
  • GridView stores the index of the clicked row in the CommandArgument property of the GridViewCommandEventArgs structure

Wednesday, August 29, 2007

Server.Execute and Server.Transfer

Server.Execute Method

  • Execute method allows to consider an external page as a subroutine
  • When the execution flow reaches the Server.Execute call, control is passed to the specified page
  • Execution of the current page is suspended, and the external page is spawned
  • Execute method is a more useful alternative to using server-side includes
  • Execute makes control to return to the calling page once external page has been executed

Server.Transfer Method

  • Calling Transfer method causes termination of current page processing and executes the specified page
  • The control never returns to the page that called the Transfer, which is not the case with Server.Execute, where control returns to the calling page
  • Hence, any code specified after Server.Transfer call, will not be executed
  • It is efficient for two reasons, first no roundtrip to the client is requested, unlike Response.Redirect
  • Secondly, the same HttpApplication that was serving the caller request is reused

Server Object - HttpServerUtility


 

  • The functionality of the ASP intrinsic Server is object in ASP.net is implemented by the HttpServerUtility class
  • An instance of the type is created when ASP.net begins to process the request and is then stored as part of the request context
  • HttpServerUtility class has two properties MachineName and ScriptTimeout
  • ScriptTimeout is to get/set the time in seconds a request is allowed to process
  • Code: this.Server.ScriptTimeout = 30000;

Important methods of Server object

UrlEncode/ UrlDecode

Encodes a string (for HTTP transmission to a client) in a URL

UrlDecode decodes a string encoded for Http transmission

MapPath

Returns the physical path of a file from provided virtual path

UrlPathEncode

Encodes only path portion of the URL string

ClearError

Clears the last exception that was thrown for the request

Transfer / Execute

See below

Global.asax

GLOBAL.ASAX

  • Used by Web Applications to handle some application-level events raised by the ASP.net runtime or by registered http modules
  • Global.asax file is optional and is located in the root directory of the application
  • Only one global.asax file per application is accepted, those in sub-directories are ignored
  • When the application is started, global.asax is parsed into a source class and compiled
  • The resultant assembly is created in the temporary directory just as any other dynamically generated assembly would be
  • The class is named as ASP.global_asax and is derived from System.Web.HttpApplication
  • Any modification made during application execution causes application restart

Contents/Syntax of Global.asax

  • Four elements determine the syntax of the global.asax file
  1. Application Directives
  2. Code declaration blocks
  3. Server side <object> tags
  4. Server side includes

Application Directives

  • The global.asax supports three directives: @Application, @Import and @Assembly
  • @Import directive imports a namespace into an application
  • @Assembly directive links an assembly to the application at compile time
  • @Application supports a few attributes - Description, Language and Inherits

Code Declaration Blocks

  • A global.asax file can contain code wrapped by a <script> tag
  • <script language= "C#" runat="server" src="global.aspx.cs">

Server-Side <object> tags

  • The server-side <object> tag allows to create new objects using a declarative syntax
  • object tag can take three forms, depending on the specified type

    <object id="..." runat="server" scope=Pipeline|Application|Session class="...">

    <object id="..." runat="server" scope=Pipeline|Application|Session progid="...">

    <object id="..." runat="server" scope=Pipeline|Application|Session classid="...">

  • In first case, the object is identified by the name of the class and assembly that contains it
  • In other two cases, the object to create is a COM object identified by the progid or classid

Server-Side Includes

  • An #include directives inserts the contents of the specified file as-is into the ASP.net file that uses it
  • The directive must be enclosed in an HTML comment
  • <!-- #include file="filename"> or <!-- #include virtual="filename">

Static Properties

  • If static proerties are defined in global.asax file, they will be accessible for reading and writing by all pages in the application
  • Sample code as under:

    <script language="C#" runat="server">

    public static int Counter = 0;

    </script>

  • To access this property from a page, code as under

    Response.Write(ASP.global_asax.Counter.ToString());

Application Lifecycle


 

0

APPLICATION_START

 

1

BeginRequest

ASP.NET HTTP pipeline begins to work on the request

2

AuthenticateRequest

All the internal ASP.NET auhentication modules subscribe to this event.

If no authentication module module produced an authenticated user, an internal default authentication module is invoked to produce an identity for the unauthenticated user

3

PostAuthenticateRequest

Post authentication, all the information is stored in the HttpContext User property

4

AuthorizeRequest

Event commonly handled by application code based on business logic or other application requirements

5

PostAuthorizeRequest

The request has been authorized

6

ResolveRequestCache

ASP.net runtime verifies whether returning a previously cached page can resolve the request

If a valid cached representation is found, the request is served from cache, and calls the EndRequest handlers

7

PostResolveRequestCache

If request can not be served from the cache, and the procedure continues

An Http handler corresponding to the requested URL is created at this point. A .aspx page will cause an instance of Page class to be generated

8

PostMapRequestHandler

Event fires once HttpHandler gets created

9

AcquireRequestState

Module associated to this event tries to retrieve state information from the request

10

PostAcquireRequestState

The state information (session/application) has been acquired

11

PreRequestHandlerExecute

Fired immidiately prior to executing the handler for a given request

12

PostRequestHandlerExecute

Event is raised when the handler has generated the response text

13

ReleaseRequestState

Event raised when handler releases the state information and prepares to shut down. Also used by the session state module to update the dirty session state if necessary

14

PostReleaseRequestState

The updated state is persisted

15

UpdateRequestCache

ASP.net runtime determines whether the generated output, now also properly filtered by registered modules, should be cached to be reused with upcoming idnetical requests

16

PostUpdateRequestCache

The page has been saved to the output cache if it was configured to do so

17

EndRequest

Final step in HTTP pipeline. The control passes back to the HttpRuntime object, which is responsible for the actual forwarding of the response to the client

0

APPLICATION_END

 

Debug and Trace

DEBUG CLASS

  • Namespace System.Diagnostics
  • Provides a set of methods and properties that help in debugging the code
  • This class can not be inherited, i.e it is sealed
  • This class provides methods to display an Assert dialog box, and to emit an assertion that will always fail
  • Provides write methods in various flavors like Write, WriteLine, WriteIf, WriteLineIf
  • To enable debugging in C#, add the /d:DEBUG flag to the compiler command line
  • or, add #define DEBUG to the top of the code file
  • Debug is DISABLED in release builds by default, so no executable code is generated for Debug methods

TRACE CLASS

  • Namespace System.Diagnostics
  • Provides a set of methods and properties that help in tracing the execution of the code
  • Methods and properties of Trace class can be used to monitor the health of an application running in real-life settings
  • Tracing helps in isolating problems and fixing them without disturbing a running system
  • To enable Tracing in C#, add the /d:TRACE flag to the compiler command line
  • or, add #define TRACE to the top of the code file
  • In VS2005 trace is ENABLED by default. Therefore, code is generated for all Trace methods in both release and debug builds
  • To set the AutoFlush and IndentSize in Web.Config, specify trace settings as under:

    <configuration>

    <system.diagnostics>

    <trace autoflush="false" indentsize="3">

    </system.diagnostics>

    </configuration>

Sunday, August 26, 2007

DataView Object

DATAVIEW OBJECT

  • The DataView class represents a customized view of DataTable
  • The relationship between DataTable and DataView are governed by the rules of a well-known design pattern; the document/view model
  • The DataTable ojects act as the document, whereas the DataView behaves as the view
  • At any moment there can be multiple views for the same underlying data
  • The view is implemented by maintaining a separate array with the indexes of the original rows that match the criteria set on the view
  • By default, the table view is unfiltered and contains all the records included in the table
  • A DataView does not contain copies of the table's rows. It is limited to storing an array of indexes that is updated whenever any of the filter properties are set


 

IMPORTANT PROPERTIES OF DATAVIEW CLASS

AllowDelete / AllowEdit / AllowNew

Get or set permissions to allow row operations in view

ApplyDefaultSort

Permission to allow default sorting

RowFilter

G/sets the expression used to filter out rows in the view

Sort

G/sets the sorting of the view in terms of columns and order

Table

G/sets the source DataTable for the view

DataViewManager

Gets the DataViewManager object associated with this view


 

IMPORTANT METHODS OF DATAVIEW CLASS

AddNew

Add a new row to the view and the underlying table

BeginInit / EndInit

Begin / End initialization of the view, used for multiple changes

Delete

Delete the row at specified index, deletes row in table too

Find

Finds a row using specified key value

FindRows

Returns an array of row objects that match specified key value

GetEnumerator

Returns an enumerator object for the DataView


 

ADO.net > Object Data Source

----------OBJECT DATA SOURCE----------

• The ObjectDataSource class enables user-defined classes to associate the output of their methods to data-bound controls
• ODS control represents a middle-tier object with data retrieval and update capabilities
• The ODC control acts as a data interface for data-bound controls such as the GridView, FormView or DetailsView controls, and enables those controls to display and edit data from a middle-tier business object on an ASP.net page
• ODS control supports a three-tier architecture by providing a way to bind data controls on the page to a middle-tier business object
• ODS works with a middle-tier object to select, insert, update, delete, page, sort, cache and filter data declaratively without extensive code
• Like other data source controls, ObjectDataSource supports declarative paramaeters to allow developers to pass page-level variables to object’s methods
• The ObjectDataSource class makes some assumptions about about the objects it wraps. As a consequence, an arbitary class cant’ be used with this data source control

ADO.net > DataView > Code Listing

DATAVIEW CODE LISTING

DataTable customers = new DataTable("Customers");
string cmdStr = ConfigurationManager.ConnectionStrings["nwind"].ConnectionString;

using (SqlConnection connection = new SqlConnection(cmdStr))
{
SqlCommand selectAllCustomers = connection.CreateCommand();
selectAllCustomers.CommandText = "Select * from [Customers]";

connection.Open();
customers.Load(selectAllCustomers.ExecuteReader(CommandBehavior.CloseConnection));
}

DataView dv = new DataView(customers, "Region= 'SP' and Country = 'Brazil'", "ContactName", DataViewRowState.CurrentRows);

GridView1.DataSource = dv;
GridView1.DataBind();

ADO.net > DataView

DATAVIEW OBJECT
• The DataView class represents a customized view of DataTable
• The relationship between DataTable and DataView are governed by the rules of a well-known design pattern; the document/view model
• The DataTable ojects act as the document, whereas the DataView behaves as the view
• At any moment there can be multiple views for the same underlying data
• The view is implemented by maintaining a separate array with the indexes of the original rows that match the criteria set on the view
• By default, the table view is unfiltered and contains all the records included in the table
• A DataView does not contain copies of the table’s rows. It is limited to storing an array of indexes that is updated whenever any of the filter properties are set

ADO.net > Creating a DataRelation

CREATING A DATARELATION
• DataRelations are exclusively in-memory objects that must be created explicitly with code
• Following code sets up a relation based on column ‘empID’

DataColumn c1 = tableEmp.Columns(“empID”);
DataColumn c2 = tableOrd.Columns(“empID”);
DataRelation rel = new DataRelation(“Emp2Orders”, c1, c2);
DataSet.Relations.Add(rel);

ADO.net > DataRelation

DataRelation

• A Data Relation represents a parent/child relationship between two DataTable objects in the same DataSet
• A relation is set between two tables based on matching columns in the parent and the child tables
• The matching columns in the two related tables can have different names, but they must have same type
• All the data relations are stored in the Relations collection

=======================================

Important properties of DataRelation class

ChildColumns / ParentColumns >> Get Child/Parent DataColumns of the relation
ChildTable / ParentTable >> Get Child/Parent DataTable object of the relation
ChildKeyConstraint >> Get the ForeignKeyConstraint object of the relation
DataSet >> Get the DataSet to which the relation belongs
RelationName >> Get/Set the name of the relation
Nested >> Used for XML rendering

ADO.net > DataTable > Methods and Properties

IMPORTANT PROPERTIES OF DATATABLE CLASS

ChildRelations >> Get the collection of child relations
Columns/Rows >> Get the collection of child columns/rows
Constraints Get the collection of constraints
DataSet >> Name of the DataSet to which the DataTable belongs to
Rows
PrimaryKey >> Get the PK of the table
TableName >> Get/Set the table name

===============================================================

IMPORTANT METHODS OF THE DATATABLE CLASS

AcceptChanges / RejectChanges >> Commit / Rollback for changes made to data in the DataTable
HasChanges / GetChanges >> GetChanges returns a dataset containing changed rows
Clone >> Copies the structure (schemas,relations) only, but NOT DATA
Copy >> Makes a deep copy, it is CLONING WITH DATA
ImportRow >> Deep copy of DataRow
ReadXml >> Populate the DataTable by reading schema and data from XML doc
Clear / Reset >> Remove all rows / Empties tables, relations and constraints
Compute >> Compute the given expression on rows, returns object
CreateDataReader >> Returns a DataTableReader object

ADO.net > DataTable > Table Constraints

TABLE CONSTRAINTS

• A constraint is a logical rule set on a table to preserve the integrity of the data
• The .net framework supports two types of constraints ForeignKeyConstraint and UniqueConstraint
• ForeignKeyConstraint class sets the rules that govern how the table propagates, updates and deletes child tables
• UniqueConstraint class ensures that a single column or array of columns have unique non-duplicated values

===============================================================

FOREIGNKEY CONSTRAINT
• ForeignKeyConstraint constructor takes the name of the object plus two DataColumn objects
• The first column is from parent table, second is from child table
• Sample code listing is as under:
DataColumn dCol1 = tableEmp.Columns(“empID”);
DataColumn dCol2 = tableOrd.Columns(“empID”);
ForeignKeyConstraint fk = new ForeignKeyConstraint(“EmpOrders”, c1, c2);
• The constraint is added to the child table and is configured using the UpdateRule, DeleteRule and AcceptRejectRule properties

====================================================================

UNIQUEKEY CONSTRAINT
• A unique key constraint can be created explicitly using its constructor as shown under:

UniqueConstraint uc;
uc = new UniqueConstraint(dcol);
tableEmp.Constraints.Add(uc);

Saturday, August 25, 2007

ADO.net > DataTable DataColumn DataRow

DATATABLE, DATACOLUMN AND DATAROW OBJECT
• DataTable object represents one table of in-memory data
• Mostly used as a container of data within a DataSet, the DataTable object is also valid as a standalone object that contains tabular data
• To create a DataTable programatically, first define its schema and then add new rows
• Using DataColumn define Columns within a DataTable
• Sample code : DataSet > DataTable > DataColumn > DataRow

----------CREATING A DataTable WITHIN A DATASET-------------
DataSet ds = new DataSet();
DataTable tableEmp = new DataTable(“Employees”);


-----------CREATING A DataColumn WITHIN A DATATABLE-----------------

DataColumn dcol = new DataColumn();
dcol.DataType = System.Type.GetType("System.Decimal");
dcol.AllowDBNull = true; dcol.Caption = "Salary"; dcol.ColumnName = "Salary";
dcol.DefaultValue = 0;
tableEmp.Columns.Add(dcol);

-------------CREATING DataRow WITHIN A DATATABLE--------------------

DataRow row = tableEmp.NewRow();
row[“ID”] = 1;
row[“Name”] = ”Bubbly”;
tableEmp.Rows.Add(row);

ADO.net > ExecuteReader v/s CreateDataReader

ExecuteReader v/s CreateDataReader
• ExecuteReader reads the data in Connected mode, while DataReader does it in disconnected mode
• The DataTableReader obtains the contents of one or more DataTable objects in the form of one or more read-only, forward-only result sets
• DataTableReader provides a way to iterate over rows in a DataTable or in rows in cache
• The cached data can be modified while the DataTableReader is active

ADO.net > DataSet Object

DATASET OBJECT
• The DataSet class implements three important interfaces:
1. IlistSource makes it possible to return a data-bound list of elements
2. ISerializable make the class capable of controlling how its data is serialized to a .net formatter
3. IXMLSerializable guarantees the class can serialize itself to XML

==================================================

IMPORTANT METHODS OF THE DATASET CLASS
AcceptChanges / RejectChanges >>Commit and Rollback for changes made to data in the DataSet
HasChanges / GetChanges >> GetChanges returns a dataset containing changed rows
Clone >> Copies the structure (schemas,relations) only, but NOT DATA
Copy >> Makes a deep copy, it is CLONING WITH DATA
Merge >> Merge an ADO.net object with current DataSet
ReadXml >> Populate the DataSet by reading schema and data from XML doc
Clear / Reset >> Remove all rows / Empties tables, relations and constraints

ADO.net > In-Memory Data Container Objects

IN-MEMORY DATA CONTAINER OBJECTS
• The System.Data namespace contains several collection-like objects that, combined, provide an in-memory representation of the DBMS relational programming model
• The DataSet is an in-memory cache of data made of tables, relations and constraints. Serializable and remotable, it can be filled from a variety of data sources and works regardless of which one is used
• DataTable represents a relational table of data with a collection of columns and rows
• DataRow represents a row in a DataTable object
• DataColumn represents a column in the DataTable object
• DataRelation class represents a relationship between two tables in the same DataSet. The relation is set on a common column
• DataView is defined on top of a table, it creates a filtered view of data. Can be configured to support editing and sorting. The data view is not a copy of the data - just a mask

Inheritance

INHERITANCE
• System.Object class is the root class of all the classes. All classes implicitly derive from the System.Object class
• A derived class automatically contains all fields from the base class. These field require initialization when an object is created
• Therefore the constructor for a derived class must call the constructor for its base class
• If base class constructor is not explicitly called, compiler does that automatically
• It is not possible to cast a child class object to another child class object even if they derive from same parent class, shown as under:
class Token // Base class
class IdentifierToken:Token //Child class1
class KeywordToken: Token //Child class2
IdentifierToken it = new IdentifierToken();
KeywordToken kt = it; // error - type conversion invalid
• Although converting to an object higher up in the hierarchy is allowed, hence following is legal
IdentifierToken it = new IdentifierToken();
Token t = it; // this is ok, as it is a child class object, deriving from Token

Params > Using Param Object

USING PARAMS OBJECT
• Use of params allows to pass an array of parameters of same type, params object allows to pass an array of objects as parameter, where every object can refer to a different type
• params object is an array of objects that are a type of System.Object
• params object can be used to declare a method that accepts any number of arguments of type System.Object where each element in the array is an object that may refer to a different type
• Declaration is as under:
class Black
{
public static void Hole(params object [] paramList)
}
• The method hole can be passed any number of objects, even no objects at all
• In case of no objects, a zero length object array is passed, shown as under:
Black.Hole(); // is interpreted as: Black.Hole(new object [0])
Black.Hole(null); // Being reference type, initializing to null is allowed
• Some sample code to call the Hole method as under:
object[] array = new object[2];
array[0] = “twenty three”;
array[1] = 23;
Black.Hole(array);
• Alternatively, Hole can be called passing parameters like any other method, as under:
Black.Hole(“forty two”, 42); // Black.Hole(new object[] {“forty two”, 42});

Params > Basics

USING PARAMS KEYWORD
• Params is used as an array parameter modifier
• Min method described above can bedeclared with params keyword as under:
• public static int Min(params int[] paramlist)
• With params specified, Min method can be called with variable number of parameters
• int min = Util.Min(3,4); or Util.Min(3,4,5,6);
• params keyword is allowed only on one dimensional arrays
• params keyword does not form a part of a signature, hence not be used for overloading
• params must be the last parameter
• A non-params method always takes priority over a params method

Array > Using Array As Argument

USING ARRAYS AS ARGUMENTS
• Arrays can be used as arguments with methods that take variable number of parameters
• A sample implementation as shown under:

class Util
{
public static int Min(int[] paramList)
{
if(paramList == null || paramList.Length == 0)
{ Throw new ArgumentException(“Util.Min”); }

int currentMin = paramList[0];
foreach(int i in paramlist)
{
if(i < currentmin)
{ currentmin = i; }


}
return currentmin;
}

}

• To use this method: int[] arrInt = new int[2,3,4]; int min = Util.Min(arrint);

SortedList

SORTEDLIST
• Similar to Hashtable, but sorts the data as it is inserted into the list
• Data is always sorted on the basis of key values
• Returns the DictionaryEntry object sorted on key values
• Declared as SortedList ages = new SortedList();

HashTable > Basics and Code Listing

HASHTABLE
• Hashtable maintains two object arrays, onefor keys and other for values
• When a Key-Value pair is inserted in Hashtable, it automatically tracks which key belongs to which value
• A Hashtable cannot contain duplicate keys, if Add method is called with a key already present, it will cause an excpetion
• Key’s presence can be tested by using ContainsKey method
• Using foreach to iterate a Hashtable returns a DictionaryEntry
• DictionaryEntry provides access to Key and Value elements
• Sample code as under:

using System;
using System.Collections;

Hashtable ages = new Hashtable();

ages[“John”] = 42;
ages[“Kathy”]=23;
ages[“Mary”]=12;

foreach(DictionaryElement in ages)
{
string name = (string)element.key;
int age = (int)element.key;
}

Stack

STACK
• Implements a Last-In-First-Out (LIFO) mechanism
• Element joins at top (push) and leaves from top (pop)
• Declared as Stack numbers = new Stack();
• To add a member, call push method numbers.Push(12);
• To remove a member, call pop method number.Pop();

Queue

QUEUE
• Queue implements a First In First Out - FIFO mechanism
• Element inserted at the back (enqueue) and removed from the front (dequeue)
• Declared as: Queue numbers = new Queue(10);
• Adding a member: numbers.Enqueue(10);
• Deleting a member: numbers.Dequeue
• Return the item from front: Peek
• Clear all items from Queue: Clear
• Find an item in Queue: Contains

ArrayList

ARRAYLIST (System.Collections)
• ArrayList is an advanced form of array that provides variety of methods to resize and alter the data it stores
• Better then Arrays that need to be recreated if its needed to resize them
• ArrayList provides Remove, Remove, Add etc. to insert or delete data
• Remove method, removes element by value, eg Remove(7) means remove the element that has the value 7
• RemoveAt method removes by index, RemoveAt(6) means remove element at location 6
• Declared as ArrayList arrList = new ArrayList();

Array > Copy and CopyTo Methods

EXPLORING Array.Copy AND Array.CopyTo METHODS
• System.Array class provides the methods to copy arrays: Copy, CopyTo, Clone
• CopyTo method copies the contents of one array to another, given a specified starting index
• Array.Copy is used as under:
int[] pins = {4,9,3,7};
int[] copy = new int[pins.Length];
pins.CopyTo(copy, 0);
• Copy method requires the target array to be initialized before the Copy call is made
• Use of Copy shown as under:
int[] pins = {4,9,3,7};
int[] copy = new int[pins.Length];
Array.Copy(pins, copy, copy.Length);
• Another method called Clone, allows to create a new array and copy it in one action
• Use of Clone is shown as under:
int[] pins = {4,9,3,7};
int[] copy = (int[])pins.Clone();

Array > Copying An Array

COPYING AN ARRAY
• Arrays are reference types. An array variable contains a reference to an array instance
• Hence, when a copy of an array variable is created, it means same array variable with two references
• This is shown as under:
• int[] pins = {3,6,9,12}; int[] alias = pins;
• Here, alias is not a separate array, but a reference to an array pointing to array called pins
• To create a copy of an array instance, two separate arrays must be declared with same data type and length. Finally, copy the values from one array into another
• This process is shown as under:
int[] pins = {9,3,7,2};
int[] copy = new int[pins.Length];

for(int i =0; i != copy.Length; i++)
copy[i] = pins[i];

ForEach Loop

EXPLORING foreach LOOP
• foreach statement always declares an iteration variable (int pin), that automatically acquires the value of each element in the array
• foreach always iterates through the whole array, hence for selective access, use for loop
• foreach always moves forward, from 0 to Length-1, hence to move backward, use for loop
• foreach provides read-only copy of array, for modifications trust for loop

Array > Iterating Through An Array

ITERATING THROUGH AN ARRAY
• Length property of System.Array tells the number of elements an array has
• An array can be iterated using for as well as foreach loop
• Sample code using for loop as under:
• int[] pins = {5,3,2,5};
for(int index = 0; index != pins.Length; index++)
{
int pin = pins[index]; Console.WriteLine(pin);
}
• Sample code using foreach loop
int[] pins = {5,3,2,1};
foreach(int pin in pins)
{ Console.WriteLine(pin); }

Array > Initializing Array Variables

INITIALIZING ARRAY VARIABLES
• When an array instance is created, all the elements are initialized to a default value depending on their type
• This behavior can be modified by providing a comma separated list of values like:
int[] arrayInt = new int[4]{1,2,3,4};
• And runtime initialization is also possible, like:
Random r = new Random();
int[] arrayInt = new int[2]{ r.Next()%10, r.Next()};
• Array of structs would look like: Time[] Schedule = {new Time(12, 30), new Time(5,30)};
• IndexOutOfRangeException is thrown if element outside the size of array is accessed/modified

Array > Basics

ARRAY (System.Array)
• An array variable is declared as : data_type[] array_name example: int[] arrayInt;
• Arrays are reference types, regardless of the type of their elements
• This means that an array variable refers to an array instance on the heap and does not hold its array elements directly on the stack
• When an array variable is declared, its size is not specified
• Size of array is specified only when an array instance gets created using new keyword
• An array variable is instantiated as: arrayInt = new int[4];
• Size of an array instance does not have to be constant, it can be calculated at run time
• Getting array size at run time:
int size = int.Parse(Console.ReadLine());
int arrayInt = new int[size];
• It is possible to create an array with size 0
• Multi-dimensional arrays can be created as: int[ , ] table = new[4, 6];

Sunday, August 19, 2007

Heap, Stack and CLR

MEMORY MANAGEMENT: VALUE v/s REFERENCE TYPES
• OS and runtimes often divide the memory used for holding the data into two separate chunks, each of which is managed in a distinct manner
• The two chunks of memory are traditionally called stack and heap
• The Stack and Heap serve different purposes:
o When a method is called, the memory required for its parameters and its local variables is always acquired from the stack
o When the method finishes (return value/throw exception), the memory acquired for the parameters and local variables is automatically released back to the stack and is available for reuse when another method is called
o When an object is created using the new keyword and a constructor call, the memory required to build the object is always acquired from the heap
o Same object can be referenced from several places by using reference variables. When the last reference to an object disappears, the memory used by the object disappears, the memory used by the object becomes available for reuse

CONECEPTS OF STACK AND HEAP
• Stack memory is organized like a stack of boxes piled on top of each other
• When a method is called, each parameter is put in a box, which is placed on top of the stack
• Each local variable likewise is assigned a box, and these are placed on top of the boxes already on the stack
• When a method finishes, all its boxes are removed from the stack
• Heap memory is like a large pile of boxes strewn around a room rather than stacked neatly on top of each other
• Each box has a label indicating whether it is in use or not
• When a new object is created, the runtime searches for an empty box and allocates it to the object
• The reference to the object is is stored in a local variable on the stack.
• The runtime keeps a track of the number of references to each box (important to remember that two variables can refer to the same object)
• When the last reference disappears, the runtime marks the box as not in use, and at some point in the future will empty the box and make it available for reuse
• IMPORTANT: Although the object itself is stored on the heap, the reference to the object is stored on the stack
• Heap memory is NOT infinite. If heap memory is exhausted, the new operator will throw OutOfMemoryException and the object will not be created

Monday, August 13, 2007

Boxing and Unboxing

BOXING AND UNBOXING
• Boxing and Unboxing enable value types to be treated as objects
• Boxing a value type packages it inside an instance of the Object reference type
• This allows the value type to be stored on the garbage collected heap
• Unboxing extracts the value type from an object

EXAMPLE OF BOXING
int i = 123;
object o = (object) i ;

EXAMPLE OF UNBOXING
object o;
o = 123;
i = (int)o;

Sunday, August 12, 2007

Reflection > Reflection and Late Binding

REFLECTION AND LATE BINDING
• Reflection provides infrastructure used by language compilers such as VB 2005 to implement implicit late binding
• Binding is the process of locating the declaration (that is, the implementation) that corresponds to a uniquely specified type
• When this process occurs at run time rather then at compile time, it is called late binding


CREATING NEW TYPES AT RUNTIME USING REFLECTION
• To create new types at runtime, System.Reflection and System.Reflection.Emit provides various types/methods
• Some important members are as under:


AssemblyName >> Used to specify the name
AssemblyBuilder >> AppDomain.CurrentDomain.DefineDynamicAssembly
ModuleBuilder >> Used to define module
AppDomain >> Has static methods like DefineDynamicAssembly
TypeBuilder >> Used to specify name of methods, the new type will have
MethodBuilder >> Define the access specifiers, parameters
ParameterBuilder >> Define the parameter in/out
ILGenerator >> Object of this is required for constructing new type
ILGenerator.Emit >> Passed OpCodes.Ldarg_1, Ldarg_2 parameters
TypeBuilder.CreateType() >> Called at last, to construct the Type

Reflection > Usage and Emit

REFLECTION
• Reflection provides objects (of type Type) that encapsulates assemblies, modules or types
• Type (Type is the name of a class), is the root of the System.Reflection functionality and primary way to access metadata
• Reflection can be used to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object
• Reflection also allows accessing Attributes
• Example of GetType method, this method is inherited by all types from the Object base class

int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

• Example that uses Reflection to obtain full name of a loaded assembly:

System.Reflection.Assembly o = System.Reflection.Assembly.Load(mscorlib.dll);
System.Console.WriteLine( o.GetName() );

USAGE SCENARIOS OF REFLECTION
• When accessing attributes in program’s metadata
• For accessing and instantiating types in an assembly
• For building new types at runtime, using classes in System.Reflection.Emit
• For performing late binding, accessing methods on types created at runtime

REFLECTION.EMIT
• The System.Reflection.Emit namespace contains classes that allow a compiler or a tool to emit metadata and MSIL and optionally generate a PE file on disk

NUnit > Basics

• NUnit is a unit testing framework for all .net languages
• Current production release is 2.4, it is open source and written in C#
• All test cases are built directly into the code of the project
• Nunit tests are grouped into a number of classes, called test fixtures
• A test fixture class is denoted by the [TestFixture] attribute
• Any class that contains tests must be marked with this attribute, so that Nunit can locate the tests
• All Nunit attributes reside in the Nunit.Framework namespace
• Nunit is built into Visual Studio, but the provided GUI program is also easy to use

[Test] public void Add()
{
double result = fvalue1 + fvalue2;
Assert.AreEqual(6, result, “Expected Result”);
}

• The Assert class contains many of the methods used to construct test cases, like: AreEqual(),AreSame(), IsTrue(), Fail()

• AreSame and AreEqual are different. AreSame checks if same objects are referenced by both objects being compared

[SetUp] and [TearDown] allow to initialize private members and cleanup code

• [ExpectedException] and [Ignore]: If a method is expected to throw exception, such a method is declared with the [ExpectedException], example as under:

[Test]
[ ExpectedException( typeof (InvalidOperationException) ) ]
public void ExceptAnException()
{
throw new InvalidCastException();
}

• Ignore attribute is to cause Nunit to skip a certain test case
• Example as under:

[Test]
[Ignore(“ ignored test ”)]pulic void IgnoredTest()
{
throw new Excpetion(); }}

Attributes in C# > Usage

USING ATTRIBUTES
• Attributes can be placed on almost any declaration, though an attribute might restrict the types of declarations on which it is valid

• An example of using attribute as under:
[ System.Runtime.InteropServices.DllImport( “user32.dll” ) ]
extern static void SampleMethod();


• Attributes can also have parameters, which can be either positional, unnamed or named

• Any positional parameters must be specified and can not be omitted

• Named parameters can be specified in any order and may be omitted

• In following example first parameter is positional, rest others are named and hence optional
[ DllImport(“user32.dll”, SetLastError = false, ExactSpelling = false )]

• More then one Attribute can be placed on a declaration

• Some attributes can be specified more then once for a given entity, such as Conditional

[ Conditional(“DEBUG”), Conditional(“TEST1”)]
void TraceMethod()
{ ... }

Attributes in C#

ATTRIBUTES IN C#
• Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties etc.)
• Once associated with a program entity, the attribute can be queried at run time using a technique called Reflection
• Attributes exist in two forms
1. Attributes that are defined in the CLR’s base class library
2. Custom attributes that are user created to add extra information to the code
• Attributes have following properties:
o Attributes add metadata to the program
o Metadata is information embedded in the program such as compiler instructions or descriptions of data
o A program can examine its own metadata using Reflection
o Attributes are commonly used when interacting with COM

Web Service > Consuming > Code Listing

CREATING A WEB SERVICE CLIENT
• Creating a client for the Web service in Visual Studio is same as creating a web application
• To use a web service, it is required to import the namespace, eg:
• using WebClient.localhost; WebClient is the name specified by the user to the web service
• Sample code that populates a GridView through DataSet returned by the web service

-----------------------------
using WebClient.localhost;

EmployeesService proxy = new EmployeesService();
proxy.Timeout = 3000; // 3 seconds
DataSet ds = null;

try
{
ds = proxy.GetEmployees();
}

catch(System.Net.WebException err)
{
if(err.Status == WebExceptionStatus.Timeout)
lblErr.Text=”Web Service Timed out”;
else
lblErr.Text=”Unknown Error occurred.”;
}
if(ds!=null)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
------------------------

Web Service > Consuming

WEB SERVICES: CREATING AND CONSUMING

• Web services should be stateless, they work on similar architecture as the web-page architecture
• Found in System.Web.Services.WebService
• A new web service object is created at the beginning of the request, and is destroyed after processing the request and returning the response
• To expose a web service a tag is required to be put on methods, these methods MUST BE PUBLIC
• Tag looks like: [WebMethod()]
• To make the web service visible, create an ASMX file and link it to the code-behind file containing exposed public web methods

CONSUMING THE WEBSERVICE
• In Visual Studio, add a web reference and select web service (specify URL to wsdl)
• Doing this generates a Proxy Class and is added in the project
• The proxy class has the same name as the web service class
• It inherits from SoapHttpClient Protocol, which has properties such as Credentials, URL, Timeout
• Declaration of Proxy Class looks as under:
public class EmployeeService:System.Web.Services.Protocols.SoapHttpClientProtocol
• The proxy contains a copy of each method in the web service
• However, it PROXY CLASS DOES NOT CONTAIN THE BUSINESS CODE
• Proxy just contains the code needed to query the remote web service and convert the results
• Example of proxy class contents:

[System.Web.Services.Protocols.SoapDocumentMethodAttribute()]
public int GetEmployeesCount()
{
object[] results = this.Invoke(“GetEmployeesCount”, new object[0]);
return ((int)(results[0]));
}

• This method calls the base SoapHttpClientProtocol.Invoke() to actually create the SOAP message and start waiting for the response

Page Life Cycle

PAGE LIFE CYCLE WITH EVENTS

START
• HTTPRuntime
• Global.asax is parsed and compiled.

PRE INIT
• Check for IsPostback.
• Create or recreate dynamic controls.
• Set the Master page dynamically.
• Set the StyleSheetTheme property.
• Set the Culture property.
• Read or set the Profile property values.

PAGE INITIALIZATION
• Page_Init
• Read or change Control properties.
• Setup handlers for events.
• Load external template files.
• Load Viewstate
• Load application persistent information to controls.
• Specify how ViewState is stored.
• Specify how ViewState is mapped to the internal state.

PAGE LOAD
Page_Load
If this is the page’s first time being processed, then perform initial databinding.
Read and update control properties.

VALIDATION
• Validate()
• Validate information assigned to validation controls

EVENT HANDLING
• Page_DataBinding() : Bind data sources to controls.
• Page_PreRender
• Make final modifications to the page
• Change the control tree structure.
• SaveViewState()

RENDERING
• Page_Render
• Make changes to the HTML of a page.
• Write text for controls on a page.

UNLOAD
• Page_Dispose
• Discard objects used in the page, including the Page object.
• Page_Unload
• Close open files.
• Close open database connections.
• Finish logging or other request-specific tasks.

Saturday, August 11, 2007

Data Binding > Single Value > Code Listing

Data Binding > Single Value Data Binding

Data Binding > $expressions

Data Binding > Repeated Value Data Binding

REPEATED VALUE BINDING
• RVB allows binding an entire list of information to a control
• This list of information is represented by a data object that wraps a collection of items
• This could be a collection of custom objects (ArrayList, HashTable) or a collection of rows (DataReader, DataSet)
• Various List Controls that support RVB are:
I. All controls which have a select tag: HtmlSelect, ListBox, DropDownList
II. CheckBox, RadioButton
III. Bulleted List Control
• Data properties of list controls are: DataSource, DataSourceID, DataTextField, DataTextFormatString, DataValueField

Page Life Cycle with Data Binding

PAGE LIFE CYCLE WITH DATA BINDING
• Data Controls on a page perform two key tasks:
I. RETRIEVE: They can retrieve data from a data source and supply it to linked controls
II. UPDATE: They can update the data source when edits take place in linked controls

• Hence a page life cycle with data controls present on the page is following:

1. The page object is created (based on the aspx file)
2. The page life cycle begins, and the Page.Init and Page.Load events fire
3. All other control events fire
4. The data source controls perform any updates. If a row is being updated, the Updating and Updated events fire, same for Insert operations and Deletion
5. The Page.PreRender event fires
6. The Data source controls perform any queries and insert the retrieved data in the linked controls. The Selecting and Selected events fire at this point
7. The page is rendered and disposed

Data Binding

DATA BINDING

• Data binding allows the developer to associate a data source to a control and have that control automatically display the data
• Data binding is declarative not programmatic
• Being Declarative means that Data Binding is defined outside the code, alongside the controls in the .aspx page
• In ASP.net, most of the web controls support single value data binding
• Single value Data Binding, developer can bind a control property to a data source, but the control can display only a single value
• Data Controls support Repeated Value binding, which means they expose data source property
• Repeated Value binding fills the data only when control’s DataBind method is called

ADO.net > Executing a Stored Procedure

STEPS IN EXECUTING A STORED PROCEDURE

• To execute a stored procedure in .net, Command object’s CommandType is set to CommandType.StoredProcedure

1. Objects required: SqlConnection, SqlCommand, SqlDataReader

2. Initialize the SqlConnection object passing it the Connection String
SqlConnection sqlConnection1 = new SqlConnection(“connectionString”);

3. Initialize the SqlCommand and SqlReader objects
SqlCommand cmd = new SqlCommand;
SqlDataReader reader;


4. Initialize the CommandText, CommandType and Connection properties of SqlCommand object
cmd.CommandText = “StoredProcedureName”;
cmd.Connection = sqlConnection1;
cmd.CommandType = CommandType.StoredProcedure;


5. Open the connection
sqlConnection1.Open();

6. Initialize the SqlDataReader object by calling ExecuteReader method on SqlCommand object
reader = cmd.ExecuteReader();

7. Close the connection
sqlConnection1.Close();

ADO.net > Performing Transactions

PERFORMING TRANSACTIONS IN ADO.NET
• Database transactions are used to control data commitment to databases
• ADO.net has three basic commands for transactions
1. BeginTransaction
2. Commit
3. Rollback

STEPS INVOLVED IN PERFORMING A DATABASE TRANSACTION

1. Objects required: SqlConnection, SqlCommand, SqlTransaction

2. Initialize SqlConnection object passing it the connection string
SqlConnection connection = new SqlConnection(“connection_string”);

3. Open the connection
connection.Open();

4. Initialize the SqlCommand by calling CreateCommand method of SqlConnection object
SqlCommand command = connection.CreateCommand();

5. Initialize the SqlTransaction object by calling BeginTransaction method of SqlConnection object
SqlTransaction transaction; transaction = connection.BeginTransaction(“transaction”);


6. Assign Connection and Transaction object to command object’s properties
command.Connection = connection; command.Transaction = transaction;

7. Assign Sql query string to CommandText property of SqlConnection object
connection.CommandText = “Insert into Region(col1,col2,col3) Values (c1Val,c2Val,c3Val)”;

8. Execute the query using SqlCommand object’s ExecuteNonQuery method
command.ExecuteNonQuery();

9. To commit the transaction, call Commit method of SqlTransaction object
transaction.Commit();

10. To rollback, call Rollback method of Transaction object
transaction.Rollback();

Friday, August 10, 2007

Steps in getting data from Database

1. Objects needed to retrieve data from Database: SqlConnection, SqlDataAdapter, DataSet

2. Instantiate SqlConnection object by passing it the ConnectionString
SqlConnection con = new SqlConnection(“connectionString”);

3. Open the connection using Open method of SqlConnection object
con.Open();

4. Instantiate DataSet object
DataSet ds = new DataSet();

5. Instantiate DataAdapter object by passing it the sql query and the connection object
SqlDataAdapter da = new SqlDataAdapter(“sqlQuery here”,con)

6. Call the Fill method of DataAdapter, passing it the DataSet object
da.Fill(ds);

7. Assign the DataSet object as Grid’s DataSource
Grid1.DataSource = ds;

8. Call the DataBind method of DataGrid
Grid1.DataBind();

Purpose behind using Interfaces

• Implementing an interface allows a class to become more formal about the behavior it promises to provide
• Interfaces form a contract between the class and the outside world, and the contract is enforced at build time by the compiler
• If a class implements an interface it must implement all the methods the implemented interface defines
• All the methods and properties defined in Interface are by default public and abstract

Design Pattern > Behavioural > Observer

• As an Object’s state changes, it is often necessary for other objects to be notified when this happens
• In C#, Delegates and Events are based on Observer pattern


Design Pattern > Structural > Iterator

ITERATOR PATTERN
• Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying operations
• In .net System.Collection assembly classes support all the functionality of the iterator pattern through a call to GetEnumerator(), which returns a concrete iterator, the Ienumerator interface

Design Pattern > Structural > Proxy

PROXY PATTERN
• Proxy is a way to “Provide a surrogate or placeholder for another object to control access to it..”
• Proxy helps in deferring creation of objects till not needed
• Use of Proxy means using a lightweight placeholder in lieu of expensive object

Design Pattern > Structural > Facade

FACADE PATTERN
• Provides a unified interface to a set of interfaces in a subsystem
• Facade defines a higher level interface that makes the subsystem easier to use
• Facade knows which subsystem classes are responsible for a request
• Delegates client requests to appropriate subsystem objects
• In coding prespective, Facade class holds objects of all the subsystems under it

Design Pattern > Creational > Factory



• A Factory Pattern is one that returns an instance of one of several possible classes depending on the data provided to it
• Usually all the classes it returns should have a common base class and common methods, but implementations of the methods may be different
• Following is an UML representation of the Factory Method Pattern. Note that no instances of Class derived1 or derived2 are directly created
• Factory class’ doIt() method is used to get the objects, and object type is determined on the basis of information passed to getObject() method

Design Pattern > Creational > Singleton

SINGLETON
• Singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application
• The Singleton Class is instantiated at the time of first access and the same instance is used thereafter till the application quits
• Singleton Class can be used in various places where one would need a common repository of information that can be accessed from all objects in an application
• For example sometimes only a single database connection object or network connection object may be needed by the application

Copy Constructor

COPY CONSTRUCTOR
• Copy Constructor is a Constructor that takes an instance of the class as its parameter and sets the data members to match the value of that instance
• C# does not provide a copy constructor

class Person
{
private string name;
private int age;

// Copy constructor.
public Person(Person previousPerson)
{
name = previousPerson.name;
age = previousPerson.age;
}




// Instance constructor.
public Person(string name, int age)
{
this.name = name;
this.age = age;
}

// Get accessor.
public string Details
{
get
{
return name + " is " + age.ToString();
}
}
}

class TestPerson
{
static void Main()
{
// Create a new person object.
Person person1 = new Person("George", 40);

// Create another new object, copying person1, using Copy Constructor
Person person2 = new Person(person1);
System.Console.WriteLine(person2.Details);
}
}

ArrayList > Clone v/s CopyTo

ARRAY LIST METHODS: CLONE v/s CopyTo
• ArrayList.Clone creates a shallow copy of the ArrayList
• ArrayList.CopyTo(Array), copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array

Shallow Copy v/s Deep Copy

DEEP COPY v/s SHALLOW COPY
• A shallow copy means the contents contains references to the same as the elements in the original array
• A shallow copy collection copies only the elements of the collection, whether they are reference types or value types
• It DOES NOT copy the objects that references refer to
• The references in the new collection point to the same objects that the references in the original collections point to
• In contrast, a deep copy of a collection copies the elements and everything directly or indirectly referenced by the elements

Thursday, August 9, 2007

Generics > Code Listing

CODE LISTING > GENERIC
public class Test< T >
{
public void Display()
{

}
}

At instantiation of this class, the generic has to be bound to any specific type:
Test< int > objTest = new Test< int >();

After instantiation, the object objText is a bound type.

IMPLEMENTING A GENERIC METHOD
using System;
using System.Collections.Generic;

class Test
{
static void Main( string[] args )
{
Test t = new Test();
int[] integerArray = {1,2,3,4,5,6};
char[] characterArray = { 'J', 'O', 'Y', 'D', 'I','P' };
double[] doubleArray = {0.1,0.2,0.3,0.4,0.5,0.6};
Console.WriteLine( "Displaying the contents of the integer array:--" );
t.Display(integerArray);
Console.WriteLine( "Displaying the contents of the character array:--" );
t.Display(characterArray);
Console.WriteLine( "Displaying the contents of the double array:--" );
t.Display(doubleArray);
}

public void Display< GenericArray >( GenericArray[] array )
{
for (int i = 0; i< array.Length; i++)
Console.WriteLine(array[i]);
}
}

Generics

GENERICS
• New feature in .net 2.0 and CLR
• Found in Namespace: System.Collections.Generic
• Generics are also called parameterized types or parameteric polymorphism
• Generics are a type of data structure that contain code that remains the same; however the data type of the parameters can change with each use
• Generic helps to defer the binding of a generic type to a data type until its point of usage arrives
• Generics introduce to the .net framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code
• Generics in C# support defining algorithms and deferring the data type until the point of use
• In a very general sense, a generic class is just a class that accepts parameters
• Generics allow strongly typed collections, hence letting the compiler do the type checking and hence preventing run time errors caused by type mismatch/casting
• Syntax: Without Generics: class List {} With Generics: class List
• Here T is the Type parameter, T gets defined when object if List is created, hence it can be List or List
• Hence, here T is instantiating at runtime

Nullable Types

NULLABLE TYPES
• Nullable types are instances of the System.Nullable struct
• A nullable type can represent the normal range of values for its underlying value type, plus an additional null value
• For example a Nullable can be assigned any value from -2147483647 to 2147483647, or it can be assigned a null value
• Same with type bool, which can take true, false and null
• Nullable is used while dealing with databases where element may not be assigned a value
• Syntax is: int? x = null or double? d = 4.108;
• To identify a nullable type: int? x = null; Type t = i.GetType(); Console.WriteLine(t.FullName);

ADO.net > DataSet > Typed DataSet

Typed Dataset

Typed datasets derive their schema (table and column structure) from .xsd files and are easier to program against

Typed Databases can be created using Data Source Configuration Wizard

A Typed Dataset is a Dataset that is first derived from the base DataSet class amd then uses information in an XSD file to generate a new class

Information from the schema (tables, columns..) is generated and compiled into this new DataSet class as a set of first class objects and properties

Because a Typed DataSet class inherits from the base DataSet class, the typed class assumes all of the functionality of the DataSet class can be used with methods that take an instance of a DataSet class as a parameter

An untyped dataset has no corresponding built-in schema

The class for a typed dataset has an object model in which its properties take on the actual names of tables and columns

Typed access is not only easier to read, but is fully supported by the IntelliSense in the Visual Studio Code Editor

Typed dataset is not recommended when schema is not available or in situations where structure of data is not static or predictable

Within a dataset, tables and column names are case insensitive, that is Customer and customer table are the same

This matches the default naming conventions of the databases where case does not differentiate the tables/columns

A strongly-typed schema is rigidly defined at compile time, while a loosely typed object, is the one whose schema is not known until runtime

DataReader and DataSet are loosely typed objects and since their schema is defined by the columns returned by the database query used to populate them

A Typed DataSet is a class generated by Visual Studio based on a database schema and whose members are strongly-typed according to this schema

The Typed DataSet itself consists of classes that extend the ADO.net DataSet, DataTable and DataRow classes

In addition to strongly-typed DataTables, Typed DataSets now also include TableAdapters, which are classes with methods for populating the DataSet’s Data Tables and propagating modifications within the Data Tables back to the database

Wednesday, July 25, 2007

ADO.net DataSet : Sort Data in a DataSet: DataView

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();

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
}

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();
}

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”

XML: Code Listing: XmlElement, XmlAttributeCollection

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

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]);
}
}
}
}