Feb 11, 2010

ASP.Net Page life cycle - simple overview

Page_Init - Initialization of the page
LoadViewState - Loading of the View State
LoadPostData - processing of the Post back data
Page_Load - Loading of Page
RaisePostDataChangedEvent - Notification of PostBack
RaisePostBackEvent - Handling of PostBack Event
Page_PreRender - Pre Rendering of Page
SaveViewState - Saving of view state
Page_Render - Rendering of Page
Page_UnLoad - Unloading of the Page

Difference between sqlserver 2000 and sqlserver 2005

- In SQL Server 2000 the Query Analyzer and Enterprise Manager are seperate,whereas in SQL Server 2005 both were combined as Management Studio.
- In Sql 2005,the new datatype XML is used,whereas in Sql 2000 there is no such datatype
- In Sql server2000 we can create 65,535 databases,whereas in Sql server2005 2(pow(20))-1 databases can be created.

Events in GridView control of ASP.NET

For Edit
void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex;
BindData();
}

//

For Cancel
void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
myGridView.EditIndex = -1;
BindData();
}

For Update
void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = myGridView.Rows[e.RowIndex];
if (row != null)
{
TextBox t = row.FindControl("TextBox1") as TextBox;
if (t != null)
{
Response.Write("The Text Entered is" + t.Text);
}
}

For Select
void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
// This will contain the selectedValue of the row
string selectedCategory = myGridView.SelectedRow.Cells[1].Text;
}

For paging
void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
myGridView.PageIndex = e.NewPageIndex;
BindData();
}

// In Datagrid
OnPageIndexChanged ="PageData"
protected void PageData(Object source, DataGridPageChangedEventArgs e )
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Binddata();
}

Delegates in C# - Simple Explanation

Delegates
=========

- also referred to as a type safe function pointer
- Improves the performance an application
- Used to call a method asynchronously
- You should follow the same syntax as in the method
- Example on multicast delegates:
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y)
{
Console.WriteLine("You r in Method 1");
}

static void Method2(int x, int y)
{
Console.WriteLine("You r in Method 2");
}

public static void "on" />Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}

Difference between abstract classes and interfaces in C#

Abstract Classes

- In abstract class a method must be declared as abstract
- For abstract methods there will be no body
- The Abstract methods can delare with Access modifiers(public,internal,protected etc)But when implementing in subclass same access modifier we have to use.
- The Abstract class can contain variables and concrete methods
- Multiple inheritance is not possible
- must and should call all the abstract methods in the derived class
- To implement abstract method in derived class we have to use override keyword
- The accessmodifiers and return types(like void,int etc) must be same in abstract method and in derived class method
- we cannot create an object to abstract classes


Interfaces

- For interface methods also there will be no body
- In Interfaces we cannot use any access modifiers.By default these methods are public.
- We cannot declare variables and concrete methods in interfaces
- Multiple inheritance is possible
- must and should call all the interface methods in the derived class
- To implement interface methods in derived class no need of override keyword
- The accessmodifiers and return types(like void,int etc) must be same in interface methods and in derived class methods
- we cannot create an object to interfaces

Feb 10, 2010

Using unsafe code in C# in easy manner

class ClassName
{

//pointer

unsafe int * ptr;

unsafe void MyMethod()
{
//you can use pointers here
}

}

To declare unsafe local variables in a method, you have to put them in unsafe blocks as the following:

static void Main()
{

//can't use pointers here

unsafe

{

//here you can declare and use pointer

}

//can't use pointers here
}

Example
=======

static void Main()
{

int var1 = 5;

unsafe
{

int * ptr1, ptr2;

ptr1 = &var1;

ptr2 = ptr1;

*ptr2 = 20;

}

Console.WriteLine(var1);
}

OUTPUE: 20

Feb 1, 2010

ADO.NET basics reference

- ADO.NET objects - Connection, Command, DataSet, DataReader, DataAdapter

- DataSet consists of a collection of tables, relationships, and constraints

- The GetChanges method of the DataSet object actually creates a second DataSet that contains only the changes to the data. This DataSet is then used by a DataAdapter (or other objects) to update the original data source.

- DataAdapter object works as a bridge between the DataSet and the source data(database)

- DataReader for forwardonly and readonly stream of data

- DataAdapter updates the data from dataset to Database using update, insert, delete command or by using SqlCommandBuilder which automatically generates the update commands.(Example4)

- SqlDataAdapter manages the connection itself, meaning it opens the connection and it closes the connection. If you
open the connection yourself, it detects this and it will not close the connection. You need to close the connection manually.

- SqlDataAdapter attach error messages to rows in a dataset by using RowError property(Example5). Then you can walk the error in a DataTable with the GetErrors() method. You can also test for errors using HasErrors.

- use RejectChanges on the DataSet, in which case the Row is restored.

- The SqlDataAdapter and SqlCommand are very similar, except for the Fill and Update methods. The Fill method fills the dataset, Update method takes changes from a DataSet and pushes them back into the database. This is accomplished by four commands specified on the DataAdapter. These commands are: SelectCommand, UpdateCommand, InsertCommand, and DeleteCommand. CommandBuilder object can generate these at run time based on a select statement. However, this run-time generation requires an extra round trip to the server to gather required metadata, so explicitly providing the insert, update, and delete commands at design time will result in better run-time performance.

- Filter Dataset using its select method
Ex: ds.Select("custname like 'Sri%'");


- Example1:

SqlConnection con=new SqlConnection(constring);
SqlCommand com=new SqlCommand();
SqlTransaction trans;
con.open();
com.Connection=con;
//Begin Transaction
trans=con.BeginTransaction();
com.Transaction=trans;
try
{
com.CommandText = "Delete from emp where empid=10";
com.ExecuteNonQuery();
com.CommandText = "Insert into emp(empid) values(10)";
com.ExecuteNonQuery();
trans.Commit();
}
catch(Exception e)
{
trans.Rollback();
}
finally
{
con.Close();
}

- Example2:

// Example using stored procedures-create, drop, in and out parameters
string spsql1="create procedure proc_name @name nchar(10), @id int out as select @id=empid from emp where empname=@name";
string spsql2="IF EXISTS ( select name from sysobjects where name='proc_name' and type='P') DROP PROCEDURE proc_name";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(spsql1,con);
SqlCommand com2=new SqlCommand(spsql2,con);
com2.ExecuteNonQuery();
com1.ExecuteNonQuery();

SqlCommand com3=new SqlCommand("proc_name",con);
com3.CommandType=CommandType.StoredProcedure;

SqlParameter params=null;
params=com3.Parameters.Add("@name", SqlDbType.NChar, 10);

// By default the parameter direction is input. So no need to specify the below statement.
params.Direction = ParameterDirection.Input;
com3.Parameters["@name"].value="ABCD";

params=com3.Parameters.Add("@id", SqlDbType.Int, 10);
params.Direction=ParameterDirection.Output;

com3.ExecuteNonQuery();

Console.WriteLine(com3.Parameters["@id"].value);
}
Catch(Exception e)
{

}
finally
{
con.Close();
}

- Example3:
//using dataset
string sqlstr="select * from emp";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(sqlstr,con);
SqlDataAdapter sa=new SqlDataAdapter(com1);
DataSet ds = new DataSet();
// we can use directly SqlDataAdapter as
// SqlDataAdapter sa=new SqlDataAdapter(sqlstr,con);
sa.fill(ds,"Emp");
foreach (DataRow dr in ds.Tables["Emp"].Rows)
{
Console.WriteLine(dr["empid"].ToString());
}
}
catch(Exception e)
{

}

- Example4:
//update using SqlDataAdapter and SqlCommandBuilder
string sqlstr1="select * from emp";
string sqlstr2="select * from dept";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(sqlstr1,con);
SqlCommand com2=new SqlCommand(sqlstr2,con);
SqlDataAdapter sa1=new SqlDataAdapter(com1);
SqlDataAdapter sa2=new SqlDataAdapter(com2);
DataSet ds = new DataSet();
DataRow dr;

// Create command builder. This line automatically generates the update commands for you, so you don't
// have to provide or create your own.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(sa1);

// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
sa1.MissingSchemaAction = MissingSchemaAction.AddWithKey;
sa2.MissingSchemaAction = MissingSchemaAction.AddWithKey;


sa1.fill(ds,"Emp");
sa2.fill(ds,"Dept");

// ADD RELATION
ds.Relations.Add("empdept", ds.Tables[0].Columns["empid"], ds.Tables[1].Columns["empid"]);

// EDIT
ds.Tables[0].Rows[0]["empname"] = "Pinkoo";

// ADD
dr=ds.Tables[0].NewRow();
dr["empid"]=10;
dr["empname"]="simpy";
ds.Tables[0].Rows.Add(dr);

//Update Database with SqlDataAdapter
da1.Update(ds,"Emp");

}
catch(Exception e)
{

}

-Example5:
// Create a new dataview instance on the emp table that was just created
DataView myDataView = new DataView(myDataSet.Tables["emp"]);
// Sort the view based on the empname column
myDataView.Sort = "empname";
myDataSet.Tables["emp"].Rows[0].RowError = "An Error was added";
myDataSet.Tables["emp"].Rows[1].RowError = "This is another error message";
if (myDataSet.Tables["Customers"].HasErrors)
{
DataRow[] ErrDataRows = myDataSet.Tables["emp"].GetErrors();
for (int i = 0; i <= ErrDataRows.Length - 1; i++)
{
}
}

-Example6:
//using Relations in a dataset
string sqlstr1="select * from emp";
string sqlstr2="select * from dept";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(sqlstr1,con);
SqlCommand com2=new SqlCommand(sqlstr2,con);
SqlDataAdapter sa1=new SqlDataAdapter(com1);
SqlDataAdapter sa2=new SqlDataAdapter(com2);
DataSet ds = new DataSet();

sa1.fill(ds,"Emp");
sa2.fill(ds,"Dept");

// ADD RELATION
ds.Relations.Add("empdept", ds.Tables[0].Columns["empid"], ds.Tables[1].Columns["empid"]);

foreach (DataRow dr1 in ds.Tables[0].Rows)
{
//access dr1["empid"]
foreach (DataRow dr2 in dr1.GetChildRows(ds.Relations["empdept"]))
{
//access dr2["deptid"]
}
}