Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Saturday, April 23, 2011

What Happens When a Request Reaches IIS

This is the link for All the details related parsing asp.net page and generating Requst and Response


http://msdn.microsoft.com/en-us/library/ms972974.aspx

Wednesday, April 20, 2011

Disable Browser Back Button using Javascript

head runat="server">
script type="text/javascript" language="javascript">
javascript:window.history.forward(0);
/script>
/head>

Disable Browser Back Button using Javascript

head runat="server">
script type="text/javascript" language="javascript">
javascript:window.history.forward(0);
/script>
/head>

Tuesday, March 22, 2011

Microsoft Enterprises Library

Microsoft Enterprises Library provide API where we dont need to open and close connection and they have sme predefind method .You dont need to create your own method .it has pedefined method for all that things for insert update delete retrieve and some more specific operation...........

You have to download the Entterprise lIbrary first and Add some Dll through AddReferences from a bin folder of Enterprises Library add

using Microsoft.Practices.EnterpriseLibrary.Data.dll
using Microsoft.Practices.EnterpriseLibrary.Common..dll

and Add the classes in code behind

using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;


//Retrieve and Insert value Using Entrprises library

protected void Page_Load(object sender, EventArgs e)
{
Database db = DatabaseFactory.CreateDatabase();
string sqlcommand = "select * from emp";
System.Data.Common.DbCommand dbCommand = db.GetSqlStringCommand(sqlcommand);
using (IDataReader reader = db.ExecuteReader(
dbCommand))
{
Gridview1.DataSource = reader;
Gridview1.DataBind();
}
}
public void save(string name)
{
DatabaseFactory.CreateDatabase().ExecuteNonQuery("inserts12",name);
}
protected void Button1_Click(object sender, EventArgs e)
{
save("subhash");
}

/////////web.config file
inside the ConfigSection
section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,Microsoft.Practices.EnterpriseLibrary.Data" />

after closing configsection You have to add

/configSections>
dataConfiguration defaultDatabase="Master1"/>

//dataconfiguration same name as the connection string because DatabaseFactory.CreateDatabase(); using for connection

//connection string

add name="Master1" providerName="System.Data.SqlClient" connectionString="Data Source=subhash-9f7eec2;user id=;password=;database=Master;integrated security=sspi;"/>

Friday, March 18, 2011

Generic

using System.Collections.Generic;

In an Arraylist, As Each item is stored as an object, During Sorting and traversing the list, it must be typed at runtime, and then compared for sorting/searching wheareas Generic list has all items typed compile time, which saves a lot of workload during sorting and searching.

The List class is the generic equivalent of the ArrayList class. It implements the IList generic interface using an array whose size is dynamically increased as required.

Type safety : it gives error at compile time if a data type mismatch is found.

Code reusablity : Same code is reused for various data tyoe like int,string etc.

public class User
{
protected string name;
protected int age;
protected double salary;
public string Name { get { return name; } set { name = value; } }
public int Age { get { return age; } set { age = value; } }
public double Salary { get { return salary; } set { salary = value; } }

static void Main(string[] args)
{
List users = new List();

for (int x = 0; x < 5; x++)
{
User user = new User();
user.Name ="Name : "+ "subhash" + x;
user.Age = x+20;
user.salary =x + 12500;
users.Add(user);
}

foreach (User user in users)
{
System.Console.WriteLine(System.String.Format("{0}:{1}:{2}", user.Name, user.Age,user.salary));
}

Console.ReadLine();
}
}

Tuesday, March 15, 2011

Using Statement in C#

Using block defines a scope, outside of which an object or objects will be disposed.
The using statement takes an object parameter, this object is destroyed when the statement finish's, or rather disposed of (IDisposable). The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
A "using" statement can be exited either when the end of the "using" statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
In the below example font1 object is disposed of after the using statement has been executed.
using (Font font1 = new Font("Arial", 10.0f)){}
Multiple objects can be used in with a "using" statement, but they must be declared inside the "using" statement, like this:
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f)){
// Use font3 and font4.
}



The problem is that SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, the developers, to make sure Dispose() gets called on these classes after we are finished with them. And, because an exception could be raised if the database is unavailable ( a very real possibility on WebHost4Life :) ), we need to make sure Dispose() gets called even in the case of an exception.

Personally, I like the “using” keyword in C#. Internally, this bad boy generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().

The new code would looking something like this:

using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cm = new SqlCommand(commandString, cn))
{
cn.Open();
cm.ExecuteNonQuery();
}
}

This is essentially equivalent to the following, although my guess is that C# will internally generate two try / finally blocks (one for the SqlConnection and one for the SqlCommand), but you get the idea:

SqlConnection cn = null;
SqlCommand cm = null;

try
{
cn = new SqlConnection(connectionString);
cm = new SqlCommand(commandString, cn);
cn.Open();
cm.ExecuteNonQuery();
}
finally
{
if (null != cm);
cm.Dispose();
if (null != cn)
cn.Dispose();
}

Friday, March 4, 2011

Cache object use for dataBase Access(Application Level Caching/Programmatic and Data Caching)

//First Page where we store dataset values into caching and use that value another page...

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);

SqlCommand cmd = new SqlCommand("select Id,Name from emp", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
Cache.Insert("user", ds);

/////second page access caching value..........

if (Cache["user"] != "")
{
ds = (DataSet)Cache["user"];
GridView1.DataSource = ds;
GridView1.DataBind();

}

Caching in ASP.NET

This is the link where we can understand easily for Caching.......



http://www.c-sharpcorner.com/uploadfile/vishnuprasad2005/implementingcachinginasp.net11302005072210am/implementingcachinginasp.net.aspx

Thursday, March 3, 2011

Ajax tutorial Link

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_suggest

Tuesday, March 1, 2011

LINQ Bind Gridview and Insert Data

SqlConnection con=new SqlConnection (ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataClassesDataContext db = new DataClassesDataContext(con);
//linq Table emps
var query = from emp1 in db.emps select new { emp1.id, emp1.Name };
GridView1.DataSource = query;
GridView1.DataBind();
}
}

protected void Button1_Click(object sender, EventArgs e)
{
DataClassesDataContext db = new DataClassesDataContext(con);
db.Connection.Open();
//emp Name of the Table
emp empob = new emp();
empob.Name = TextBox1.Text.Trim();
db.emps.InsertOnSubmit(empob);
db.SubmitChanges();
db.Connection.Close();
TextBox1.Text = "";

}

Monday, February 28, 2011

Read Data from Excel and Export to Sql server

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

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

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";
}

}
}

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

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.

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

sql server DataBase Reference(Help)

http://www.functionx.com/sqlserver/index.htm

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/ "

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(""); sb.Append(""); sb.Append(""); sb.Append(""); // get your data while (oDr.Read()) { sb.Append(""); sb.Append(""); sb.Append(""); } sb.Append("
Financial Report
");
sb.Append("id".ToString());
sb.Append("
");
sb.Append("Name".ToString());
sb.Append("
");
sb.Append("Roll".ToString());
// finish the rest of the row
sb.Append("
");
sb.Append(oDr["id"].ToString());
sb.Append("
");
sb.Append(oDr["Name"].ToString());
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 = "";
}

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

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

}
}

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

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.

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

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

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

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;

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 = "";
}
}

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;

}

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

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

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

}

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.

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

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.

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

Session default Expiration

Session default Expiration : is 20 Minute

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.

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>

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.

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

Thursday, January 27, 2011

Sorting in array wihout using sort method

public static int[] SortArray(int[] characters, string Order)
{
if (Order == "Desc")
{
for (int i = 0; i < characters.Length; i++) { for (int j = i; j < characters.Length; j++) { if ((int)characters[j] > (int)characters[i])
{
int tempChar = characters[i];
characters[i] = characters[j];
characters[j] = tempChar;
}
}
}
}
else
{
for (int i = 0; i < characters.Length; i++)
{
for (int j = i; j < characters.Length; j++)
{
if ((int)characters[j] < (int)characters[i])
{
int tempChar = characters[i];
characters[i] = characters[j];
characters[j] = tempChar;
}
}
}
}
return characters;
}



///calling function

int[] characters = new int[] { 1,9,2,10,5 };
characters = Program.SortArray(characters, "Asc");
string str = "";
for (int i = 0; i < characters.Length; i++)
{
str += characters[i].ToString();
}
Console.WriteLine(str);
Console.ReadLine();

Tuesday, January 25, 2011

what is axapta

Microsoft Dynamics Axapta is a customizable, multiple language ,multiple currency enterprise resources planning or ERP solution. Microsoft Dynamics AX is completely integrated solution. It’s a web enabled and support Microsoft SQL Server and Oracle with customizable source code. You can modify the solution however and whenever you want.

Difference Between Axapta and Navision

Axapta & Navison, both are the application of Microsoft Dynamics.

Axapta uses X++ as programming language & Navison uses CSL.

There are many differences & one such difference is that Axapta has a payroll but Nav doesnot have payroll functionality.

Thursday, January 20, 2011

webservices Bind GridView

//connectionStrings>
add name="Master" connectionString="Data Source=SF-74\SQLEXPRESS;user id=;pwd=;Trusted_Connection=true" />

/connectionStrings>

//use some NameSpaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;
using System.Data;

[WebMethod]
public XmlDocument GetDataFromDB()
{
string errorMessage = "";
XmlDocument myDatas = new XmlDocument();
//Connection string is stored in the web.config file as an appSetting
string connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection dbConnection = null;
// Open a connection to the database
try
{
dbConnection = new SqlConnection(connectionString);
dbConnection.Open();
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
if (errorMessage == "")
{
// Build an insert command
string SQL = "select * From sa";
SqlCommand GetCustomerCmd = new SqlCommand(SQL, dbConnection);

try
{
SqlDataAdapter custDA = new SqlDataAdapter();
custDA.SelectCommand = GetCustomerCmd;
DataSet custDS = new DataSet();
custDA.Fill(custDS, "ProfileContact");
myDatas.LoadXml(custDS.GetXml());
dbConnection.Close();

}
catch (System.Exception ex)
{
errorMessage = ex.Message;

}
finally
{
dbConnection.Dispose();
}
}
return myDatas;
}


////////////aspx.cs

localhost.WebService2 proxy = new WebApplication1.localhost.WebService2();

protected void Page_Load(object sender, EventArgs e)
{
XmlDocument myServiceDoc = new XmlDocument();
System.Xml.XmlNode neNode;
//Adding the resulting XML from WebMethod to a user created XmlNode
neNode = proxy.GetDataFromDB();
//Creating a Dataset
DataSet myDataSet = new DataSet();
//The XmlNode is added to a byte[]
byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(neNode.OuterXml);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buf);
//The XML is readed from the MemoryStream
myDataSet.ReadXml(ms);

GridView1.DataSource = myDataSet.Tables[0];
GridView1.DataBind();

//GridView1.DataSource = proxy.GetDataFromDB();
//GridView1.DataBind();

}

Method Overloading in WebServices

When u overload a method than replace
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[WebServiceBinding(ConformsTo = WsiProfiles.None)]


[WebMethod]
public int Add(int i, int j)
{
return i + j;
}
[WebMethod(MessageName = "Add2")]
public int Add(int i, int j, int k)
{
return i + j + k;
}

when u overload a method u hve to give the Mesaage name that would be unique from ur method name...

aspx.cs page

localhost.WebService1 proxy = new WebApplication1.localhost.WebService1();
proxy.Add(5,4,8);

Tuesday, January 18, 2011

HttpHandler vs HttpModule

//This link will help for read about HttpHandler and HttpModule

http://geekswithblogs.net/flanakin/articles/ModuleHandlerIntro.aspx

Introduction

All requests to IIS are handled through Internet Server Application Programming Interface (ISAPI) extensions. ASP.NET has its own filter to ensure pages are processed appropriately. By default, the ASP.NET ISAPI filter (aspnet_isapi.dll) only handles ASPX, ASMX, and all other non-display file formats used by .NET and Visual Studio. However, this filter can be registered with other extensions in order to handle requests to those file types, too, but that will be covered later.

Every request flows through a number of HTTP modules, which cover various areas of the application (i.e. authentication and session intofmation). After passing through each module, the request is assigned to a single HTTP handler, which determines how the system will respond to the request. Upon completion of the request handler, the response flows back through the HTTP modules to the user.


HTTP Module

HTTP modules are executed before and after the handler and provide a method for interacting with the request. Custom modules must implement the System.Web.IHttpModule interface. Modules are typically synchronized with events of the System.Web.IHttpModule class (implemented within the Global.asax.cs or .vb file). The following consists of a list of events that should be considered when implementing your module:

BeginRequest
AuthenticateRequest
AuthorizeRequest
ResolveRequestCache
AcquireRequestState
PreRequestHandlerExecute
PostRequestHandlerExecute
ReleaseRequestState
UpdateRequestCache
EndRequest
PreSendRequestHeaders*
PreSendRequestContent*
Error*
The events identified by an asterisk (*) can occur at any time within the request; all others are listed in their calling order.

HTTP Handlers

HTTP handlers proces the request and are generally responsible for initiating necessary business logic tied to the request. Custom handlers must implement the System.Web.IHttpHandler interface. Additionally, a handler factory can be created which will analyze a request to determine what HTTP handler is appropriate. Custom handler factories implement the System.Web.IHttpHandlerFactory interface.

Dataset- Filter Row Through DefaultView

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolsConnectionString"].ConnectionString);
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter("select * from students", con);
Dataset ds = new DataSet();
adp.Fill(ds);
string message;
ds.Tables[0].DefaultView.RowFilter = "Name='Subhash'";
if (ds.Tables[0].DefaultView.Count != 0)
{
message = ds.Tables[0].DefaultView[0].Row["LastName"].ToString();
}
else
{
message = "";
}

Log4Net(for Making logger file)

//This is the link where you can read about log4Net
//open source provide by Microsoft

http://www.codeproject.com/KB/dotnet/Log4net_Tutorial.aspx
http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx

http://shiman.wordpress.com/2008/07/09/how-to-log-in-c-net-with-log4net-a-tutorial/Here is
great example for sending logfile into mail......

use the logger to log a few statements with various severity levels. log4net defines 5 such levels:
Log4Net supports five levels of logs with five methods.

Debug: fine-grained statements concerning program state, typically used for debugging;

Info: informational statements concerning program state, representing program events or behavior tracking;

Warn: statements that describe potentially harmful events or states in the program;

Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;

Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.

we have to add Log4Net Dll in Add reference section.

after that Inside the AssemblyInfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

and add some code in web.config file..

section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" requirePermission="false"/>


log4net debug="true">
appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
file value="Log4net\\log4net.txt"/>
appendToFile value="true"/>
rollingStyle value="Size"/>
maxSizeRollBackups value="10"/>
maximumFileSize value="50KB"/>
staticLogFileName value="true"/>
lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
layout type="log4net.Layout.PatternLayout">
conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n"/>
/layout>
/appender>
root>
level value="ALL"/>
appender-ref ref="RollingLogFileAppender"/>
/root>
/log4net>



add key="log4net.Internal.Debug" value="true" />
/appSettings>



//////////and Inside the .cs page

using log4net;//Add class in page

//Define Globally
private static readonly log4net.ILog log = log4net.LogManager.GetLogger("_Default");

//use like this
protected void Page_Load(object sender, EventArgs e)
{
try
{
int a = 0;
int b = 1;
int c = b / a;
}
catch (Exception ex)
{
log.Error(ex.Message, ex);//here is using
}
}

Friday, January 14, 2011

Compute with DataTable

DataTable Dtable=new DataTable();
DataColumn DColumn=new DataColumn("Salary",typeof(float));
DTable.Column.Add(DColumn);

DataRow DRow=DTable.NewRow();
DRow[0]=25000;
DTable.Rows.Add(DRow);

DRow=DTable.NewRow();
DRow[0]=30000;
DTable.Rows.Add(DRow);
//For Doolar Formate
string u= string.Format("{0:C}", ds.Tables[0].Compute("sum(Salary)", ""));
string u = string.Format("{0:0,000,000}", ds.Tables[0].Compute("sum(Salary)", ""));
//for Indian Rupee formate
string u = string.Format("{0:#,#.}", ds.Tables[0].Compute("sum(Salary)", ""));
Console.WriteLine(TotalSalary);

Thursday, January 13, 2011

C# IndexOf String Examples

IndexOf methods:

First, here we note that there are four IndexOf instance methods. The first two methods find the first indexes. They scan through the characters from the left to right. The second two find the last indexes, and they go from right to left.

IndexOf:This method finds the first index of the char argument. It returns -1 if the char was not found.

IndexOfAny:This method finds the first index of any of the char arguments. It returns -1 if none are found.

LastIndexOf:This finds the last index of the char argument. It returns -1 if the char was not found.

LastIndexOfAny:This finds the first index of any of the char arguments. It returns -1 if none are found.

Example:
string Path: C:\Documents and Settings\Jitendra\My Documents\Visual Studio 2008\Projects\WebApplication5\WebApplication5\

string k = stem.Web.HttpContext.Current.Request.PhysicalApplicationPath;
int o ;
k = k.Remove(k.LastIndexOf("\\"));
o = k.LastIndexOf("\\");
string appName1 = k.Substring(o+1);

Example:- string strFileName;
string strFile = strFileName.Substring(strFileName.LastIndexOf("\\")+1);

Wednesday, January 12, 2011

Special Character check through javascript

//The IndexOf method can be used to check if one character is inside of another. For example, suppose you want to check an email address to see if it contains the @ character. If it doesn't you can tell the user that it's an invalid email address.



script type="text/javascript" language ="javascript" >

function checkSpecialCharacters() {

var str = "'!#$%^&;*()";
var txtUserId = document.getElementById('txtUserId').value;
var txtPassword = document.getElementById('txtPassword').value;
var txt = txtUserId + txtPassword;

for (var i = 0; i < str.length; i++) { var char1 = str.substr(i, 1) if (txt.indexOf(char1) > -1) {
alert('special character(s) are not allowed in loginid/password');
//alert(obj.getMessage(196));
return false;
}
}
}
/script>

Tuesday, January 11, 2011

DefaultView

//DefaultView:filter a limited number of columns from a table:
//Distinct Data in DataTable with the Field of roleid,roleName,abbreviation........


DataSet infoDS=new DataSet();
DataTable dTable = infoDS.Tables[0].DefaultView.ToTable(true, "roleid", "roleName", "abbreviation");

for (int i = 0; i < dTable.Rows.Count; i++) { if (dTable.Rows.Count > 0)
{
string _RoleId = dTable.Rows[i]["roleid"].ToString();
string _RoleName = dTable.Rows[i]["roleName"].ToString();
string _Abbreviation = dTable.Rows[i]["abbreviation"].ToString();
}
}

Compute with DataTable

DataTable Dtable=new DataTable();
DataColumn DColumn=new DataColumn("Salary",typeof(float));
DTable.Column.Add(DColumn);

DataRow DRow=DTable.NewRow();
DRow[0]=25000;
DTable.Rows.Add(DRow);

DRow=DTable.NewRow();
DRow[0]=30000;
DTable.Rows.Add(DRow);

float TotalSalary=(float)DTable.Compute("Sum(Salary)","");
Console.WriteLine(TotalSalary);

Saturday, January 8, 2011

Dropdown bind through xml

XmlDocument xml = new XmlDocument();
string s =Server.MapPath("XMLfILE.xml");
string list = "/catalog/book";
xml.Load(s);
XmlNodeList xn = xml.SelectNodes(list);
foreach (XmlNode eleSourceNode in xn)
{
string ID = eleSourceNode.Attributes["id"].Value;
string author1 = eleSourceNode["author"].InnerText;
DRPLIST.Items.Add(new ListItem(author1 ,ID));
}


//XMLFILE.xml

?xml version="1.0"?>
catalog>
book id="bk101">
author>Gambardella, Matthew /author>
title>XML Developer's Guide /title>
genre>Computer /genre>
price>44.95 /price>
publish_date>2000-10-01 /publish_date>
description>
An in-depth look at creating applications
with XML.
/description>
/book>

book id="bk111">
author>O'Brien, Tim /author>
title>MSXML3: A Comprehensive Guide /title>
genre>Computer /genre>
price>36.95 /price>
publish_date>2000-12-01/publish_date>
description>
The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.
/description>
/book>
book id="bk112">
author>Galos, Mike/author>
title>Visual Studio 7: A Comprehensive Guide/title>
genre>Computer /genre>
price>49.95 /price>
publish_date>2001-04-16/publish_date>
description>
Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.
/description>
/book>
/catalog>

Link for Asp.net Architecture(Isapi.dll,httpcontext,hpptmodule)

http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp

Boxing and Unboxing(Convert value type to ref type and ref type to value type.)

int Val = 1;
Object Obj = Val; //Boxing
int i = (int)Val; //Unboxing