What is serialization?
Serialization is the process of saving the current state of any object into persistent storage (like file system), so that it can be retrieved later (Deserialize) and re create the same object.
For example, you have an object called student. You assign some values into the properties of this student object and serialze this object into a file. You can keep this file and de serialize any time later to re produce your student to the saved state.
What is serializable class ?
If a class can be serialized by using the builtin serialization features in .NET, that class is called serializable class. Most of the classes provided by .NET Framework is serializable.
Different types of Serialization
There are two broad categories of serialization in .NET
1. XML Serialization
2. Binary Serialization
XML Serialization serializes the object into an xml file. This file is human readable and can be shared with other applications.
Binary serialization is more efficient, but the serialized file is in binary format. It may not make any sense for a human being to open this file and understand what it contains. It is a stream of bytes.
Can I make my own classes serializable ?
Yes, it is very easy to make any class serializable. Simply add an attribute called 'Serializable' just above the class declaration and your class is serializable - means anybody can write few lines of C# code to save the state of the instance of your class into disk and retrieve (deserialize) later.
[Serializable]
public class MyClass
{
public string name;
public string adress;
}
How to serialize classes ?
The following samples demonstrate how to do XML Serialization and Binary Serialization using .NET classes.
We are serializing an 'ArrayList' object into disk and deserializing it again from the disk into another array list.
If you are not familiar with ArrayList - it is a collection class provided by .NET Framework, which can hold a list of any objects. The sample shown below uses an ArrayList which holds a list of strings.
XML Serialization
ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );
XmlSerializer serializer = new XmlSerializer( typeof(ArrayList) );
TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();
In the first step, we are creating an array list and adding two strings into it. next step is to create an instance of XmlSerializer class, which is provided by .NET Framework to help serialize any objects. In the constructor of XmlSerializer class, we have to specify what type of object we want to serialize using this. Since we are going to serialize an ArrayList, we are specifying 'typeof(ArrayList)'.
Next, we are going to do the real thing - saving the state of the ArrayList into an XML file. We will create a TextWriter object and specify the xml file name to which we will save the ArrayList.
The following lines will save the arraylist 'itemsToSerialize' into the file 'MyApplicationData.xml':
TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();
Now, you can check the folder where your application executable is. A file with the name 'MyApplicationData.xml' will be created and you can open the file in any text editor to see the content.
Deserialization
We have serialized an arraylist into an xml file. This means, the state of the arraylist is saved into the xml file. So, we should be able to retrieve the same arraylist from this xml file. The following code will deserialize the arraylist from the xml file.
Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );
IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );
stream.Close();
Just few lines of code ! The above code will read the XML file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized' - means the list of items we originally saved into the XML file will be loaded back to the array list. Now the arraylist 'itemsDeserialized' will contain two strings 'john' 7 'smith' whcih we saved as part of the serialization process.
Binary Serialization
Binary serialization is pretty much same as XML serialization, except that the data stored in a stream of bytes, not in XML format. See the sample code :
ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );
Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Create );
IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );
stream.Close();
The above code sample will serialize the arraylist 'itemsToSerialize' into the file 'MyApplicationData.dat'.
Deserializing the binary data
The objects serialized using binary formatter can be deserialized the same way.
Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );
IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );
stream.Close();
The above sample will read the file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized'.
Where is Serialization used
Serialization has lot of uses in application development. One important purpose is to transmit data between application domains. Webservices and remoting uses serialization/deserialization technique to exchange data.
When you call a webservice and pass parameters, the parameters are serialized into XML data and send to the server. When the webservice return data, the result is serialized into XML and returned to the caller. This means, you can pass only serializable data in web service calls.
In Remoting, you can choose either Binary or SOAP(XML) formatting. Depending on what format you choose, data is serialized using xml or binary format and exchanged between the server and client.
In addition to the above, you can use serialization as a way to store the application data into files. For example, you want to save the last logged in user name, but you don't have a database. You can serialize the user object itself or serialize just the name of the user into disk. When you start the application next time, you can deserialize the user name from the serialized data. Many of the applications use this serialization mechanism to remember the user settings and application data.
Summary
The classes provided by .NET Framework make it very easy to persist the state of any serializable object and restore it to the same state. In the above samples, we have used an ArrayList object. Instead of ArrayList, we can serialize/de serialize any serializable objects including custom classes.
Sample Application
The attached sample application demonstrates both XMl serialization and Binary serialization. The sample project has a list box. You can add/remove items to the listbox. When you press the serialize button, the items in the listbox is copied to an ArrayList object and this array list is serialized.
When you press the de serialize button, the data is de serialzed into an Arraylist object and the listbox is loaded from this array list.
Note that the data serialized will persist even after you close the application. So, you can add few items into the list box in the sample project, serialize them into file and close the application. When you re start the application, you can restore the state of your list box you saved last.
A notable difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not. In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved. Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object.
Asp.Net Articles
Saturday, June 14, 2008
Saturday, February 23, 2008
Creating Custom Configuration Sections in Web.config
Most ASP.NET applications include a number of configuration settings, such as connection strings, mail server settings, system-wide default settings, and so forth. While these settings could be hard-coded in the source code, it's usually a wiser idea to place them in a configuration file, such as Web.config. The reasoning being that if these values need to be modified, editing a configuration file is a lot easier than updating the code, rebuilding, and re-deploying. In fact, Web.config provides an section intended to hold application-wide configuration settings (see Specifying Configuration Settings in Web.config for more details).
While work well for in-house applications, if you are building an application that will be deployed by end users a more professional approach is to use a custom configuration section. , for example, requires that all values be simple scalars provided through elements, like:
While
Click here to view complete article
Working with Databases in ASP.NET 2.0 and Visual Studio 2005
When you install any of the Visual Studio 2005 editions you'll be asked if you also want to install SQL Server 2005 Express edition. If you choose Yes, this will install SQL Server 2005 Express edition on your development box, where you're installing Visual Studio 2005. (SQL Server 2005 Express edition can be installed side-by-side with other versions of SQL Server, including SQL Server 2000 and other editions of SQL Server 2005.)
If you use SQL Server 2000 in your current projects you are probably most comfortable working with the database through Enterprise Manager. While you can still use Enterprise Manager for SQL Server 2000, or SQL Server 2005's Management Studio for your SQL Server 2005 databases, you can also manage these databases through Visual Studio 2005's Data Connections. I mention this because for SQL Server 2005 Express edition there is not a GUI tool like SQL Server 2000's Enterprise Manager or SQL Server 2005's Management Studio; instead, you have to create and manage your SQL Server 2005 Express edition databases through Visual Studio 2005. (Microsoft is working on a SQL Server Management Studio Express Edition for SQL Server 2005 Express; currently the software is released as a community technical preview edition, although an "official" version should be released in due time - keep your eyes on the SQL Server 2005 Express homepage for the latest news.)
Managing SQL Server 2005 Express Edition Databases
If you have any other SQL Server 2005 edition other than Express, you can install the client tools on your machine, which includes Management Studio, the GUI tool for managing SQL Server 2005 databases. If you have this tool installed you can use it to also manage SQL Server 2005 Express edition databases.
To manage a database through Visual Studio 2005, go to the Server Explorer; there you'll find a Data Connections node (shown in the screenshot to the right). You can add new database connections by right-clicking on Data Connections node and choosing Add Connection. This will bring up a dialog box that prompts you for information such as the database server, authentication information, what database to use, and so on. If you installed SQL Server 2005 Express edition on your machine, the database was installed, by default, using the instance name SQLExpress. Therefore, the server name to connect to would be YourMachineName\SQLExpress or .\SQLExpress. In addition to connecting to an existing database, you can also create a new database by right-clicking on the Data Connections node and choosing Create New SQL Server Database.
Once a database has been added to the Data Connections tab, you can add, delete, or modify tables, stored procedures, views, and so on through the appropriate folders. To create a new table or stored procedure, right-click on the appropriate folder and choose Add New X menu option; to modify an existing table, stored procedure, or view, double-click the table, stored procedure, or view. This will bring it up in Visual Studio, where you can modify it as needed. You can also view and modify the data in individual tables by right-clicking on a table name and choosing Show Table Data.
Adding a Database to the App_Data Folder
In addition to adding existing databases through the Data Connections tab, you can also add a site-specific database to the website's App_Data folder. App_Data is a new, reserved folder in ASP.NET 2.0 that is designed to hold data-related content, including SQL database files (.mdf files), Access database files (.mdb files), XML files, and so on. From an ASP.NET website project, you can effortlessly create and add a new SQL Server 2005 Express database to your project by right-clicking on the App_Data folder in the Solution Explorer and choosing Add New Item. Then, from the Add New Item dialog box (shown below), choose to add a new SQL Database.
If you want to follow along with this article, create a SQL Server 2005 Express database in the App_Data folder called Customers.mdf. Add a single table to this database named Customers with the following columns: CustomerID (an auto-increment primary key field), Name, City, State, and ZipCode. Then add some records to this table through VS 2005. (The database file and complete ASP.NET code is available for download at the end of this article...)
You can also add existing Access database files and even SQL Server 2000 database files. (Note: In order to add an existing SQL Server 2000 .mdf file you'll need to ensure that it has first been detached via the Enterprise Manager; to accomplish this, right-click on the database name in Enterprise Manager, select All Tasks, and choose Detach Database. Once you've detached the database and added it to the ASP.NET 2.0 project, you can reattach it through Enterprise Manager.)
Connecting to a Database Using the SqlDataSource Control
Now that we've seen how to create and work with databases through Visual Studio's interface, let's turn our attention to accessing and displaying data from a database in an ASP.NET 2.0 web page. ASP.NET 2.0 includes a number of new datasource controls, whose sole purpose is to provide declarative access to data. There are five built-in datasource controls, all of which can be found in the "Data" portion of the Toolbox in Visual Studio (see the screenshot to the right).
* SqlDataSource - used to retrieve and modify data from a relational database. The "Sql" in the name doesn't mean that this datasource only works with Microsoft SQL Server; rather, it can be used against any relational database: SQL Server, Access, Oracle, and so on. The control is intelligent enough to, internally, use the more efficient SqlClient classes if you are connecting to a SQL Server database.
* AccessDataSource - used to retrieve and modify data from an Access database file. You may be wondering why this control exists if SqlDataSource can work with Access database files. The AccessDataSource control makes it easier to connect to an Access database - you just specify the path to the Access database's .mdb file. With the SqlDataSource you need to use a fully qualified connection string that specifies the data provider.
* ObjectDataSource - used for retrieving and modifying data through a business object. Ideally your ASP.NET application includes a set of classes that constitute the middle tier (rather than having the ASP.NET pages work directly with the database). If you have such an architecture, the ObjectDataSource can be used to query the middle tier.
* XmlDataSource - used for retrieving data from an XML file.
* SiteMapDataSource - used to provide read-only access to the site structure as defined in the site map. This control is used when you want to display a site's structure in a TreeView or Menu control; for more information on ASP.NET 2.0's site navigation features refer to Creating a Site Navigation Hierarchy.
In this article we'll be examining just the SqlDataSource control, and just its basic functionality.
If you use SQL Server 2000 in your current projects you are probably most comfortable working with the database through Enterprise Manager. While you can still use Enterprise Manager for SQL Server 2000, or SQL Server 2005's Management Studio for your SQL Server 2005 databases, you can also manage these databases through Visual Studio 2005's Data Connections. I mention this because for SQL Server 2005 Express edition there is not a GUI tool like SQL Server 2000's Enterprise Manager or SQL Server 2005's Management Studio; instead, you have to create and manage your SQL Server 2005 Express edition databases through Visual Studio 2005. (Microsoft is working on a SQL Server Management Studio Express Edition for SQL Server 2005 Express; currently the software is released as a community technical preview edition, although an "official" version should be released in due time - keep your eyes on the SQL Server 2005 Express homepage for the latest news.)
Managing SQL Server 2005 Express Edition Databases
If you have any other SQL Server 2005 edition other than Express, you can install the client tools on your machine, which includes Management Studio, the GUI tool for managing SQL Server 2005 databases. If you have this tool installed you can use it to also manage SQL Server 2005 Express edition databases.
To manage a database through Visual Studio 2005, go to the Server Explorer; there you'll find a Data Connections node (shown in the screenshot to the right). You can add new database connections by right-clicking on Data Connections node and choosing Add Connection. This will bring up a dialog box that prompts you for information such as the database server, authentication information, what database to use, and so on. If you installed SQL Server 2005 Express edition on your machine, the database was installed, by default, using the instance name SQLExpress. Therefore, the server name to connect to would be YourMachineName\SQLExpress or .\SQLExpress. In addition to connecting to an existing database, you can also create a new database by right-clicking on the Data Connections node and choosing Create New SQL Server Database.
Once a database has been added to the Data Connections tab, you can add, delete, or modify tables, stored procedures, views, and so on through the appropriate folders. To create a new table or stored procedure, right-click on the appropriate folder and choose Add New X menu option; to modify an existing table, stored procedure, or view, double-click the table, stored procedure, or view. This will bring it up in Visual Studio, where you can modify it as needed. You can also view and modify the data in individual tables by right-clicking on a table name and choosing Show Table Data.
Adding a Database to the App_Data Folder
In addition to adding existing databases through the Data Connections tab, you can also add a site-specific database to the website's App_Data folder. App_Data is a new, reserved folder in ASP.NET 2.0 that is designed to hold data-related content, including SQL database files (.mdf files), Access database files (.mdb files), XML files, and so on. From an ASP.NET website project, you can effortlessly create and add a new SQL Server 2005 Express database to your project by right-clicking on the App_Data folder in the Solution Explorer and choosing Add New Item. Then, from the Add New Item dialog box (shown below), choose to add a new SQL Database.
If you want to follow along with this article, create a SQL Server 2005 Express database in the App_Data folder called Customers.mdf. Add a single table to this database named Customers with the following columns: CustomerID (an auto-increment primary key field), Name, City, State, and ZipCode. Then add some records to this table through VS 2005. (The database file and complete ASP.NET code is available for download at the end of this article...)
You can also add existing Access database files and even SQL Server 2000 database files. (Note: In order to add an existing SQL Server 2000 .mdf file you'll need to ensure that it has first been detached via the Enterprise Manager; to accomplish this, right-click on the database name in Enterprise Manager, select All Tasks, and choose Detach Database. Once you've detached the database and added it to the ASP.NET 2.0 project, you can reattach it through Enterprise Manager.)
Connecting to a Database Using the SqlDataSource Control
Now that we've seen how to create and work with databases through Visual Studio's interface, let's turn our attention to accessing and displaying data from a database in an ASP.NET 2.0 web page. ASP.NET 2.0 includes a number of new datasource controls, whose sole purpose is to provide declarative access to data. There are five built-in datasource controls, all of which can be found in the "Data" portion of the Toolbox in Visual Studio (see the screenshot to the right).
* SqlDataSource - used to retrieve and modify data from a relational database. The "Sql" in the name doesn't mean that this datasource only works with Microsoft SQL Server; rather, it can be used against any relational database: SQL Server, Access, Oracle, and so on. The control is intelligent enough to, internally, use the more efficient SqlClient classes if you are connecting to a SQL Server database.
* AccessDataSource - used to retrieve and modify data from an Access database file. You may be wondering why this control exists if SqlDataSource can work with Access database files. The AccessDataSource control makes it easier to connect to an Access database - you just specify the path to the Access database's .mdb file. With the SqlDataSource you need to use a fully qualified connection string that specifies the data provider.
* ObjectDataSource - used for retrieving and modifying data through a business object. Ideally your ASP.NET application includes a set of classes that constitute the middle tier (rather than having the ASP.NET pages work directly with the database). If you have such an architecture, the ObjectDataSource can be used to query the middle tier.
* XmlDataSource - used for retrieving data from an XML file.
* SiteMapDataSource - used to provide read-only access to the site structure as defined in the site map. This control is used when you want to display a site's structure in a TreeView or Menu control; for more information on ASP.NET 2.0's site navigation features refer to Creating a Site Navigation Hierarchy.
In this article we'll be examining just the SqlDataSource control, and just its basic functionality.
Click here to view complete article
Subscribe to:
Posts (Atom)