Monday, June 25, 2007

Indexer in C#

Indexers allow you to index a class or a struct instance in the same way as an array.
The systax is:

[modifier] [return type] this [argument list]
{
get
{
// codes for get accessor
}
set
{
// codes for set accessor
}
}

Here is the C# code:

public class PersonIndexer
{
int[] _age=new int[2];
string[,] _name=new string[2,2];

public int this[int i]
{
get { return _age[i]; }
set { _age[i] = value; }
}
public string this[int i,int j]
{
get { return _name[i, j]; }
set { _name[i, j] = value; }
}
}

static void Main()
{
PersonIndexer Ind = new PersonIndexer();
Ind[0] = 30;
Ind[1] = 40;

Ind[0, 0] = "sanjay";
Ind[0, 1] = "saini";
Ind[1, 0] = "Ram";
Ind[1, 1] = "Kumar";
MessageBox.Show(Ind[0, 0]+ " "+Ind[0, 1]+" is " + Convert.ToString(Ind[0])+" yrs. old.");
MessageBox.Show(Ind[1, 0] + " " + Ind[1, 1] + " is " + Convert.ToString(Ind[1]) + " yrs. old.");
}

Note:

1. If you declare more than one indexer in the same class, they must have different signatures.
2. They can not be static.
3. They can also be inherited.
4. They can be overridden in the derived class and exibit polymorphism.
5. They can be created abstract in the class.

Reference:
http://www.csharphelp.com/archives/archive140.html

Friday, June 15, 2007

Consuming Web Service from Client-Side code

We can consume web service from the client side using web service behaviour.The WebService behavior enables client-side script to invoke remote methods exposed by Web Services, or other Web servers, that support the SOAP and Web Services Description Language (WSDL) 1.1. This behavior provides developers the opportunity to use and leverage SOAP, without requiring expert knowledge of its implementation. The WebService behavior supports the use of a wide variety of data types, including intrinsic SOAP data types, arrays, objects, and XML data.
The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions.

WebService HTC File (webservice.htc)
The WebService behavior is encapsulated in an HTC file. Therefore, before you begin using the behavior in your own Web pages, download the WebService HTC File from the following location and copy it to a folder in your Web project.
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/samples/internet/behaviors/library/webservice/default.asp

Now suppose you want to consume web service from "http://localhost/MathsWebService/MathsService.asmx" location whose web method "Sum" that takes 2 integer values and returns integer sum, you want to call from the client side code.
Example-

< body onload="init()" >
< form id="form1" runat="server" >
< div id="service" style="behavior: url(webservice.htc)" >
< /div >
Num 1:< asp:TextBox ID="n1" runat="server" > < /asp:TextBox >< br />
Num 2:< asp:TextBox ID="n2" runat="server" > < /asp:TextBox >< br />
< asp:Button ID="btnsum" runat="server" OnClientClick="return fnSum()" Text="Sum" />
< /form >
< /body >

Note:We have added web service behaviour in our web page using style attribute.

< script language="JavaScript" >

function init()
{
service.useService("http://localhost/MathsWebService/MathsService.asmx?WSDL","MyMath");
}
function fnSum()
{
var intA = document.getElementById('n1');
var intB = document.getElementById('n2');
service.MyMath.callService(Mycallback,"Sum", intA.value, intB.value);
return false;
}
function Mycallback(result)
{
alert("Result = " + result.value);
}
< /script >

Note: webservice.htc file contains useService and callService methods.

This example will take 2 integer values from the textboxes and user click on Sum button the result will be displayed in the alert message.

Reference:
http://msdn2.microsoft.com/en-us/library/ms531032.aspx

Disco And UDDI

Web service Publishing means enabling a Web service user (consumer) to locate the web service description and instructing the consumer how they should interact with the Web service. The process of locating and interrogating Web service description is called the discovery process. There are two ways for the discovery of Web services, DISCO and UDDI.

Discovery with DISCO

In the past, most consumers found out about new Web Services (and their endpoint addresses) by browsing the Web, receiving an e-mail, or by word-of-mouth. But now you can publish a deployed Web Service using DISCO, you simply need to create a .disco file and place it in the vroot along with the other service-related configuration files.Or if you want to make discovery extremly simple for the counsumers, you can create a default web page of your website and place the url of the .disco file on it or place a like to redirect the users to the location of .disco file.

Web Services Discovery Tool (Disco.exe)

There are currently two methods available for discovering the DISCO document. One is a command-line client called disco.exe and the other is the Add Web Reference feature in Visual Studio® .NET.
Both methods generate .disco, .wsdl and .discomap files on the consumer's machine.

The following command line simply takes the URL of the DISCO document to discover.

disco.exe /out:< directory name > < web service path like- http://webservicehost/webservice/service.disco >

Now use another command-line utility called wsdl.exe that can generate Web Service proxies(.cs/.vb) from WSDL documents or the .discomap files generated by disco.exe. You can run it like so:

wsdl.exe /l:CS /out: < path of .cs file > < resuls.discomap >

Now you can use these .cs/.vb proxy classes in your code just like other source files.

Discovery with UDDI

The Universal Discovery, Description, and Integration (UDDI) project provides a global directory of Web Services. UDDI enables consumers to search and locate Web services if the consumer is not aware of the exact location of the service or the owner of the service. UDDI is for Web services like Google is for Web pages. UDDI allows us to easily find Web services based on a centralized and globally available registry of businesses which are accessible over the Internet. If you have a Web service and if you wish to publish it with UDDI then you need to visit the UDDI web site and register your service there.
Microsoft and IBM (who, with Ariba, are jointly developing UDDI) both have operating sites up and running today at http://uddi.microsoft.com and http://www-3.ibm.com/services/uddi/, respectively.


Reference:
http://msdn.microsoft.com/msdnmag/issues/02/02/xml/

Thursday, June 14, 2007

Implementing AJAX in asp.net application using XMLHttp

XMLHttp is an object that was originally designed by Microsoft to provide client-side access to XML documents on remote servers through the HTTP protocol. It exposes a simple API, which allows you to send requests (GET/POSTS) and get the resultant XML, HTML or binary data.

Here, I am using same problem that I have used in the previous post.

Problem: We have a dropdown server control on our web page that we want to populate with users name from the user table in the database when user clicks on the populate button without flickering effect on the web page.

Follow these steps for implementing ajax solution to this problem in your web application using XMLHttp.

1. Add dropdown control and Pupulate button on the web page.

User Name : < asp:DropDownList ID="ddlUsers" runat="server" Width="100%" >

< input id="btnFill" onclick="getusername()" type="button" value="Fill Users using XMLHttp" />

2. Write following java script on the aspx page.

< script language="javascript" type="text/javascript" >
function getusername()
{
var Url ;
Url ='ProcessXMLHttp.aspx';
var oServerXMLHTTP = createXMLHttp();
/*oServerXMLHTTP.open("GET", Url, false);*/
oServerXMLHTTP.open("POST", Url, false);
// because we're using POST, we need to set some headers.
oServerXMLHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
oServerXMLHTTP.setRequestHeader("Content-Length",0)

try
{
oServerXMLHTTP.send();
var Response =oServerXMLHTTP.responseText.split(',');

var user=document.getElementById('<%=ddlUsers.ClientID%>');
var tab=document.createElement('table');
for(i=0;i < Response.length;i++)
{

user.options[user.options.length]=new Option(Response[i],i);
}

}
catch(e)
{

}
return true;

}
function createXMLHttp()
{
if (typeof XMLHttpRequest != "undefined")
{
return new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
var aVersions = [ "MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp","Microsoft.XMLHttp"];
for (var i = 0; i < aVersions.length; i++)
{
try
{
var oXmlHttp = new ActiveXObject(aVersions[i]);
return oXmlHttp;
}
catch (oError)
{
//Do nothing
}
}
}
throw new Error("XMLHttp object could be created.");
}
< /script >

In this script I have used post method for http request, you can also use Get method that I have commented out in the script.

3. Now create ProcessXMLHttp.aspx page that you have passed as a url to the open method of XMLHttp object and write following code in its cs file.

protected void Page_Load(object sender, EventArgs e)
{
GetUsers();
}

public void GetUsers()
{
IBLLService ObjBLLService = BLLServiceFactory.GetBLLService();
DataSet Ds = ObjBLLService.GetData();

Response.Clear();
string str=String.Empty;
for (int i = 0; i < Ds.Tables[0].Rows.Count; i++)
if(i==Ds.Tables[0].Rows.Count-1)
str = str + Ds.Tables[0].Rows[i][0].ToString() ;
else
str = str + Ds.Tables[0].Rows[i][0].ToString() + ",";

Response.Write(str);
Response.End();
}

In the GetUsers method, Replace the following lines with your own code to get the users name data from the DB.

IBLLService ObjBLLService = BLLServiceFactory.GetBLLService();
DataSet Ds = ObjBLLService.GetData();

4. Now you are finished with the coding, its time to test it.

Implementing AJAX in asp.net application using Ajax.dll

Problem: We have a dropdown server control on our web page that we want to populate with users name from the user table in the database when user clicks on the populate button without flickering effect on the web page.

Follow these steps for implementing ajax solution to this problem in your web application using ajax.dll

1. Download the latest version of ajax.dll from the following link:

http://ajax.schwarz-interactive.de/csharpsample/default.aspx

2. Add the httphandler for ajax in the web.config file of your web app.
Example-
< httpHandlers >
< add verb="POST, GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
< /httpHandlers >

3. Register the aspx.cs class with the ajax.
Exlample-
protected void Page_Load(object sender, EventArgs e)
{

Ajax.Utility.RegisterTypeForAjax(typeof(AjaxDemo));

}

AjaxDemo -is the class name.


4. Now create the serverside ajax method in the .aspx.cs file.
Example-

[Ajax.AjaxMethod]
public DataSet GetUsers()
{
IBLLService ObjBLLService = BLLServiceFactory.GetBLLService();
DataSet Ds=ObjBLLService.GetData();
return Ds;
}
In the GetUsers method, Replace the existing code with your own code to get the users name data from the DB.

5.Write following java script on the .aspx page.

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

function getusername()
{
AjaxDemo.GetUsers(fillusers);
}
function fillusers(Response)
{
if(Response!=null)
{
var tab=Response.value.Tables[0];
var user=document.getElementById('<%=ddlUsers.ClientID%>');
for(i=0;i < tab.Rows.length;i++)
{
var ro=tab.Rows[i];
user.options[user.options.length]=new Option(ro.firstname,i); // firstname is the field name in the DB table.
}
}
}
< /script >

Add dropdown control and Pupulate button on the web page.

User Name : < asp:DropDownList ID="ddlUsers" runat="server" Width="100%" >

< input id="btnFill" onclick="getusername()" type="button" value="Fill Users using Ajax dll" />

6. We are finished with the coding now its time to test it.

The Document Object Model (DOM)

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated With DOM API, programmers can build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using DOM API.
Its a W3C specification, one important objective for the DOM is to provide a standard programming interface that can be used in a wide variety of environments and applications.

Reference:
http://www.w3.org/TR/DOM-Level-2-Core/introduction.html

Wednesday, June 13, 2007

Service-oriented architecture (SOA)

SOA is an architectural style whose goal is to achieve loose coupling among interacting software agents. A service is a unit of work done by a service provider to achieve desired end results for a service consumer. Both provider and consumer are roles played by software agents on behalf of their owners.
SOA-based systems inter-operate based on a formal definition (or contract, e.g., WSDL) that is independent of the underlying platform (such as Java, .NET etc) and programming language (like. C#, Java). Services written in C# running on .NET platforms and services written in Java running on Java EE platforms, for example, can both be consumed by a common composite application. Applications running on either platform can also consume services running on the other as Web services, which facilitates reuse.
For more information on the topic checkout following references.

Reference:
http://en.wikipedia.org/wiki/Service-oriented_architecture
http://webservices.xml.com/pub/a/ws/2003/09/30/soa.html

Session State Management using SQLServer

To configure session state management in a web application we have to use the sessionState section of the web.config file. sessionState can have following mode.

1.Off - Indicates that the session state is turned off.
2. InProc - session kept as live objects in web server (aspnet_wp.exe). Use "cookieless" configuration in web.config to add the sessionId onto the URL.
3. StateServer - session serialized and stored in memory in a separate process (aspnet_state.exe). State Server can run on another machine.
4. SQLServer - session serialized and stored in SQL server.
5. Custom - Indicates that you will have a custom mechanism of session storage using a provider model of ASP.NET.

Now to maintain session state with SQL server,first, we have to configure SQL server.

Actually we need special database to maintain session state with the SQL server and .Net Framework provides us sql scripts for this purpose. Following is the list of these sql scripts.

-> InstallSqlState.sql-- Contains scripts to set up database for state management. Its creates database "ASPSTATE" that contains stored procedures that create tables in tempdb. The tables(ASPStateTempSessions and ASPStateTempApplications) in tempdb are where session state is actually stored. Thus, when the SQL Server is shutdown, all session state is lost. It also creates a job called State_Job_DeleteExpiredSessions to delete expired sessions from tempdb. Recall that ASP.NET does not keep session resources alive indefinitely. To support this feature when a SQL Server is used to maintain state, the SQL Server Agent must be running so that the expired session deletion job runs as needed.

-> UninstallSqlState.sql-- Contains scripts for droping the database (ASPSTATE) and all supporting objects (e.g., the job to delete expired sessions). But before running this script, stop the Web server service to avoid any error Or use the SQL Server Enterprise Manager and find the processes accessing the ASPState database and delete them.

-> InstallPersistSqlState.sql-- contains scripts to set up database for persistent state management. It causes the session state data to be stored in permanent tables in ASPState instead of temporary tables in tempdb.

-> UninstallPersistSqlState.sql-- Contains scripts for droping the database (ASPSTATE) and all supporting objects (e.g., the job to delete expired sessions).

-> InstallSqlStateTemplate.sql / UninstallSqlStateTemplate.sql--
These are templates files for installing the ASP.NET session state SQL objects
on a database other than the default 'ASPState'.
To create your own script files based on the template:
1. Create your own script files by coping the two template files.
2. Decide a name for your database (e.g. MyASPStateDB)
3. In your own script files, replace all occurences of "DatabaseNamePlaceHolder"
by your database name.
4. Install and uninstall ASP.NET session state SQL objects using your own
script files.

You can run these file either in SQL Query Analyzer or using command line tool aspnet_regsql.exe.

Now use the sessionState section of the web.config file to configure an ASP.NET Web application to use a SQL Server for session state management.

< sessionState
mode="SQLServer"
stateConnectionString="tcpip=localhost"
sqlConnectionString="data source=localhost;user id=sa;password=kkak"
cookieless="false"
timeout="20" />

In case you have setup custom database for the session state management using InstallSqlStateTemplate.sql then add database name in the sqlConnectionString. Like...

< sessionState
mode="SQLServer"
stateConnectionString="tcpip=localhost"
sqlConnectionString="data source=localhost; database=MyASPStateDB;user id=sa;password=kkak"
cookieless="false"
timeout="20" />

Note: The session state timeout interval is specified by using the timeout parameter.By default ASP .NET uses cookies to identify which requests belong to a particular session.If cookies are not available, a session can be tracked by adding a session identifier to the URL. To disable cookies, set sessionState cookieless="true".

Reference:
http://www.dbazine.com/sql/sql-articles/cook9

Difference between Destructor, Dispose and Finalize methods

Here, I have given a brief description of these 3 methods.

1. Destructor
They are special methods that contains clean up code for the object. You can not call them explicitly in your code as they are called implicitly by GC. In C# they have same name as the class name preceded by the "~" sign. Like-

Class MyClass
{

~MyClass()
{
.....
}
}

In VB.NET, destructors are implemented by overriding the Finalize method of the System.Object class.

2. Dispose
These are just like any other methods in the class and can be called explicitly but they have a special purpose of cleaning up the object. In the dispose method we write clean up code for the object. It is important that we freed up all the unmanaged recources in the dispose method like database connection, files etc.
The class implementing dispose method should implement IDisposable interface.A Dispose method should call the GC.SuppressFinalize method for the object it is disposing if the class has desturctor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalize method.
Reference: http://msdn2.microsoft.com/en-us/library/aa720161(VS.71).aspx

3. Finalize
A Finalize method acts as a safeguard to clean up resources in the event that your Dispose method is not called. You should only implement a Finalize method to clean up unmanaged resources. You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically. Finalize method is called by the GC implicitly therefore you can not call it from your code.

Note: In C#, Finalize method can not be override, so you have to use destructor whose internal implementation will override the Finalize method in MSIL.But in the VB.NET, Finalize method can be override because it does support destructor method.

Tuesday, June 12, 2007

Error: Do not override object.Finalize. Instead, provide a destructor.

You cannot call or override the Object.Finalize method from the C#. Because C# provides destructors as the mechanism for writing finalization code. You must use the destructor syntax in C# to perform cleanup operations. This syntax is convenient because it implicitly calls the Finalize method for an object's base class. This guarantees that Finalize is called for all levels of destructors from which the current class is derived.

Suppose you have written a destructor in your code, like this:

~DemoClass()
{
// Perform some cleanup operations here.
}

This code implicitly translates to the following:

protected override void Finalize()
{
try
{
// Perform some cleanup operations here.
}
finally
{
base.Finalize();
}
}

So if you have a destructor in your class and your are also trying to override Finalize function then you wil l get following build error.

"Type already defines a member called 'Finalize' with the same parameter types."

ClickOnce

ClickOnce is new windows based application deployment technology. It has made the deployment of windows based application quite easy. It’s rightly called clickonce because end-user can install application published using this technology by just single click.

To publish your windows application follows these steps:

1. Open the property of your windows project and choose the publish tab.
2. Now click on publish wizard button.
3. Publish wizard window will open, alternatively you can open this wizard from Build->Publish locattion in the menue.
4. Now specify the location on the harddisk where you want to create publish folder and click next.
5. Now choose the installation method like from website,from UNC path or from CD and click next.
6. Then choose whether the application will be available offline or not and click next.
7. Last, click on finish.

If you have choosen installation from website option then clickonce application will open in the IE. On the web page you have to just click on install button to install the application.

ClickOnce applications can be deployed via web servers, file servers or CDs. You can also configure during publishing whether the application should check for an update or not.

Reference: http://msdn2.microsoft.com/en-us/netframework/aa497348.aspx

SessionId changes with every request in the asp.net2.0 application

For any web programmer, its obvious to think and believe that SessionId remains same through out the user sessiona and it was right till asp.net1.1. But in asp.net2.0, this behavior has changed. In the asp.net application new sessionid is returned with the response to every request.

According to MSDN the reason/solution is:

"When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object."

IIS 6.0 Process Model


The IIS 6 process model is the default model on machines running Windows 2003 Server operating system. It introduces several changes and improvements over the IIS 5 process model. One of the biggest changes is the concept of application pools. On IIS 5.X all web applications, that is, all AppDomains, were hosted by the ASP.NET worker process. To achieve a finer granularity over security boundaries and personalization, the IIS 6 process model allows applications to run inside different copies of a new worker process, w3wp.exe. Each application pool can contain multiple AppDomains and is hosted in a single copy of the worker process. In other words, the shift is from a single process hosting all applications to multiple processes hosting each an application pool. This model is also called the worker process isolation mode.
Another change is that in IIS 6 request is received at lower kernal level and routed by http.sys to the application pools unlike in IIS 5.X where request is received by a user process called inetinfo.exe.
Each application pool has its own w3wp.exe worker process. The w3wp.exe worker process, differently from the aspnet_wp.exe process used in IIS 5 model, isn’t ASP.NET specific, and is used to handle any kind of requests. The specific worker process then decides which ISAPI modules to load according to the type of resources it needs to serve.

Reference: http://dotnetslackers.com/articles/iis/ASPNETInternalsIISAndTheProcessModel.aspx

IIS 5.X Process Model


This is the default process model available on Windows 2000 and XP machines. As mentioned it consists in the IIS inetinfo.exe process listening by default on the TCP port 80 for incoming HTTP requests and queuing them into a single queue, waiting to be processed. If the request is specific to ASP.NET, the processing is delegated to the ASP.NET ISAPI extension, aspnet_isapi.dll. This, in turn, communicates with the ASP.NET worker process, aspnet_wp.exe via named pipes and finally is the worker process which takes care of delivering the request to the ASP.NET HTTP runtime environment.
Therefore all ASP.NET web applications hosted on IIS are actually hosted inside the worker process, too. However, this doesn’t mean that all the applications are run under the same context and share all their data. As mentioned, ASP.NET introduces the concept of AppDomain, which is essentially a sort of managed lightweight process which provides isolation and security boundaries. Each IIS virtual directory is executed in a single AppDomain, which is loaded automatically into the worker process whenever a resource belonging to that application is requested for the first time. Once the AppDomain is loaded – that is, all the assemblies required to satisfy that request are loaded into the AppDomain – the control is actually passed to the ASP.NET pipeline for the actual processing. Multiple AppDomains can thus run under the same process, while requests for the same AppDomain can be served by multiple threads. However, a thread doesn’t belong to an AppDomain and can serve requests for different AppDomains, but at a given time a thread belongs to a single AppDomain.

Reference: http://dotnetslackers.com/articles/iis/ASPNETInternalsIISAndTheProcessModel.aspx

The ASP.NET Process Model

Uder IIS 5.X, all ASP.NET-related requests received by the inetinfo.exe are delegated to aspnet_isapi.dll. It dispatches these request to an external worker process called aspnet_wp.exe. The aspnet_isapi.dll, hosted in the IIS process inetinfo.exe, passes the control to aspnet_wp.exe, along with all the information concerning the incoming request. The communication between the two is performed via named pipes, a well known mechanism for IPC (Inter Process Communication). The ASP.NET worker process performs a considerable number of tasks, together with the ISAPI extension. Each web application, corresponding to a different virtual directory hosted on IIS, is executed in the context of the same process, the ASP.NET worker process. To provide isolation and abstraction from the execution context the ASP.NET model introduces the concept of Application Domains, in brief AppDomains. They can be considered as lightweight processes.

Under IIS 6, incoming requests are handled by Http.sys program at lower – Kernel – level. Then It routes the request to the right application pool. A worker process (W3wp.exe) is attached with every application pool.
In IIS6.0, aspnet_wp.exe process is not used, in favour of another process called w3wp.exe. Furthermore, inetinfo.exe is no longer used to forward HTTP requests to ISAPI extensions, although it keeps running for serving other protocols requests.

.NET 2.0 transaction model

Currently .net provides 3 transaction models.

1. Using ADO.NET data providers.
2. Using enterprise services transaction.
3. Using System.Transactions for .NET Framework 2.0

The first 2 models have some shortcoming that we are going to discuss now.

1. The ADO.NET transaction model

In the transaction model we can not update more than one database in single transaction.

Lets have an example:

SqlConnection con = new SqlConnection("Connection String");
SqlTransaction tr = con.BeginTransaction();
SqlCommand cmd = new SqlCommand("Update query", con, tr);
try
{
cmd.ExecuteNonQuery();
tr.Commit();
}
catch (Exception exc)
{
tr.Rollback();
}
finally
{
con.Close();
}

In the code above, the transaction object is actually created from a connection to a single database. So there is no direct way of grouping updates to more than one database into a single transaction.

2. Enterprise services transactions

Though this model remove the shortcoming of the previous model as it provides distributed transaction manager that enable you to have transactions independent of the database but it also has some shortcomings:

* Class needs to inherit from the ServicedComponent class to implement enterprise service transactions that restrict your class from inheriting from any other base class.
* It takes transaction as a distributed transaction. Even if single database is involved, enterprise services will still take it as a distributed transaction and handle it as such. As a result, it using more resources than needed.
* The assembly you create need to be deployed in component services to run under the COM+ context.For that assembly must be strong named and registered using regsvcs.exe utility.

3. Introducing System.Transactions

The System.Transactions model is a new addition to the .NET 2.0 framework. It addresses the shortcomings in the

above discussed models, and brings the best features of the ADO.NET and enterprise services transaction models

together.
In System.Transactions, you have the TransactionScope object you can use to scope a set of statements and group

them under one transaction.
Example -

C# Code
class AccountManager
{
void TransferCash(Account from, Account to, double amt)
{
using(TransactionScope scope=new TransactionScope())
{
from.Withdraw(amt);
to.Deposit(amt);
scope.Complete();
}
}
}

As you can see in the code above, class needs not to inherit from any other class. System.Transactions is smart

enough to decide whether to use a distributed transaction or not. In case of single database is involved, it

uses lightweight transaction and if there are multiple databases involved, it will use a distributed

transaction.

Reference: http://www.simple-talk.com/dotnet/.net-framework/.net-2.0-transaction-model/

Monday, June 11, 2007

Internet Explorer does not show contents of App_offline.htm

It happens because under default configuration, Internet Explorer first looks at the page size and if it's less than 512 bytes 404 status code friendly message is displayed instead of your App_offline.htm content.

So if you use the app_offline.htm feature, you should make sure you have at least 512 bytes of content within it to make sure that IE shows its content instead of 404 status code friendly message.

Configure "Show Friendly Http Errors" feature of IE6.

This can be configured in the Tools->Internet Options->Advanced tab within IE, and is on by default with IE6.

Temporarily shut down your ASP.NET 2.0 web application

There is a simple way to bring down your ASP.NET 2.0 application. The only thing you have to do is to create simple html file called App_offline.htm and add it to your ASP.NET 2.0 web application root directory.

After you add this file in your web app, ASP.NET 2.0 runtime stops the application and unloads whole application domain. It stops processing new incomming requests and serves your App_offline.htm file insted. Because whole application domain is unloaded all application files and assemblies are now unlocked and you can make any necessary changes.

When you want to make your web application online, just exclude/delete/rename App_offline.htm file from your web project.

when using App_offline.htm file to temporarily shut down your ASP.NET 2.0 web application. When this file is present, all requests are served with this file and returned with status code 404 Not Found whereas web application pages are only temporarily unavailable, but this status code says they were not found.Search engine spiders would interpret this status code and remove requested page from their search database.

Different types of GNU licence

GNU is a recursive acronym for "GNU's Not Unix". The GNU project was announced in 1983 by Richard Stallman with the goal of creating a complete operating system -- called the GNU system or simply GNU -- that is free software, meaning that users are allowed to copy, modify and redistribute it. The GNU project is now carried out under the auspices of the Free Software Foundation (FSF).

There are 3 types of GNU licence.

1. GPL - GNU General Public Licence

Under this licence, disclosure of source code to the target audience is necessary.

2. LGPL - GNU Lesser General Public License

It applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

3. GFDL - GNU Free Documentation License

The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially.

Reference: http://www.gnu.org/licenses/

Merging Data of the DataTables in the ADO.NET1.1

Here, I am giving 3 code samples for merging data from the datatables.

//common code

SqlConnection con=new SqlConnection(@"server=localhost\sqlexpress;database=demo;uid=sa;pwd=kkak");
con.Open();
SqlDataAdapter da1=new SqlDataAdapter("select * from table1",con);
SqlDataAdapter da2=new SqlDataAdapter("select * from table2",con);

// sample -1

DataSet ds1=new DataSet();
da1.Fill(ds1,"table1");
DataSet ds2=new DataSet();
da2.Fill(ds2,"table2");
ds1.Merge(ds2.Tables["table2"]);

// sample -2

DataSet ds1=new DataSet();
da1.Fill(ds1,"table1");
DataTable dt2=ds1.Tables["table1"].Clone();
da2.Fill(dt2);
ds1.Merge(dt2);

// sample -3

DataSet ds1=new DataSet();
da1.Fill(ds1,"table1");
DataSet ds2=new DataSet();
da2.Fill(ds2,"table2");
for(int i=0;i< ds2.Tables["table2"].Rows.Count;i++)
{
DataRow dr=ds2.Tables["table2"].Rows[i];
ds1.Tables["table1"].ImportRow(dr);
}

How to make website SSL enable.

Secure Socket Layer(SSL) is used for secured communication over the internet. Banking services, e-commerce etc. websites implement SSL so that they can be accessible through Https protocol for secured communication. If you wish, you can configure only a section of your website should be accessible through https and rest of the website can be accessed through http protocol. Like in the online shopping website only the payment section of the website can be configured to be access through https protocol.

In order to make website SSL enabled, we need a certificate. There are many different web sites that provide certificates for use on IIS like www.verisighn.com.
Although, windows comes pre-installed with some certificates of trusted companies. These certificates can be viewed by running certmgr.msc from the comsole window. For any certificate in the list of trusted certificates your program(IE), will not give you warning when you access their website with SSL enabled.

To show how to setup an SSL website we will use a trial certificate that Verisign provides to anyone. Before that create the certificate request.

Follow these steps:

1. Open the IIS manager window.
2. Right click on the website/virtual directory and choose property window.
3. In the Property window choose Directory Security tab and click on server certificate button.
4. Certificate Wizard window will open, click on next and choose Create a new certificate option. Now follow the wizard steps.
5. The web server certificate wizard will create a certificate request and it will ask you where you want to save it to. Save it somewhere where you can easily access it because you will need to open up the file and submit it to Verisign in order for a certificate response to be sent back to you.
6.Open the text file that contains certificate request and copy its content.
7. Now open http://www.verisign.com/ in IE. Once the page has loaded up find the link "SSL Trial ID" and click on it.
8. The Verisign web site will now take you though the process of obtaining a certificate.
9. In this process on the step "Submit CSR" enter in the certificate request that you copied earlier and click on continue.
10. After the process steps complete, your certificate response will be e-mailed to you.
11. Now check your mail account for the certificate response,At the bottom of the e-mail Verisign sent you is the certificate that you need. Copy this text from the BEGIN CERTIFICATE to the END CERTIFICATE include those lines.
12. Open notepad, paste the text into it and save the file as response.txt.
13. Go back to your web site's Properties dialog and click on the Directory Security tab. Click on the Server Certificate button. Click "Next" until you come to the screen shown. Make sure the "Process the pending request and install the certificate" option is selected. Click Next.
14.In the next screen click on browse to browse the response.txt file, click on next and complete the rest of the steps.
15. Click on the "Edit" button located in the Directory Security tab of the web site's Properties dialog.
16. Check the "Require secure channel (SSL)" checkbox and click on OK.

Now Our site have become SSL enabled.To access your SSL enabled website use https instead of http.


To configure a perticular web page inntead of whole site to be accessed using https protocol, right click on that perticular web page in the IIS manager and open its property window.Click on the "Edit" button located in the Directory Security tab of the web site's Properties dialog and Check the "Require secure channel (SSL)"
checkbox and click on OK.

Error : 'RSA key container could not be opened.'

This error occurs if the user does not have the right to access the key container.

Use following command to give permission to the web suer a/c "ASPNET"

aspnet_regiis -pa "Key Container Name" "ASPNET"

Like - aspnet_regiis -pa "NetFrameworkConfigurationKey" "ASPNET"

Note -Key container name could be found in the machine.config file under configProtectedData section.

Path of machine.config file is %WinDir%\Microsoft.Net\Framework\v2.0\Config

Encrypt Configuration Sections in ASP.NET 2.0 Using RSA

RSAProtectedConfigurationProvider uses the RSA public key encryption to encrypt and decrypt data.It supports machine-level and user-level key containers for key storage. Machine-level key containers are available to all users, but a user-level key container is available to that user only.

Use RSA machine key containers if application runs on its own dedicated server with no other applications or you want multiple app use same key. It stores in the following folder:

\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys

Use a user-level key container if you run your application in a shared hosting environment and you want to make sure that your application's sensitive data is not accessible to other applications on the server. It stores in the following folder:

\Documents and Settings\{UserName}\Application Data\Microsoft\Crypto\RSA


By default RSAProtectedConfigurationProvider is configured to use the machine-level key container.

Following command is used to encrypt configuration section in web.config file with RSA:
aspnet_regiis -pe "section name" -app "/application name"

section name - appSettings, connectionStrings, identity, sessionState etc.

Like - aspnet_regiis -pe "connectionStrings" -app "/MyWebApplication"

If you are using asp.net web server then give physical path of web app and use -pef option like -

aspnet_regiis -pef "connectionStrings" -app "c:\MyWebApplication"

To grant access to the ASP.NET application identity use following command:

aspnet_regiis -pa "NetFrameworkConfigurationKey" "ASPNET"

If you are not sure which identity to use, check the identity from a Web page by using the following code:

using System.Security.Principal;
...
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(WindowsIdentity.GetCurrent().Name);
}


Decrypt configuration section in web.config file with RSA using following command:
aspnet_regiis -pd "section name" -app "/application name"

If you are using asp.net web server then give physical path of web app and use -pdf option like -

aspnet_regiis -pdf "connectionStrings" -app "c:\MyWebApplication"


Following sections can not be encrypted :

processmodel
runtime
mscorlib
startup
system.runtime.remoting
configprotecteddata
satelliteassemblies
cryptographysettings
cryptonamemapping
cryptoclasses>

Reference:

http://msdn2.microsoft.com/En-US/library/ms998283.aspx
http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=229

Introduction of XHTML

XHTML is a web standard which has been agreed by the W3C. Its a combination of XML and HTML.XML was designed to describe data and HTML was designed to display data.Therefore, by combining HTML and XML, and their strengths, we got a markup language XHTML for writing better formatted web page.

Following are some of XHTML feature:
1. Its a case sensitive.
2. All tags must be in lower case.
3. All tags must use id instead of name attribute.
4. Web page must have DOCTYPE tag.
5. DOCTYPE could be strict, transitional or frameset.
6. All attributes of a tag must be quoted.
7. Opening tag must match with closing tag for container tags.
8. Empty tags like line break < br > must be followed by space and forword slash like - < br />.
9. Attributes must not be shortened. Like in case of checkbox tag write < input type="checkbox" checked="checked" > instead of < input type="checkbox" checked >.

Reference:
http://www.freewebmasterhelp.com/tutorials/xhtml
http://www.w3schools.com/xhtml/

Using Threads Versus Using Thread Pools

ThreadPools reduces thread creation and termination overhead because it uses single thread from the thread pool to execute multiple tasks serially.Whereas in the normal senario in a multithreaded applcation they are executed on seperat thread parallely.To understand it better, lets assume a senario, Suppose we have 5 tasks that take 1ms time each to execute and 1ms for creation and 1ms for termination.

In case of using ThreadPool(Suppose SetMaxThreads=1)
The thread creation/termination overhead will be 2ms because single thread is created and the work done will be of 5ms.

In case of using Thread
The thread creation/termination overhead will be 10ms because 5 threads will be created/terminated seperatly and the total work done will be of 5ms.

So the conclusion is that in case of executing multiple breif tasks ThreadPool is more sutiable and in case of executing lengthy tasks Threads are better option.

Reference : http://blogs.msdn.com/oldnewthing/archive/2007/04/03/2014992.aspx

Sunday, June 10, 2007

Implementing ThreadPool using C#

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. Thread pool reduces the overhead of creating and destroying threads because when a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. Thus enabling applications to avoid the cost of creating a new thread for each task.
There is one thread pool per process. The thread pool has a default size of 25 threads per available processor. The number of threads in the thread pool can be changed using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.
Example-


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;


class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
// Queue the task.
for (int i = 0; i < 3; i++)
{
switch (i)
{
case 0:
ThreadPool.QueueUserWorkItem(new WaitCallback(Task1));
break;
case 1:
ThreadPool.QueueUserWorkItem(new WaitCallback(Task2));
break;
case 2:
ThreadPool.QueueUserWorkItem(new WaitCallback(Task3), (object)"Task3");
break;
}
MessageBox.Show("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread.Sleep(3000);
}
}
// This thread procedure performs the task.
static void Task1(Object obj)
{
// No object was passed to QueueUserWorkItem, so
// obj is null.
MessageBox.Show("Hello from Taks1.");
}
static void Task2(Object obj)
{
// No object was passed to QueueUserWorkItem, so
// obj is null.
MessageBox.Show("Hello from Taks2.");
}
static void Task3(Object obj)
{
// An object was passed to QueueUserWorkItem that has a string value, so
// obj is cast to string type.
string str = (string)obj;
MessageBox.Show("Hello from " + str +".");
}
}

Friday, June 8, 2007

To show assembly from the GAC in the Add Reference dialog box

When you add an assembly in the GAC(c:\windows\assembly), it does not show in the add reference dialog box automatically, instead you have to make it visible in the add reference dialog box by updating the system registery.

Following are the steps:
1. Run the regedit.exe
2. Registry Editor will open, now traverse to the following location
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NetFramework\AssemblyFolders]
3.Now right click on AssemblyFolders and Create a new key with the name of the folder from where you have added the assembly into the GAC (make sure that assembly should be there).
4. Now right click on the default value under the newly created key, choose modify option a dialog box will popup, enter the path of the assembly folder in the value data and click on ok.
5. Close the registry editor and restart the VS.Net.

If you want this setting for all the users of this machine then follow the above steps under [HKEY_LOCAL_MACHINE]

.Net application implementing indexing service is throwing an error

If you are implementing indexing service in your application, most likly you may encounter with an error with the following description-

An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Access is denied: 'MyWebApp'.
Source Error:
Line 198:

This error occurs because of the Microsoft Indexing Services which scans the Temporary ASP.NET Files and while doing so, the system puts a lock on the same.
To resolve this, the following steps need to be carried out:-

1. Start - Settings - Control Panel - Administrative Tools - Computer mangement.
2. Expand the services and applications node and select the Indexing service node.
3. Expand the Indexing Service Node and then select and expand the System Node.
4. Right click on Directories and select new directory. browse the path to the temporary asp.net files c:\winnt\microsoft.net\framework\v1.1.4322\.
5. Select the temporary asp.net files. give ok and then select the "NO" in the Include in index radiobutton.
6. give ok and then stop and start the indexing service.
this should solve the problem.

How to implement Indexing service in the asp.net application?

Microsoft Index Service allows the contents of files on the machine to be indexed to enable free-text searching. It uses catalog to maintain the indexes. A catalog can be created or existing catalogs can be re configured.
First of all you have to create a new catalog. Following are the steps:

1. Open the Computer Management tool available in Administrative Tools.
2. In the tree view under Services And Application node click on Indexing Service.
3. You will see the list of existing catalogs in the right panel.
4. Right-click on 'Indexing Service' and select 'New' and 'Catalog' from the list that appears. You will be presented with the Dialogue box
5. Give the catalog a name like “Search” and location of the catalog
6. Press 'OK' to continue, note that the server will inform you that the 'Catalog will remain off-line until service is restarted'.
7. Add directory whose content you want to get indexed.
8. Open the properties of it
– In the tracking tab choose your site in the WWW Server dropdown.
– In the Generation tab check the Generate abstracts.

Reference - http://www.simongibson.com/intranet/indexserv/

For accessing catalog in your .net application, you have to get Interop.Cisso.dll and add its reference into your project. Following is the code sample:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Text;
using System.ComponentModel;
using Cisso;

void SearchProcess()
{

if(Request.QueryString[ "qry" ].ToString()!="")
{
string SearchString= Request.QueryString[ "qry" ].ToString();

OleDbDataAdapter DataAdapterObj =new OleDbDataAdapter();
DataSet IndexSearchDS =new DataSet("IndexServerResults");// ' give the dataset a name
CissoQueryClass Qry=new CissoQueryClass();
CissoUtilClass Util=new CissoUtilClass();
StringBuilder strbldSearch =new StringBuilder(SearchString);
strbldSearch.Append(" and not #filename *.inc");
strbldSearch.Append(" and not #filename *.css");
strbldSearch.Append(" and not #filename *.vb");
strbldSearch.Append(" and not #filename *.cs");
strbldSearch.Append(" and not #filename *.js");
strbldSearch.Append(" and not #filename *.xml");
strbldSearch.Append(" and not #filename *.ascx");
strbldSearch.Append(" and not #filename *.log");
strbldSearch.Append(" and not #filename *.config");

Qry.Query = strbldSearch.ToString();
Qry.Catalog = "Search";// ' name of your IndexServer Catalog
Qry.SortBy = "rank[a]";// ' a-ascending, d-descending
Qry.Columns = "Rank, DocTitle, vpath, Path, Filename, Size, Write, Characterization,";
Qry.MaxRecords = 250;// ' for best performance keep below 500
Util.AddScopeToQuery(Qry, "/", "deep");
DataAdapterObj.Fill(IndexSearchDS,Qry.CreateRecordset("nonsequential"),"IndexServerResults");
}
}

Change the script map of the asp.net application

Following options can be used to change the script map of a asp.net application.
1. Use IIS Manager.
step 1. Open the IIS manager windowstep 2. write click the asp.net app and choose the properties option.step 3. Go to the ASP.NET tab in the properties window and choose the appropriate version from the dropdown.

2. Use ASP.NET IIS Registration Tool (Aspnet_regiis.exe)
When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET ISAPI version mapped to an ASP.NET application determines which version of the common language runtime (CLR) is used for the application. The ASP.NET IIS Registration Tool (Aspnet_regiis.exe) allows an administrator or installation program to easily update the script maps for an ASP.NET application to point to the ASP.NET ISAPI version that is associated with the tool. The tool can also be used to display the status of all installed versions of ASP. NET, register the ASP.NET version that is coupled with the tool, create client-script directories, and perform other configuration operations.

For .Net Framework2.0
step 1. Go to the path -> %winDir%\Microsoft.Net\Framework\v2.0.50727\
step 2. Run following command-
aspnet_regiis.exe -s W3SVC/1/root/

Note- If an error occurs with the following description "The error indicates that this version of asp.net must be registered on the machine."

Try following command - aspnet_regiis -i

Above command installs the ASP.NET version that is associated with the ASP.NET IIS Registration tool and updates the script maps of all existing ASP.NET applications. Note that only applications that are currently mapped to an earlier version of ASP.NET are affected.

The following command installs the ASP.NET version that is associated with the tool, but it does not update the script maps of existing ASP.NET applications.

aspnet_regiis -ir

3. Use Denis Bauer's aspnet version switcher tool.
Following is the link to download this tool.http://www.denisbauer.com/NETTools/ASPNETVersionSwitcher.aspx

error : The alias "LM/W3SVC/1/root/webapplication" already exists. Please choose a different alias.

This is the very common error that any web programmer can face when he/she tries to web share a folder.The solution is to remove the virtual directory entry from the IIS window. But what if the entry does not exist in the IIS window. This situation comes when you delete/move the folder from the c:\inetpub\wwwroot folder before deleting its virtual directory. So the solution is to remove the virtual directory entry from the IIS. Ok.... Now the million dollar question is - How to remove virtual directory entry from the IIS database?

There are 3 ways to do it.

1. Use following command-

iisweb /delete "/"

2. Recreate the folder with the same name in the c:\inetpub\wwwroot and then restart the IIS (use iisreset.exe). You will see the virtual directory with the same name in the IIS window, now remove the virtual directory.

3. Use the following command-

c\inetpub\wwwroot\cscript adsutil.vbs DELETE "W3SVC\1\root\"

Consuming Web Services

There are various ways of consuming web services. Here I am mentioning 3 of them.

1. Using Add Reference dialog box in the VS.Net IDE.
2. Using commandline utility- wsdl.exe/disco.exe
3. Using IE5.5 Behaviour - wed service behaviour(webservice.htc), enables client script to access web service without postback.

Consuming web service without using Add Reference dialog box.

Here I am going to describe how we can use wsdl.exe/disco.exe for consuming wed service.

Path of wsdl.exe/Disco.exe is < root >\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

Using wsdl.exe

steps 1. Create .cs/.vb source file(proxy) using wsdl.exe. Example-


wsdl.exe /l:CS /out: < path of .cs file to be created > < path of the web service like - http://webservicehost/webservice/service.asmx?wsdl >

Or

wsdl.exe /l:CS /out: < path of .cs file to be created > < path of the web service like - http://webservicehost/webservice/service.asmx >

Or

wsdl.exe /l:CS /out: < path of .cs file to be created > < path of WSDL file like – d:\Service.wsdl >

Or

wsdl.exe /l:CS /out: < path of .cs file to be created > < path of DISCOMAP file like – d:\Results.discomap>

step 2.Include the created .cs/.vb source file(proxy) and use it just like other local source files of your project. Or use csc.exe/vbc.exe for creating dll from the source file(proxy). And than add reference of this dll and use it.

Using disco.exe

step 1- Use disco.exe to generate .disco, .wsdl,.discomap files. Example-

disco.exe /out:< directory name > < web service path like- http://webservicehost/webservice/service.asmx >

Or

disco.exe /out:< directory name > < web service path like- http://webservicehost/webservice/service.asmx?disco >

Or

disco.exe /out:< directory name > < web service path like- http://webservicehost/webservice/service.asmx?wsdl >

Note - In this case only .wsdl and .discomap files will be created.

step 2- Use wsdl.exe to generate source file(proxy)/dll from the .wsdl file.

Thursday, June 7, 2007

Disable the context menu

For security reasons,sometimes we want that the user should not be able to see the source code of the web page that can be done choosing view source option from the context menu. So best way is to hide the context menu. For that write a javascript function and pass it to the oncontextmenu attribute of the body tag. Example-

body oncontextmenu="return HideContext();"


javascript function -
function HideContext()
{
alter('Context Menu not availabe.');
return false;
}

Disable the selection of the web page's contents.

But sometimes we want that the user should not be able to select the content of the web page. For that return false to the onselectstart attribute of the body tag. Example-

body onselectstart="return false"

.Net Serialization

There are 2 methods of serialization provided in the .net.
1. Using XMLSerializer class - namespace : System.XML.Serialization
2. Using SoapFormatter/BinaryFormatter class - namespace : System.Runtime.Serialization.Formatter.Soap/Binary

XMLSerializer class is used primarily for web services because its good for cross plateform serialization.But it has its limitations, like class must have parameterless constructor, it cant serialize private class fields and only Read/Write properties can be serialized. A class needs to be declared public. We can choose not to serialise class fields by attributing them with [XMLIgnore] attribute. Example-


[Serializable()]
public class TestSimpleObject
{
int member1;
string member2;
string member3;
double member4;
// A field that is not serialized.
[NonSerialized()]
public string member5;
public TestSimpleObject()
{
member1 = 11;
member2 = "hello";
member3 = "world";
member4 = 3.14159265;
member5 = "hello world!";
}
}
public void Print()
{
Console.WriteLine("member1 = '{0}'", member1);
Console.WriteLine("member2 = '{0}'", member2);
Console.WriteLine("member3 = '{0}'", member3);
Console.WriteLine("member4 = '{0}'", member4);
Console.WriteLine("member5 = '{0}'", member5);
}
}


void XmlSerializationFn()
{
//Creates a new TestSimpleObject object.
TestSimpleObject obj = new TestSimpleObject();
Console.WriteLine("Before serialization the object contains: ");
obj.Print();
//Opens a file and serializes the object into it in binary format.
Stream stream = File.Open("Xmldata.xml", FileMode.Create);
XmlSerializer Xml = new XmlSerializer(typeof(TestSimpleObject));
Xml.Serialize(stream, obj);
stream.Close();
//Empties obj.
obj = null;
//Opens file "Xmldata.xml" and deserializes the object from it.
stream = File.Open("Xmldata.xml", FileMode.Open);
Xml = new XmlSerializer(typeof(TestSimpleObject));
obj = (TestSimpleObject)Xml.Deserialize(stream);
stream.Close();
Console.WriteLine("");
Console.WriteLine("After deserialization the object contains: ");
obj.Print();
}

SoapFormatter/BinaryFormatter class is used primarily for Remoting. BinaryFormatter should be used if serialization/Deserialization performed on .net plateform and SoapFromatter in all other cases. It imposes less restriction than XMLSerializer.Target class does not require to have parameterless constructor and Private/Public fields of the class can be serialized. But it also has a limitation - the constructor of the new object not invoked at the time of deserialization A class needs to be attributed [serializeable]. We can choose not to serialise class fields by attributing them with [NonSerialized] attribute. Example-


void SoapFormatterFn()
{
//Creates a new TestSimpleObject object.
TestSimpleObject obj = new TestSimpleObject();
Console.WriteLine("Before serialization the object contains: ");
obj.Print();
//Opens a file and serializes the object into it in binary format.
Stream stream = File.Open("Soapdata.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(stream, obj);
stream.Close();
//Empties obj.
obj = null;
//Opens file "Soapdata.xml" and deserializes the object from it.
stream = File.Open("Soapdata.xml", FileMode.Open);
formatter = new SoapFormatter();
obj = (TestSimpleObject)formatter.Deserialize(stream);
stream.Close();
Console.WriteLine("");
Console.WriteLine("After deserialization the object contains: ");
obj.Print();
}
void BinaryFormatterFn()
{
//Creates a new TestSimpleObject object.
TestSimpleObject obj = new TestSimpleObject();
Console.WriteLine("Before serialization the object contains: ");
obj.Print();
//Opens a file and serializes the object into it in binary format.
Stream stream = File.Open("Binarydata.xml", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Close();
//Empties obj.
obj = null;
//Opens file "Binarydata.xml" and deserializes the object from it.
stream = File.Open("Binarydata.xml", FileMode.Open);
formatter = new BinaryFormatter();
obj = (TestSimpleObject)formatter.Deserialize(stream);
stream.Close();
Console.WriteLine("");
Console.WriteLine("After deserialization the object contains: ");
obj.Print();
}

Size of empty class

For the 32-bit system, an instance of an empty class occupies total 8 bytes.Because method table pointer takes 8 bytes and sync block takes 4 bytes.

First step towards technical blogging

After much procrestination I have jumped into the world of technical blogging. I hope you people will find my posts helpful.