SqlBulkCopy Use for Insert Bulk Data into sql server.You have to create one table inside the sql server and create only structure of the table which we have in Excel .and Use the code Below.
//File upload pick the file name and Details is a sheet name Inside the .Xls file
DataTable dt = new DataTable();
protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+FileUpload1.PostedFile.FileName +";Extended Properties=Excel 8.0; ");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Details$] ", con);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
InsertBulkDATA();
}
private void InsertBulkDATA()
{
SqlBulkCopy sbc = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
sbc.DestinationTableName = "tblData";
sbc.WriteToServer(dt);
}
Monday, February 28, 2011
Saturday, February 26, 2011
Hosting WCF Services in IIS
This is the link which will describe how to Host wcf services in IIS
http://www.youtube.com/watch?v=mX8quq7MoeI&feature=related
http://www.youtube.com/watch?v=mX8quq7MoeI&feature=related
Labels:
Hosting WCF Services in IIS
WCF Implementation(for retrieve Data and match the data for login)
File---> New WEBSITE---->WCF SERVICES
we have Iservice.cs Interface and second is Service.cs Class
Inside the Iservice.cs (Interface) we have to define one interface for that.(that will be accessible with other application)
[OperationContract]
DataTable GetUserId();
second is....Service.cs Class give the method body which we create interface...
}
public DataTable GetUserId()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
string cmd = "select Name from customer";
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
after that Build the website....
///////Use service with other application.....
create new website
Add services with your application :- Right click on solution explorer there is Add Service Reference select your services otherwise paste the url of service and ok .
////Inside the button click u can acces use that....
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
con.Open();
DataTable ds = new DataTable();
ds = objService.GetUserId();
if (ds.Rows.Count > 0)
{
foreach (DataRow item in ds.Rows)
{
string id = item["name"].ToString();
if (id == textUserId.Text)
{
lblMessage.Text = "Valid";
break;
}
else
lblMessage.Text = "InValid";
}
}
}
///////want to use same application.........
Right click on solution explorer on same website and click on AddNewItem pick NewForm ...
Inside new form ..............
Add services with your application :- Right click on solution explorer there is Add Service Reference select your services otherwise paste the url of service and ok .
protected void Button1_Click(object sender, EventArgs e)
{
Service sf = new Service();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
con.Open();
DataTable ds = new DataTable();
ds = sf.GetUserId();
if (ds.Rows.Count > 0)
{
foreach (DataRow item in ds.Rows)
{
string id = item["name"].ToString();
if (id == textUserId.Text)
{
lblMessage.Text = "Valid";
break;
}
else
lblMessage.Text = "InValid";
}
}
}
we have Iservice.cs Interface and second is Service.cs Class
Inside the Iservice.cs (Interface) we have to define one interface for that.(that will be accessible with other application)
[OperationContract]
DataTable GetUserId();
second is....Service.cs Class give the method body which we create interface...
}
public DataTable GetUserId()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
string cmd = "select Name from customer";
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
after that Build the website....
///////Use service with other application.....
create new website
Add services with your application :- Right click on solution explorer there is Add Service Reference select your services otherwise paste the url of service and ok .
////Inside the button click u can acces use that....
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
con.Open();
DataTable ds = new DataTable();
ds = objService.GetUserId();
if (ds.Rows.Count > 0)
{
foreach (DataRow item in ds.Rows)
{
string id = item["name"].ToString();
if (id == textUserId.Text)
{
lblMessage.Text = "Valid";
break;
}
else
lblMessage.Text = "InValid";
}
}
}
///////want to use same application.........
Right click on solution explorer on same website and click on AddNewItem pick NewForm ...
Inside new form ..............
Add services with your application :- Right click on solution explorer there is Add Service Reference select your services otherwise paste the url of service and ok .
protected void Button1_Click(object sender, EventArgs e)
{
Service sf = new Service();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
con.Open();
DataTable ds = new DataTable();
ds = sf.GetUserId();
if (ds.Rows.Count > 0)
{
foreach (DataRow item in ds.Rows)
{
string id = item["name"].ToString();
if (id == textUserId.Text)
{
lblMessage.Text = "Valid";
break;
}
else
lblMessage.Text = "InValid";
}
}
}
Thursday, February 24, 2011
WCF Introduction
//This is the link for Understand the End Point.
http://www.youtube.com/watch?v=GC344FZeWqc&feature=related
Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
WCF services provide better reliability and security in compared to ASMX web services.
In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
EndPoint:---WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components. 1)Address 2)Binding 3)CONTRACT
1) Address:- Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
2) Binding:- Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client.
Simple definition for Binding describes how the client will communicate with service. We can understand with an example.
Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
EX:- endpoint address="http://localhost:8090/MyService/MathService.svc"
contract="IMathService"
binding="wsHttpBinding"/>
endpoint address="net.tcp://localhost:8080/MyService/MathService.svc"
contract="IMathService"
binding="netTcpBinding"/>
3)cONTRACT:- Collection of operation that specifies what the endpoint will communicate with outside world.In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF.......
Service Contract :-Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.
Data Contract :- Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.
Message Contract :-Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
Fault Contract :- Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client
http://www.youtube.com/watch?v=GC344FZeWqc&feature=related
Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
WCF services provide better reliability and security in compared to ASMX web services.
In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
EndPoint:---WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components. 1)Address 2)Binding 3)CONTRACT
1) Address:- Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
2) Binding:- Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client.
Simple definition for Binding describes how the client will communicate with service. We can understand with an example.
Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
EX:- endpoint address="http://localhost:8090/MyService/MathService.svc"
contract="IMathService"
binding="wsHttpBinding"/>
endpoint address="net.tcp://localhost:8080/MyService/MathService.svc"
contract="IMathService"
binding="netTcpBinding"/>
3)cONTRACT:- Collection of operation that specifies what the endpoint will communicate with outside world.In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF.......
Service Contract :-Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.
Data Contract :- Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.
Message Contract :-Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
Fault Contract :- Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client
Labels:
WCF Introduction
Application Pool and Application Domain? What is the difference between the two.
1)Application pool is a grouping of URLs that is routed to one or more worker processes.
2)An application pool is a group of one or more URLs of different Web applications and Web sites. Any Web directory or virtual directory can be assigned to an application pool.
Every application within an application pool shares the same worker process executable, W3wp.exe, the worker process that services one application pool is separated from the worker
process that services another [Like starting MS Word and opening many word documents]. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This
ensures that if a worker process fails, it does not affect the applications running in other application pools. [i.e] for Eg., If word document is having issue it should not
logically affect your Excel Sheet isn’t it. application domain is a mechanism (similar to a process in an operating system) used to isolate executed software applications from one another so that they do not affect each other. [i.e] opening of MS WORD doesn’t affect MS EXCEL
you can open and close both the applications any time since there is no dependency between the applications. Each application domain has its own virtual address space which scopes the resources for the application domain using that address space.
2)An application pool is a group of one or more URLs of different Web applications and Web sites. Any Web directory or virtual directory can be assigned to an application pool.
Every application within an application pool shares the same worker process executable, W3wp.exe, the worker process that services one application pool is separated from the worker
process that services another [Like starting MS Word and opening many word documents]. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This
ensures that if a worker process fails, it does not affect the applications running in other application pools. [i.e] for Eg., If word document is having issue it should not
logically affect your Excel Sheet isn’t it. application domain is a mechanism (similar to a process in an operating system) used to isolate executed software applications from one another so that they do not affect each other. [i.e] opening of MS WORD doesn’t affect MS EXCEL
you can open and close both the applications any time since there is no dependency between the applications. Each application domain has its own virtual address space which scopes the resources for the application domain using that address space.
Wednesday, February 23, 2011
sql server funcation Return Table (User Defined Function)
create function fun(@id int)
returns table
as
return (select name from students where id=@id)
//How to use in sql server
select * from master.dbo.fun(1);
////how to use in asp.net
con.open();
SqlCommand cmd = new SqlCommand("select name from schools.dbo.fun(3)", con);
SqlDataReader dr2 = cmd.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
string s= dr2.GetString(0);
}
}
con.close();
///another Function return string
CREATE FUNCTION GetFullName()
RETURNS varchar(100)
AS
BEGIN
RETURN 'Doe, John'
END
//how to use function in sql server
PRINT Schools.dbo.GetFullName();
returns table
as
return (select name from students where id=@id)
//How to use in sql server
select * from master.dbo.fun(1);
////how to use in asp.net
con.open();
SqlCommand cmd = new SqlCommand("select name from schools.dbo.fun(3)", con);
SqlDataReader dr2 = cmd.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
string s= dr2.GetString(0);
}
}
con.close();
///another Function return string
CREATE FUNCTION GetFullName()
RETURNS varchar(100)
AS
BEGIN
RETURN 'Doe, John'
END
//how to use function in sql server
PRINT Schools.dbo.GetFullName();
Ajax Help for Designing any pages(Source Code)
www.dynamicdrive.com/
//download ajax .dll(AjaxControlToolkit.dll) and Add it into your project....
after that add the @Register directive: @Register Directive use for informs the compiler of any custom server control add to the page..
%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
after that use the Reference Link " www.dynamicdrive.com/ "
//download ajax .dll(AjaxControlToolkit.dll) and Add it into your project....
after that add the @Register directive: @Register Directive use for informs the compiler of any custom server control add to the page..
%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
after that use the Reference Link " www.dynamicdrive.com/ "
HTML REPORT and Print the Html Report
//Take one Input Button for Print
input type="button" id="btnPrint" runat="server" value ="Print" onclick ="PrintReport();"/>
//Make one method for print
script type="text/javascript" language="javascript" >
function PrintReport() {
var bt = document.getElementById("btnPrint").style.display='block';
window.print()
}
/script>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ con.open();
SqlCommand cmd = new SqlCommand("select * from students", con);
SqlDataReader oDr = cmd.ExecuteReader();
if (oDr.HasRows)
{
StringBuilder sb = new StringBuilder();
sb.Append("");
sb.Append("
");
Response.Write(sb);
con.close();
}
}
}
input type="button" id="btnPrint" runat="server" value ="Print" onclick ="PrintReport();"/>
//Make one method for print
script type="text/javascript" language="javascript" >
function PrintReport() {
var bt = document.getElementById("btnPrint").style.display='block';
window.print()
}
/script>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ con.open();
SqlCommand cmd = new SqlCommand("select * from students", con);
SqlDataReader oDr = cmd.ExecuteReader();
if (oDr.HasRows)
{
StringBuilder sb = new StringBuilder();
sb.Append("
Financial Report | ||
---|---|---|
"); sb.Append("id".ToString()); sb.Append(" | ");
sb.Append(""); sb.Append("Name".ToString()); sb.Append(" | ");
sb.Append(""); sb.Append("Roll".ToString()); // finish the rest of the row sb.Append(" |
"); sb.Append(oDr["id"].ToString()); sb.Append(" | ");
sb.Append(""); sb.Append(oDr["Name"].ToString()); sb.Append(" | ");
sb.Append(""); sb.Append(oDr["Roll"].ToString()); // finish the rest of the row sb.Append(" |
Response.Write(sb);
con.close();
}
}
}
Three Tier Insert and Retrieve Data(Using Singleton for SqlConnection only)
Application layer(PL) :- is the form where we design using the controls like textbox, labels, command buttons etc.
Business layer(BAL) :- is the class where we write the functions which get the data from the application layer and passes through the data access layer.BAL contains business logic, validations or calculations related with the data, if needed.
Data layer(DAL) :- is also the class which gets the data from the business layer and sends it to the database or gets the data from the database and sends it to the business layer.
Property layer(BE) :- is the sub layer of the business layer in which we make the properties to sent or get the values from the application layer. These properties help to sustain the value in a object so that we can get these values till the object destroy.
////// SQL HELPER CLASS(Inside the DAL Make sql Helper class) for connection string........
public class sqlHelper
{
private static SqlConnection connection = null;
public static SqlConnection conn
{
get
{
if (connection == null)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolsConnectionString"].ConnectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
return connection;
}
}
public static void closeconn(SqlConnection connection)
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
///////// DAL(Data Access Layer) CLASS LIBRARY..............
Using BE; //ADD REFERENCE OF BE
public class DAL
{
public int InsertDal(BE.BE obBe)
{
try
{
SqlCommand cmd = new SqlCommand("Insert_Student", sqlHelper.conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Name", obBe.Name);
cmd.Parameters.AddWithValue("Roll", obBe.Roll);
return cmd.ExecuteNonQuery();
}
catch
{
sqlHelper.closeconn(sqlHelper.conn);
throw;
}
finally
{
sqlHelper.closeconn(sqlHelper.conn);
}
}
public DataSet BindDal()
{
try
{
SqlCommand cmd = new SqlCommand("Bind", sqlHelper.conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
catch
{
sqlHelper.closeconn(sqlHelper.conn);
throw;
}
finally
{
sqlHelper.closeconn(sqlHelper.conn);
}
}
}
/////////// BAL(Business Access Layer) CLASS LIBRARY....................
Using DAL;
Using BE;
public class BAL
{
DAL.DAL obDal = new DAL.DAL();
public int InsertBal(BE.BE obBe)
{
try
{
return obDal.InsertDal(obBe);
}
catch { throw; }
}
public DataSet BindBal()
{
try
{
return obDal.BindDal();
}
catch { throw; }
}
}
////// BE(Business Entity) CLASS LIBRARY.............(Property)
public class BE
{
private int _Id;
private string _Name = string.Empty;
private int _roll;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public int Roll
{
get { return _roll; }
set { _roll = value; }
}
}
/////////// PL(Persentation Layer).aspx Page
using BE;
using BAL;
BAL.BAL OBbAL = new BAL.BAL ();
BE.BE obBe = new BE.BE();
//Retrieve the value
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = OBbAL.BindBal();
GridView1.DataBind();
}
}
//Insert the value
protected void btnInsert_Click(object sender, EventArgs e)
{
obBe.Name =TextBox1.Text.Trim().Replace(",","''");
obBe.Roll =Convert.ToInt32(TextBox2.Text.Trim().Replace(",","''"));
OBbAL.InsertBal(obBe);
TextBox1.Text = "";
TextBox2.Text = "";
}
Business layer(BAL) :- is the class where we write the functions which get the data from the application layer and passes through the data access layer.BAL contains business logic, validations or calculations related with the data, if needed.
Data layer(DAL) :- is also the class which gets the data from the business layer and sends it to the database or gets the data from the database and sends it to the business layer.
Property layer(BE) :- is the sub layer of the business layer in which we make the properties to sent or get the values from the application layer. These properties help to sustain the value in a object so that we can get these values till the object destroy.
////// SQL HELPER CLASS(Inside the DAL Make sql Helper class) for connection string........
public class sqlHelper
{
private static SqlConnection connection = null;
public static SqlConnection conn
{
get
{
if (connection == null)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolsConnectionString"].ConnectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
return connection;
}
}
public static void closeconn(SqlConnection connection)
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
///////// DAL(Data Access Layer) CLASS LIBRARY..............
Using BE; //ADD REFERENCE OF BE
public class DAL
{
public int InsertDal(BE.BE obBe)
{
try
{
SqlCommand cmd = new SqlCommand("Insert_Student", sqlHelper.conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Name", obBe.Name);
cmd.Parameters.AddWithValue("Roll", obBe.Roll);
return cmd.ExecuteNonQuery();
}
catch
{
sqlHelper.closeconn(sqlHelper.conn);
throw;
}
finally
{
sqlHelper.closeconn(sqlHelper.conn);
}
}
public DataSet BindDal()
{
try
{
SqlCommand cmd = new SqlCommand("Bind", sqlHelper.conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
catch
{
sqlHelper.closeconn(sqlHelper.conn);
throw;
}
finally
{
sqlHelper.closeconn(sqlHelper.conn);
}
}
}
/////////// BAL(Business Access Layer) CLASS LIBRARY....................
Using DAL;
Using BE;
public class BAL
{
DAL.DAL obDal = new DAL.DAL();
public int InsertBal(BE.BE obBe)
{
try
{
return obDal.InsertDal(obBe);
}
catch { throw; }
}
public DataSet BindBal()
{
try
{
return obDal.BindDal();
}
catch { throw; }
}
}
////// BE(Business Entity) CLASS LIBRARY.............(Property)
public class BE
{
private int _Id;
private string _Name = string.Empty;
private int _roll;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public int Roll
{
get { return _roll; }
set { _roll = value; }
}
}
/////////// PL(Persentation Layer).aspx Page
using BE;
using BAL;
BAL.BAL OBbAL = new BAL.BAL ();
BE.BE obBe = new BE.BE();
//Retrieve the value
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = OBbAL.BindBal();
GridView1.DataBind();
}
}
//Insert the value
protected void btnInsert_Click(object sender, EventArgs e)
{
obBe.Name =TextBox1.Text.Trim().Replace(",","''");
obBe.Roll =Convert.ToInt32(TextBox2.Text.Trim().Replace(",","''"));
OBbAL.InsertBal(obBe);
TextBox1.Text = "";
TextBox2.Text = "";
}
Tuesday, February 22, 2011
Indexer in c#
//Indexer in c#
C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community.
Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.
Indexer is a collection of SET and GET methods.
Indexer name must be "this".
One class can have only one indexer.
Indexer Concept is object act as an array.
Indexers in C# must have at least one parameter.
Else the compiler will generate a compilation error.
indexers are never static in C#.
Benefits:-
Indexers always need an object reference to assign or retreive data from arrays or collections.
The following is syntax
this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
//Example
class IndexerClass
{
private string[] names = new string[10];
public string this[int i]
{
get
{
return names[i];
}
set
{
names[i] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass text = new IndexerClass();
text[0] = "subhash";
text[1] = "subhash1";
text[2] = "subhash2";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(text[i]);
}
Console.ReadKey();
}
C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community.
Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.
Indexer is a collection of SET and GET methods.
Indexer name must be "this".
One class can have only one indexer.
Indexer Concept is object act as an array.
Indexers in C# must have at least one parameter.
Else the compiler will generate a compilation error.
indexers are never static in C#.
Benefits:-
Indexers always need an object reference to assign or retreive data from arrays or collections.
The following is syntax
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
//Example
class IndexerClass
{
private string[] names = new string[10];
public string this[int i]
{
get
{
return names[i];
}
set
{
names[i] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass text = new IndexerClass();
text[0] = "subhash";
text[1] = "subhash1";
text[2] = "subhash2";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(text[i]);
}
Console.ReadKey();
}
Create Xml File and Append the Existing Xml file
Using System.Xml;
Make one Cofiguration Folder Inside make that .xml file.
protected void btnGeneratexmlfile_Click(object sender, EventArgs e)
{
string type = "new";
Int32 queryid;
string FilePath = Request.PhysicalApplicationPath + @"Configuration\" + "QueryMaster.xml";
string SouPath = Request.PhysicalApplicationPath + "Configuration";
StringBuilder _UserInfo = new StringBuilder();
if (File.Exists(FilePath) == true)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load (FilePath);
XmlNode xmlNode = xmlDoc.SelectSingleNode("//querytrans");
if (type == "new")
queryid = 1000 + xmlNode.ChildNodes.Count + 1;
String Query = "trans type=\"new\" bookid=\"1\" assetid=\"35\" queryid=\"6\" byuserid=\"5\" byroleid=\"1\" touserid=\"4\" toroleid=\"9\" transdate=\"" + DateTime.Now.ToString() + "\"> ![CDATA[" + 12 + "]]> /trans>";
xmlNode.InnerXml = xmlNode.InnerXml + Query;
File.SetAttributes(FilePath, FileAttributes.Normal);
xmlDoc.Save(FilePath);//Append the xml file
}
else//if file not exist
{
_UserInfo.Append("?xml version=\"1.0\" encoding=\"utf-8\" ?>");
_UserInfo.Append("querytrans>");
_UserInfo.Append("/querytrans>");
StreamWriter _sw = new StreamWriter(SouPath + "\\QueryMaster.xml");
_sw.WriteLine(_UserInfo.ToString());
_sw.Flush();
_sw.Close();
_sw.Dispose();
}
}
Make one Cofiguration Folder Inside make that .xml file.
protected void btnGeneratexmlfile_Click(object sender, EventArgs e)
{
string type = "new";
Int32 queryid;
string FilePath = Request.PhysicalApplicationPath + @"Configuration\" + "QueryMaster.xml";
string SouPath = Request.PhysicalApplicationPath + "Configuration";
StringBuilder _UserInfo = new StringBuilder();
if (File.Exists(FilePath) == true)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load (FilePath);
XmlNode xmlNode = xmlDoc.SelectSingleNode("//querytrans");
if (type == "new")
queryid = 1000 + xmlNode.ChildNodes.Count + 1;
String Query = "trans type=\"new\" bookid=\"1\" assetid=\"35\" queryid=\"6\" byuserid=\"5\" byroleid=\"1\" touserid=\"4\" toroleid=\"9\" transdate=\"" + DateTime.Now.ToString() + "\"> ![CDATA[" + 12 + "]]> /trans>";
xmlNode.InnerXml = xmlNode.InnerXml + Query;
File.SetAttributes(FilePath, FileAttributes.Normal);
xmlDoc.Save(FilePath);//Append the xml file
}
else//if file not exist
{
_UserInfo.Append("?xml version=\"1.0\" encoding=\"utf-8\" ?>");
_UserInfo.Append("querytrans>");
_UserInfo.Append("/querytrans>");
StreamWriter _sw = new StreamWriter(SouPath + "\\QueryMaster.xml");
_sw.WriteLine(_UserInfo.ToString());
_sw.Flush();
_sw.Close();
_sw.Dispose();
}
}
HTML Report in c# .Net
//Blog does not take starting tag of the html.....please write all starting tag and end tag before each table tag,th tag and tr tag and td tag and closing tag...
protected void btnHtmlkReport_Click(object sender, EventArgs e)
{
conn.open();
SqlCommand cmd = new SqlCommand("select * from students", conn);
SqlDataReader oDr = cmd.ExecuteReader();
if (oDr.HasRows)
{
StringBuilder sb = new StringBuilder();
sb.Append("table align='center'>");
sb.Append("tr> td > th>Financial Report /th>/td>/tr>");
sb.Append("tr>td align='center'>");
sb.Append("id".ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append("Name".ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append("Roll".ToString());
// finish the rest of the row
sb.Append("");
// get your data
while (oDr.Read())
{
sb.Append("tr>td align='center'>");
sb.Append(oDr["id"].ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append(oDr["Name"].ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append(oDr["Roll"].ToString());
// finish the rest of the row
sb.Append("/td>/tr>");
}
sb.Append("/table>");
Response.Write(sb);
con.close();
}
}
protected void btnHtmlkReport_Click(object sender, EventArgs e)
{
conn.open();
SqlCommand cmd = new SqlCommand("select * from students", conn);
SqlDataReader oDr = cmd.ExecuteReader();
if (oDr.HasRows)
{
StringBuilder sb = new StringBuilder();
sb.Append("table align='center'>");
sb.Append("tr> td > th>Financial Report /th>/td>/tr>");
sb.Append("tr>td align='center'>");
sb.Append("id".ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append("Name".ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append("Roll".ToString());
// finish the rest of the row
sb.Append("");
// get your data
while (oDr.Read())
{
sb.Append("tr>td align='center'>");
sb.Append(oDr["id"].ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append(oDr["Name"].ToString());
sb.Append("/td>");
sb.Append("td align='center'>");
sb.Append(oDr["Roll"].ToString());
// finish the rest of the row
sb.Append("/td>/tr>");
}
sb.Append("/table>");
Response.Write(sb);
con.close();
}
}
Labels:
HTML Report in c# .Net
Registered .DLL
Manual Registration
You can register a DLL manually. To do this, follow these steps:
1. Find the exact location of your .dll file.
2. Click on the Start menu.
3. Select the Run option.
4. On the edit field of the Run dialog box, type regsvr32 followed by the complete path and file name of the .dll file. The path and file name should be enclosed in quotation marks.
Here is an example:
regsvr32 “C:\Windows\System32\abd.dll”
5. Make sure you have typed the information correctly and press enter. The system will include the .dll file in the registry.
6. You will see a message box telling you the DLL file has been successfully registered.
You can register a DLL manually. To do this, follow these steps:
1. Find the exact location of your .dll file.
2. Click on the Start menu.
3. Select the Run option.
4. On the edit field of the Run dialog box, type regsvr32 followed by the complete path and file name of the .dll file. The path and file name should be enclosed in quotation marks.
Here is an example:
regsvr32 “C:\Windows\System32\abd.dll”
5. Make sure you have typed the information correctly and press enter. The system will include the .dll file in the registry.
6. You will see a message box telling you the DLL file has been successfully registered.
Labels:
Registered .DLL
Create and Close Connection using singleton in c#
//Class
public class GetConnection
{
private static SqlConnection connection = null;
public static SqlConnection conn
{
get {
if (connection == null)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolsConnectionString"].ConnectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
return connection;
}
}
public static void closeconn(SqlConnection connection)
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
//aspx.cs Button click use Singleton Class
SqlCommand cmd = new SqlCommand("select * from students", GetConnection.conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
SqlCommand cmd1 = new SqlCommand("insert into student(Name) values(s)", GetConnection.conn);
cmd.ExecuteNonQuery();
GetConnection.closeconn(GetConnection.conn);
public class GetConnection
{
private static SqlConnection connection = null;
public static SqlConnection conn
{
get {
if (connection == null)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolsConnectionString"].ConnectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
return connection;
}
}
public static void closeconn(SqlConnection connection)
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
//aspx.cs Button click use Singleton Class
SqlCommand cmd = new SqlCommand("select * from students", GetConnection.conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
SqlCommand cmd1 = new SqlCommand("insert into student(Name) values(s)", GetConnection.conn);
cmd.ExecuteNonQuery();
GetConnection.closeconn(GetConnection.conn);
Update Existing Xml file
//Xml File
?xml version="1.0" encoding="utf-8"?>
CategoryList>
Category ID="01">
MainCategory>XML /MainCategory>
Description>This is a list my XML articles. /Description>
Active>true /Active>
/Category>
Category ID="02">
MainCategory>Asp.net /MainCategory>
Description>Subahsh /Description>
Active>True /Active>
/Category>
/CategoryList>
//aspx.cs
if (!IsPostBack)
{
XmlDocument xml = new XmlDocument();
string s = Server.MapPath("XMLfILE.xml");
string list = "/CategoryList/Category";
xml.Load(s);
XmlNodeList xn = xml.SelectNodes(list);
foreach (XmlNode eleSourceNode in xn)
{
string ID = eleSourceNode.Attributes["ID"].Value;
string author1 = eleSourceNode["MainCategory"].InnerText;
DropDownList1.Items.Add(new ListItem(author1, ID));
}
}
//DropDown SelectIndexChange
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("XMLfILE.xml"));
XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='"+DropDownList1.SelectedValue+"' ]");
TextBox2.Text = nodeList[0].ChildNodes[0].InnerText;
TextBox3.Text= nodeList[0].ChildNodes[1].InnerText;
TextBox4.Text = nodeList[0].ChildNodes[2].InnerText;
}
//Update Xml File
protected void btnUpdateXml_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("XMLfILE.xml"));
XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='" + DropDownList1.SelectedValue + "' ]");
// update MainCategory
nodeList[0].ChildNodes[0].InnerText = TextBox2.Text.Trim();
// update Description
nodeList[0].ChildNodes[1].InnerText = TextBox3.Text.Trim();
// update Active
nodeList[0].ChildNodes[2].InnerText = TextBox4.Text.Trim();
// Don't forget to save the file
xmlDoc.Save(Server.MapPath("XMLfILE.xml"));
}
?xml version="1.0" encoding="utf-8"?>
CategoryList>
Category ID="01">
MainCategory>XML /MainCategory>
Description>This is a list my XML articles. /Description>
Active>true /Active>
/Category>
Category ID="02">
MainCategory>Asp.net /MainCategory>
Description>Subahsh /Description>
Active>True /Active>
/Category>
/CategoryList>
//aspx.cs
if (!IsPostBack)
{
XmlDocument xml = new XmlDocument();
string s = Server.MapPath("XMLfILE.xml");
string list = "/CategoryList/Category";
xml.Load(s);
XmlNodeList xn = xml.SelectNodes(list);
foreach (XmlNode eleSourceNode in xn)
{
string ID = eleSourceNode.Attributes["ID"].Value;
string author1 = eleSourceNode["MainCategory"].InnerText;
DropDownList1.Items.Add(new ListItem(author1, ID));
}
}
//DropDown SelectIndexChange
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("XMLfILE.xml"));
XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='"+DropDownList1.SelectedValue+"' ]");
TextBox2.Text = nodeList[0].ChildNodes[0].InnerText;
TextBox3.Text= nodeList[0].ChildNodes[1].InnerText;
TextBox4.Text = nodeList[0].ChildNodes[2].InnerText;
}
//Update Xml File
protected void btnUpdateXml_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("XMLfILE.xml"));
XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='" + DropDownList1.SelectedValue + "' ]");
// update MainCategory
nodeList[0].ChildNodes[0].InnerText = TextBox2.Text.Trim();
// update Description
nodeList[0].ChildNodes[1].InnerText = TextBox3.Text.Trim();
// update Active
nodeList[0].ChildNodes[2].InnerText = TextBox4.Text.Trim();
// Don't forget to save the file
xmlDoc.Save(Server.MapPath("XMLfILE.xml"));
}
Labels:
Update Existing Xml file
Monday, February 21, 2011
Take zip folder and Unzip the file using Ionic Zip Dll
//using Ionic.Zip;
//take one file upload control and click event write
if (FileUpload1.HasFile)
{
String TargetDirectory = FileUpload1.PostedFile.FileName;
using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(TargetDirectory))
{
zip1.ExtractAll(Server.MapPath("UploadFile")
, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
}
}
//take one file upload control and click event write
if (FileUpload1.HasFile)
{
String TargetDirectory = FileUpload1.PostedFile.FileName;
using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(TargetDirectory))
{
zip1.ExtractAll(Server.MapPath("UploadFile")
, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
}
}
Sunday, February 20, 2011
Singleton Example
//Class , Only one instance is created of Singleton class.
public class Singleton
{
public int x=0;
private static Singleton Instance;
private Singleton() { }
public static Singleton instance
{
get
{
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
}
}
//Page Load Check for Instance
Singleton s = Singleton.instance;
Singleton s1 = Singleton.instance;
public class Singleton
{
public int x=0;
private static Singleton Instance;
private Singleton() { }
public static Singleton instance
{
get
{
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
}
}
//Page Load Check for Instance
Singleton s = Singleton.instance;
Singleton s1 = Singleton.instance;
Labels:
Singleton Example
Friday, February 18, 2011
data table in ASP.NET 2.0(C#)
//Add a GridView control, one lable controls, four textbox controls and button control in the page .
DataTable myDt;
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "username";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
private void AddDataToTable(string id,string username, string firstname, string lastname, DataTable myTable)
{
DataRow row;
row = myTable.NewRow();
row["id"] = id;
row["username"] = username;
row["firstname"] = firstname;
row["lastname"] = lastname;
myTable.Rows.Add(row);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myDt = new DataTable();
myDt = CreateDataTable();
Session["myDatatable"] = myDt;
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
this.GridView1.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Trim() == "")
{
this.lblTips.Text = "You must fill a username.";
return;
}
else
{
AddDataToTable(this.TextBox1.Text.Trim(),this.txtUserName.Text.Trim(), this.txtFirstName.Text.Trim(), this.txtLastName.Text.Trim(), (DataTable)Session["myDatatable"]);
GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
GridView1.DataBind();
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.txtUserName.Text = "";
this.TextBox1.Text = "";
this.lblTips.Text = "";
}
}
DataTable myDt;
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "username";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
private void AddDataToTable(string id,string username, string firstname, string lastname, DataTable myTable)
{
DataRow row;
row = myTable.NewRow();
row["id"] = id;
row["username"] = username;
row["firstname"] = firstname;
row["lastname"] = lastname;
myTable.Rows.Add(row);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myDt = new DataTable();
myDt = CreateDataTable();
Session["myDatatable"] = myDt;
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
this.GridView1.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Trim() == "")
{
this.lblTips.Text = "You must fill a username.";
return;
}
else
{
AddDataToTable(this.TextBox1.Text.Trim(),this.txtUserName.Text.Trim(), this.txtFirstName.Text.Trim(), this.txtLastName.Text.Trim(), (DataTable)Session["myDatatable"]);
GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
GridView1.DataBind();
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.txtUserName.Text = "";
this.TextBox1.Text = "";
this.lblTips.Text = "";
}
}
Labels:
data table in ASP.NET 2.0(C#)
Grid View with check boxe Insert all the vlue in maping tble
//DataBase
//first table
CREATE TABLE tbluser(
[UId] [int] IDENTITY(1,1) NOT NULL,
[usreId] [varchar](100) CONSTRAINT [pkuser] PRIMARY KEY CLUSTERED ,
[UserName] [varchar](100)
)
//second table
CREATE TABLE tblGroup(
[GroupId] [int] IDENTITY(1,1)CONSTRAINT [pkGroup] PRIMARY KEY CLUSTERED ,
[GroupName] [varchar](100) )
//third table
CREATE TABLE MapUserGroup(
[usreId] [varchar](100) FOREIGN KEY([Groupid]) REFERENCES [dbo].[tblGroup] ([GroupId]),
[Groupid] [int] FOREIGN KEY([usreId]) REFERENCES [dbo].[tbluser] ([usreId]))
//.cs code
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var sql = "select GroupId,GroupName from tblGroup";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
gUser.DataSource = ds;
gUser.DataBind();
}
unCheckUserGrid();
}
}
private void unCheckUserGrid()
{
for (int groupcount = 0; groupcount < gUser.Rows.Count; groupcount++) { CheckBox chkGroup = (CheckBox)gUser.Rows[groupcount].FindControl("chkUser"); chkGroup.Checked = false; } } protected void gUser_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { CheckBox chkGHeader = (CheckBox)e.Row.FindControl("chkUHeader"); chkGHeader.Attributes.Add("onclick", "return maintainState('" + chkGHeader.ClientID + "','" + gUser.ClientID + "');"); } if (e.Row.RowIndex >= 0)
{
CheckBox chkGroup = (CheckBox)e.Row.FindControl("chkUser");
chkGroup.Attributes.Add("onclick", "return uncheckHeader('" + gUser.ClientID + "');");
}
}
string sql = string.Empty;
private void saveall()
{
ArrayList arr = new ArrayList();
CheckBox chk;
Label lbl;
int i;
foreach (GridViewRow d in gUser.Rows)
{
chk = (CheckBox)d.FindControl("chkUser");
if (chk.Checked)
{
lbl = (Label)d.FindControl("lblGroupId");
arr.Add(lbl.Text);
}
}
string userId = txtUserName.Text.Trim().Replace("'", "''");
SqlDataAdapter adp = new SqlDataAdapter("Select usreId from tbluser where usreId='" + userId + "'", con);
DataSet ds = new DataSet();
adp.Fill(ds);
SqlCommand cmd ;
if (ds.Tables[0].Rows.Count > 0)
{
string UId = ds.Tables[0].Rows[0]["usreId"].ToString();
if (arr.Count > 0)
{
for (i = 0; i <= arr.Count - 1; i++) { sql += "insert into MapUserGroup(usreId,groupid) values('" + UId + "','" + arr[i] + "')"; } con.Open(); cmd = new SqlCommand(sql, con); cmd.ExecuteNonQuery(); con.Close(); unCheckUserGrid(); } } } protected void BtnSave_Click(object sender, EventArgs e) { con.Open(); SqlCommand cmd = new SqlCommand("insert into tbluser(usreId) values('" + txtUserName.Text.Trim().Replace("'", "''") + "')", con); cmd.ExecuteNonQuery(); con.Close(); //after save in maping value saveall(); } //Design .aspx page table align="center" >
tr>
td>
span>UserName /span>
/td>
td>
asp:TextBox runat="server" ID="txtUserName" > /asp:TextBox>
/td>
/tr>
/table>
table align="center" >
tr>
td>
div style="overflow: auto">
asp:GridView ID="gUser" AutoGenerateColumns="False"
runat="server"
BackColor="White" BorderColor="#999999" BorderStyle="Double"
BorderWidth="1px" CellPadding="0" Width="100%" Font-Overline="False"
Font-Size="Small" HorizontalAlign="Center" onrowdatabound="gUser_RowDataBound" >
FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
RowStyle BackColor="#EEEEEE" ForeColor="Black" />
Columns>
asp:TemplateField>
HeaderTemplate>
asp:CheckBox ID="chkUHeader" runat="server" />
/HeaderTemplate>
ItemTemplate>
asp:CheckBox ID="chkUser" runat="server" />
/ItemTemplate>
ItemStyle Width="10%" />
/asp:TemplateField>
asp:TemplateField HeaderText="Group Id" HeaderStyle-HorizontalAlign="Left">
ItemTemplate>
asp:Label ID="lblGroupId" runat="server" Font-Size="100%" Text='<%# Bind("GroupId") %>' >
/ItemTemplate>
HeaderStyle HorizontalAlign="Left">
/asp:TemplateField>
asp:TemplateField HeaderText="Group Name" HeaderStyle-HorizontalAlign="Left">
ItemTemplate>
asp:Label ID="lblGroupName" Font-Size="100%" runat="server" Text='<%# Bind("GroupName") %>'>
/ItemTemplate>
HeaderStyle HorizontalAlign="Left">
/asp:TemplateField>
/Columns>
SelectedRowStyle BackColor="#008A8C" ForeColor="White" />
HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" BorderStyle="Double" Font-Size="Small"
HorizontalAlign="Left" />
AlternatingRowStyle BackColor="#DCDCDC" />
/asp:GridView>
/div>
/td>
/tr>
tr>
td align="right" >
asp:Button ID="BtnSave" runat="server" onclick="BtnSave_Click" Text="Save" />
/td>
/tr>
/table>
//.Js file
function maintainState(checkall,Grid)
{
var gvTable=document.getElementById(Grid);
var control=document.getElementById(checkall);
for(var i=1;i
{
if(control.checked==true)
{
gvTable.rows[i].cells[0].childNodes[0].checked=true;
}
else
{
gvTable.rows[i].cells[0].childNodes[0].checked=false;
}
}
}
function uncheckHeader(control)
{
document.getElementById(control).rows[0].cells[0].childNodes[0].checked=false;
}
//first table
CREATE TABLE tbluser(
[UId] [int] IDENTITY(1,1) NOT NULL,
[usreId] [varchar](100) CONSTRAINT [pkuser] PRIMARY KEY CLUSTERED ,
[UserName] [varchar](100)
)
//second table
CREATE TABLE tblGroup(
[GroupId] [int] IDENTITY(1,1)CONSTRAINT [pkGroup] PRIMARY KEY CLUSTERED ,
[GroupName] [varchar](100) )
//third table
CREATE TABLE MapUserGroup(
[usreId] [varchar](100) FOREIGN KEY([Groupid]) REFERENCES [dbo].[tblGroup] ([GroupId]),
[Groupid] [int] FOREIGN KEY([usreId]) REFERENCES [dbo].[tbluser] ([usreId]))
//.cs code
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var sql = "select GroupId,GroupName from tblGroup";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
gUser.DataSource = ds;
gUser.DataBind();
}
unCheckUserGrid();
}
}
private void unCheckUserGrid()
{
for (int groupcount = 0; groupcount < gUser.Rows.Count; groupcount++) { CheckBox chkGroup = (CheckBox)gUser.Rows[groupcount].FindControl("chkUser"); chkGroup.Checked = false; } } protected void gUser_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { CheckBox chkGHeader = (CheckBox)e.Row.FindControl("chkUHeader"); chkGHeader.Attributes.Add("onclick", "return maintainState('" + chkGHeader.ClientID + "','" + gUser.ClientID + "');"); } if (e.Row.RowIndex >= 0)
{
CheckBox chkGroup = (CheckBox)e.Row.FindControl("chkUser");
chkGroup.Attributes.Add("onclick", "return uncheckHeader('" + gUser.ClientID + "');");
}
}
string sql = string.Empty;
private void saveall()
{
ArrayList arr = new ArrayList();
CheckBox chk;
Label lbl;
int i;
foreach (GridViewRow d in gUser.Rows)
{
chk = (CheckBox)d.FindControl("chkUser");
if (chk.Checked)
{
lbl = (Label)d.FindControl("lblGroupId");
arr.Add(lbl.Text);
}
}
string userId = txtUserName.Text.Trim().Replace("'", "''");
SqlDataAdapter adp = new SqlDataAdapter("Select usreId from tbluser where usreId='" + userId + "'", con);
DataSet ds = new DataSet();
adp.Fill(ds);
SqlCommand cmd ;
if (ds.Tables[0].Rows.Count > 0)
{
string UId = ds.Tables[0].Rows[0]["usreId"].ToString();
if (arr.Count > 0)
{
for (i = 0; i <= arr.Count - 1; i++) { sql += "insert into MapUserGroup(usreId,groupid) values('" + UId + "','" + arr[i] + "')"; } con.Open(); cmd = new SqlCommand(sql, con); cmd.ExecuteNonQuery(); con.Close(); unCheckUserGrid(); } } } protected void BtnSave_Click(object sender, EventArgs e) { con.Open(); SqlCommand cmd = new SqlCommand("insert into tbluser(usreId) values('" + txtUserName.Text.Trim().Replace("'", "''") + "')", con); cmd.ExecuteNonQuery(); con.Close(); //after save in maping value saveall(); } //Design .aspx page table align="center" >
tr>
td>
span>UserName /span>
/td>
td>
asp:TextBox runat="server" ID="txtUserName" > /asp:TextBox>
/td>
/tr>
/table>
table align="center" >
tr>
td>
div style="overflow: auto">
asp:GridView ID="gUser" AutoGenerateColumns="False"
runat="server"
BackColor="White" BorderColor="#999999" BorderStyle="Double"
BorderWidth="1px" CellPadding="0" Width="100%" Font-Overline="False"
Font-Size="Small" HorizontalAlign="Center" onrowdatabound="gUser_RowDataBound" >
FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
RowStyle BackColor="#EEEEEE" ForeColor="Black" />
Columns>
asp:TemplateField>
HeaderTemplate>
asp:CheckBox ID="chkUHeader" runat="server" />
/HeaderTemplate>
ItemTemplate>
asp:CheckBox ID="chkUser" runat="server" />
/ItemTemplate>
ItemStyle Width="10%" />
/asp:TemplateField>
asp:TemplateField HeaderText="Group Id" HeaderStyle-HorizontalAlign="Left">
ItemTemplate>
asp:Label ID="lblGroupId" runat="server" Font-Size="100%" Text='<%# Bind("GroupId") %>' >
/ItemTemplate>
HeaderStyle HorizontalAlign="Left">
/asp:TemplateField>
asp:TemplateField HeaderText="Group Name" HeaderStyle-HorizontalAlign="Left">
ItemTemplate>
asp:Label ID="lblGroupName" Font-Size="100%" runat="server" Text='<%# Bind("GroupName") %>'>
/ItemTemplate>
HeaderStyle HorizontalAlign="Left">
/asp:TemplateField>
/Columns>
SelectedRowStyle BackColor="#008A8C" ForeColor="White" />
HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" BorderStyle="Double" Font-Size="Small"
HorizontalAlign="Left" />
AlternatingRowStyle BackColor="#DCDCDC" />
/asp:GridView>
/div>
/td>
/tr>
tr>
td align="right" >
asp:Button ID="BtnSave" runat="server" onclick="BtnSave_Click" Text="Save" />
/td>
/tr>
/table>
//.Js file
function maintainState(checkall,Grid)
{
var gvTable=document.getElementById(Grid);
var control=document.getElementById(checkall);
for(var i=1;i
if(control.checked==true)
{
gvTable.rows[i].cells[0].childNodes[0].checked=true;
}
else
{
gvTable.rows[i].cells[0].childNodes[0].checked=false;
}
}
}
function uncheckHeader(control)
{
document.getElementById(control).rows[0].cells[0].childNodes[0].checked=false;
}
Wednesday, February 16, 2011
var datatype in C#
Declaring local variables implicitly has some restrictions; the variable must be initialized to some expression that can not be null.
var a= 10;
var z = "Rekha";
The primary reason for its existence is the introduction of anonymous types in C#
Another point to stress is that variable inference does not work for class level fields or method arguments or anywhere else other than for local variables in a method.
Advantages :
Less typing with no loss of functionality
Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
Makes it so you don't have to write the same name twice in a variable declaration.
Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
var a= 10;
var z = "Rekha";
The primary reason for its existence is the introduction of anonymous types in C#
Another point to stress is that variable inference does not work for class level fields or method arguments or anywhere else other than for local variables in a method.
Advantages :
Less typing with no loss of functionality
Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
Makes it so you don't have to write the same name twice in a variable declaration.
Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
Labels:
var datatype in C#
What is difference between Physical path and Virtual path?
Physical path is the path where ur original application has
stored(actual directory path of application).
virtual path is the link between physical path and
IIS..becoz to execute the webapplication in Physical
path,it needs to be mapped on to IIS(webserver) and this
logical link between physical path and IIS is called
virtual path
stored(actual directory path of application).
virtual path is the link between physical path and
IIS..becoz to execute the webapplication in Physical
path,it needs to be mapped on to IIS(webserver) and this
logical link between physical path and IIS is called
virtual path
Recursive method for Find all directory and inside the directory found all files
// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
//Logic here in file
}
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries){
ProcessFile(fileName);
}
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
ProcessDirectory(subdirectory);
}
}
//call the Method
string FilePath = Request.PhysicalApplicationPath + "UploadFile";
if (Directory.Exists(FilePath))
{
ProcessDirectory(FilePath);
}
public static void ProcessFile(string path)
{
//Logic here in file
}
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries){
ProcessFile(fileName);
}
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
ProcessDirectory(subdirectory);
}
}
//call the Method
string FilePath = Request.PhysicalApplicationPath + "UploadFile";
if (Directory.Exists(FilePath))
{
ProcessDirectory(FilePath);
}
Tuesday, February 15, 2011
What is the difference between WCF Service and Web Service?
What is the difference between WCF Service and Web Service?
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.
•Web services can be hosted in IIS as well as outside of the IIS. While WCF service can be hosted in IIS, Windows activation service,Self Hosting,WAS and on lots of proctols like Named Pipe,TCP etc.Here lots of people disagree how we can host the web service outside of the IIS but Here is the article for that.http://msdn.microsoft.com/en-us/library/aa529311.aspx.
•In Web Services Web Service attribute will added on the top of class. In WCF there will be a Service Contract attributes will be there. Same way Web Method attribute are added in top of method of Web service while in WCF Service Operation Contract will added on the top method.
•In Web service System.XML.Serialization is supported while in the WCF Service System.RunTime.Serialization is supported.
•WCF Services can be multithreaded via ServiceBehavior class while web service can not be.
•WCF Services supports different type of bindings like BasicHttpBinding, WSHttpBinding, WSDualHttpBinding etc.while Web services only used soap or xml for this.
•Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive that identifies the class that contains the code for the service and the assembly in which it is located while in WCF.WCF services can readily be hosted within IIS 5.1 or 6.0, the Windows Process Activation Service (WAS) that is provided as part of IIS 7.0, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol.
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.
•Web services can be hosted in IIS as well as outside of the IIS. While WCF service can be hosted in IIS, Windows activation service,Self Hosting,WAS and on lots of proctols like Named Pipe,TCP etc.Here lots of people disagree how we can host the web service outside of the IIS but Here is the article for that.http://msdn.microsoft.com/en-us/library/aa529311.aspx.
•In Web Services Web Service attribute will added on the top of class. In WCF there will be a Service Contract attributes will be there. Same way Web Method attribute are added in top of method of Web service while in WCF Service Operation Contract will added on the top method.
•In Web service System.XML.Serialization is supported while in the WCF Service System.RunTime.Serialization is supported.
•WCF Services can be multithreaded via ServiceBehavior class while web service can not be.
•WCF Services supports different type of bindings like BasicHttpBinding, WSHttpBinding, WSDualHttpBinding etc.while Web services only used soap or xml for this.
•Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive that identifies the class that contains the code for the service and the assembly in which it is located while in WCF.WCF services can readily be hosted within IIS 5.1 or 6.0, the Windows Process Activation Service (WAS) that is provided as part of IIS 7.0, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol.
Monday, February 14, 2011
View state Data stored?
Where is the View state Data stored?
ViewState data is stored in the hidden field. When the page is submitted to the server the data is sent to the server in the form of hidden fields for each control. If th viewstate of the control is enable true the value is retained on the post back to the client when the page is post backed
ViewState data is stored in the hidden field. When the page is submitted to the server the data is sent to the server in the form of hidden fields for each control. If th viewstate of the control is enable true the value is retained on the post back to the client when the page is post backed
Labels:
View state Data stored?
candidate key, alternate key, composite key.
■Define candidate key, alternate key, composite key.
■A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.
■A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.
Labels:
alternate key,
candidate key,
composite key.
Session
InProc means where the session variable will be stored in the procesor .
OutProc are the session modes like Stateserver and Sqlserver
In Stateserver session variables are stored in application domain
In Sqlserver session mode session variable is stored in sql server
The StateServer mode uses a stand-alone Microsoft Windows service that is independent of IIS and can run on a separate server.
In this case the session state is serialized and stored in memory in a separate process that is managed by the aspnet_state.exe file.
This has got some performance drawbacks due to the overhead involved in serialization and de-serialization of objects.
The main primary advantage of storing the Session State in a State Server is that it is not in the same process as the ASP.NET and a crash of ASP.NET
would in no way destroy the session data. Secondly, this mode of Session State storage enables to share the information across a web garden or a web farm.
Rememeber that this mode is slow compared to the InProc mode as it is stored in an external process
OutProc are the session modes like Stateserver and Sqlserver
In Stateserver session variables are stored in application domain
In Sqlserver session mode session variable is stored in sql server
The StateServer mode uses a stand-alone Microsoft Windows service that is independent of IIS and can run on a separate server.
In this case the session state is serialized and stored in memory in a separate process that is managed by the aspnet_state.exe file.
This has got some performance drawbacks due to the overhead involved in serialization and de-serialization of objects.
The main primary advantage of storing the Session State in a State Server is that it is not in the same process as the ASP.NET and a crash of ASP.NET
would in no way destroy the session data. Secondly, this mode of Session State storage enables to share the information across a web garden or a web farm.
Rememeber that this mode is slow compared to the InProc mode as it is stored in an external process
Session default Expiration
Session default Expiration : is 20 Minute
Labels:
Session default Expiration
Xslt
XSLT - a language for transforming XML documents
XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.
XPath - a language for navigating in XML documents
XSL-FO - a language for formatting XML documents
XSLT stands for Extensible Stylesheet Language Transformations. This language used in XSL style sheets to transform XML documents into other XML documents.
XSLT is based on template rules which specify how XML documents should be processed. An XSLT processor reads both an XML document and an XSLT style sheet. Based on the instructions the processor finds in the XSLT style sheet, it produce a new XML document. With XSLT we can also produce HTML or XHTML from XML document. With XSLT we can add/remove elements and attributes, rearrange and sort elements, hide and display elements from the output file. Converting XML to HTML for display is probably the most common application of XSLT today.
XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.
XPath - a language for navigating in XML documents
XSL-FO - a language for formatting XML documents
XSLT stands for Extensible Stylesheet Language Transformations. This language used in XSL style sheets to transform XML documents into other XML documents.
XSLT is based on template rules which specify how XML documents should be processed. An XSLT processor reads both an XML document and an XSLT style sheet. Based on the instructions the processor finds in the XSLT style sheet, it produce a new XML document. With XSLT we can also produce HTML or XHTML from XML document. With XSLT we can add/remove elements and attributes, rearrange and sort elements, hide and display elements from the output file. Converting XML to HTML for display is probably the most common application of XSLT today.
use Xslt with Xml
XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.
//Xslt
The element element extracts the value of a selected node.
The element can be used to select the value of an XML element and add it to the output.
XSLT is a language for transforming XML documents into XHTML documents or to other XML documents.
--------------------------------------------------------------------------------
?xml version="1.0" encoding="iso-8859-1"?>
!-- Edited by XMLSpy® -->
xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
xsl:template match="/">
html>
body>
h2>My CD Collection /h2>
table border="1">
tr bgcolor="#9acd32">
th>Title /th>
th>Artist /th>
/tr>
xsl:for-each select="catalog/cd">
tr>
td>
xsl:value-of select="title"/>
/td>
td>
xsl:value-of select="artist"/>
/td>
/tr>
/xsl:for-each>
/table>
/body>
/html>
/xsl:template>
/xsl:stylesheet>
//Xml
cd>
title>Bridge of Spies /title>
artist>T`Pau /artist>
country>UK /country>
company>Siren /company>
price>7.90 /price>
year>1987 /year>
/cd>
cd>
title>Private Dancer /title>
artist>Tina Turner /artist>
country>UK /country>
company>Capitol /company>
price>8.90 /price>
year>1983 /year>
/cd>
cd>
title>Midt om natten /title>
artist>Kim Larsen /artist>
country>EU /country>
company>Medley /company>
price>7.80 /price>
year>1983 /year>
/cd>
cd>
title>Pavarotti Gala Concert /title>
artist>Luciano Pavarotti /artist>
country>UK /country>
company>DECCA /company>
price>9.90 /price>
year>1991 /year>
/cd>
cd>
title>The dock of the bay /title>
artist>Otis Redding /artist>
country>USA /country>
company>Atlantic /company>
price>7.90 /price>
year>1987 /year>
/cd>
cd>
title>Picture book /title>
artist>Simply Red /artist>
country>EU /country>
company>Elektra /company>
price>7.20 /price>
year>1985 /year>
/cd>
cd>
title>Red /title>
artist>The Communards /artist>
country>UK /country>
company>London /company>
price>7.80 /price>
year>1987 /year>
/cd>
cd>
title>Unchain my heart /title>
artist>Joe Cocker /artist>
country>USA /country>
company>EMI /company>
price>8.20 /price>
year>1987 /year>
/cd>
/catalog>
//Xslt
The
The
XSLT is a language for transforming XML documents into XHTML documents or to other XML documents.
--------------------------------------------------------------------------------
?xml version="1.0" encoding="iso-8859-1"?>
!-- Edited by XMLSpy® -->
xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
xsl:template match="/">
html>
body>
h2>My CD Collection /h2>
table border="1">
tr bgcolor="#9acd32">
th>Title /th>
th>Artist /th>
/tr>
xsl:for-each select="catalog/cd">
tr>
td>
xsl:value-of select="title"/>
/td>
td>
xsl:value-of select="artist"/>
/td>
/tr>
/xsl:for-each>
/table>
/body>
/html>
/xsl:template>
/xsl:stylesheet>
//Xml
cd>
title>Bridge of Spies /title>
artist>T`Pau /artist>
country>UK /country>
company>Siren /company>
price>7.90 /price>
year>1987 /year>
/cd>
cd>
title>Private Dancer /title>
artist>Tina Turner /artist>
country>UK /country>
company>Capitol /company>
price>8.90 /price>
year>1983 /year>
/cd>
cd>
title>Midt om natten /title>
artist>Kim Larsen /artist>
country>EU /country>
company>Medley /company>
price>7.80 /price>
year>1983 /year>
/cd>
cd>
title>Pavarotti Gala Concert /title>
artist>Luciano Pavarotti /artist>
country>UK /country>
company>DECCA /company>
price>9.90 /price>
year>1991 /year>
/cd>
cd>
title>The dock of the bay /title>
artist>Otis Redding /artist>
country>USA /country>
company>Atlantic /company>
price>7.90 /price>
year>1987 /year>
/cd>
cd>
title>Picture book /title>
artist>Simply Red /artist>
country>EU /country>
company>Elektra /company>
price>7.20 /price>
year>1985 /year>
/cd>
cd>
title>Red /title>
artist>The Communards /artist>
country>UK /country>
company>London /company>
price>7.80 /price>
year>1987 /year>
/cd>
cd>
title>Unchain my heart /title>
artist>Joe Cocker /artist>
country>USA /country>
company>EMI /company>
price>8.20 /price>
year>1987 /year>
/cd>
/catalog>
Labels:
use Xslt with Xml
Friday, February 11, 2011
Heap Vs Stack(Value Type(Stack) and Reference Type(Heap))
//Link for Stack Vs Heap
http://www.c-sharpcorner.com/uploadfile/rmcochran/csharp_memory01122006130034pm/csharp_memory.aspx
Stack vs. Heap: What's the difference?
The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called"). The Heap is more or less responsible for keeping track of our objects (our data, well... most of it - we'll get to that later.).
Think of the Stack as a series of boxes stacked one on top of the next. We keep track of what's going on in our application by stacking another box on top every time we call a method (called a Frame). We can only use what's in the top box on the stack. When we're done with the top box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that its purpose is to hold information (not keep track of execution most of the time) so anything in our Heap can be accessed at any time. With the Heap, there are no constraints as to what can be accessed like in the stack. The Heap is like the heap of clean laundry on our bed that we have not taken the time to put away yet - we can grab what we need quickly. The Stack is like the stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it.
The Stack is self-maintaining, meaning that it basically takes care of its own memory management. When the top box is no longer used, it's thrown out. The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to keep the Heap clean (no one wants dirty laundry laying around... it stinks!).
What goes on the Stack and Heap?
We have four main types of things we'll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.
Value Types:
In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType):
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
Reference Types:
All the "things" declared with the types in this list are Reference types (and inherit from System.Object... except, of course, for object which is the System.Object object):
class
interface
delegate
object
string
Pointers:
The third type of "thing" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type is means we access it through a Pointer. A Pointer is a chunk of space in memory that points to another space in memory. A Pointer takes up space just like any other thing that we're putting in the Stack and Heap and its value is either a memory address or null.
How is it decided what goes where? (Huh?)
Ok, one last thing and we'll get to the fun stuff.
Here are our two golden rules:
A Reference Type always goes on the Heap - easy enough, right?
Value Types and Pointers always go where they were declared. This is a little more complex and needs a bit more understanding of how the Stack works to figure out where "things" are declared.
The Stack, as we mentioned earlier, is responsible for keeping track of where each thread is during the execution of our code (or what's been called). You can think of it as a thread "state" and each thread has its own stack. When our code makes a call to execute a method the thread starts executing the instructions that have been JIT compiled and live on the method table, it also puts the method's parameters on the thread stack. Then, as we go through the code and run into variables within the method they are placed on top of the stack.
http://www.c-sharpcorner.com/uploadfile/rmcochran/csharp_memory01122006130034pm/csharp_memory.aspx
Stack vs. Heap: What's the difference?
The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called"). The Heap is more or less responsible for keeping track of our objects (our data, well... most of it - we'll get to that later.).
Think of the Stack as a series of boxes stacked one on top of the next. We keep track of what's going on in our application by stacking another box on top every time we call a method (called a Frame). We can only use what's in the top box on the stack. When we're done with the top box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that its purpose is to hold information (not keep track of execution most of the time) so anything in our Heap can be accessed at any time. With the Heap, there are no constraints as to what can be accessed like in the stack. The Heap is like the heap of clean laundry on our bed that we have not taken the time to put away yet - we can grab what we need quickly. The Stack is like the stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it.
The Stack is self-maintaining, meaning that it basically takes care of its own memory management. When the top box is no longer used, it's thrown out. The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to keep the Heap clean (no one wants dirty laundry laying around... it stinks!).
What goes on the Stack and Heap?
We have four main types of things we'll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.
Value Types:
In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType):
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
Reference Types:
All the "things" declared with the types in this list are Reference types (and inherit from System.Object... except, of course, for object which is the System.Object object):
class
interface
delegate
object
string
Pointers:
The third type of "thing" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type is means we access it through a Pointer. A Pointer is a chunk of space in memory that points to another space in memory. A Pointer takes up space just like any other thing that we're putting in the Stack and Heap and its value is either a memory address or null.
How is it decided what goes where? (Huh?)
Ok, one last thing and we'll get to the fun stuff.
Here are our two golden rules:
A Reference Type always goes on the Heap - easy enough, right?
Value Types and Pointers always go where they were declared. This is a little more complex and needs a bit more understanding of how the Stack works to figure out where "things" are declared.
The Stack, as we mentioned earlier, is responsible for keeping track of where each thread is during the execution of our code (or what's been called). You can think of it as a thread "state" and each thread has its own stack. When our code makes a call to execute a method the thread starts executing the instructions that have been JIT compiled and live on the method table, it also puts the method's parameters on the thread stack. Then, as we go through the code and run into variables within the method they are placed on top of the stack.
Wednesday, February 9, 2011
Static ,const and readonly
The value of a static readonly field is set at runtime; therefore, the value can be modified by the containing class. On the other hand, the value of a const field is set to a compile-time constant.
In the case of static readonly, the containing class is allowed to modify the value only:
in the variable declaration (via a variable initializer)
in the static constructor (or instance constructors for non-static)
Typically, static readonly is used either when the value is unknown at compile time or if the type of the field is not allowed in a const declaration.
Also, instance readonly fields are allowed.
Note: for reference types, in both cases—static and instance—the readonly modifier only prevents assignment of a new reference to the field. It does not specifically make the object pointed to by the reference immutable.
Example:-
class TestProgram
{
public static readonly Test test = new Test();
static void Main (string[] args)
{
test.Name = "Application";
test = new Test();
// Error: A static readonly field cannot
// be assigned to (except in a static constructor
// or a variable initializer).
}
}
class Test
{
public string Name;
}
In the case of static readonly, the containing class is allowed to modify the value only:
in the variable declaration (via a variable initializer)
in the static constructor (or instance constructors for non-static)
Typically, static readonly is used either when the value is unknown at compile time or if the type of the field is not allowed in a const declaration.
Also, instance readonly fields are allowed.
Note: for reference types, in both cases—static and instance—the readonly modifier only prevents assignment of a new reference to the field. It does not specifically make the object pointed to by the reference immutable.
Example:-
class TestProgram
{
public static readonly Test test = new Test();
static void Main (string[] args)
{
test.Name = "Application";
test = new Test();
// Error: A static readonly field cannot
// be assigned to (except in a static constructor
// or a variable initializer).
}
}
class Test
{
public string Name;
}
Labels:
const and readonly,
Static
Subscribe to:
Posts (Atom)