asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Creating Collections for Data Binding and Serialization
By Thiru Thangarathinam
Rating: 4.1 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    Designing an n-tier application means carefully evaluating the different options and paying careful attention to the type of objects being returned from the business logic layer. The client for the business logic layer could be either ASP.NET Web forms or ASP.NET Web services. An efficient approach for creating this type of business logic is to return strongly typed collection objects from the business logic layer.

    A collection is a way of grouping a set of related items. Collections can be used to keep track of many things, such as all the controls on a form (the Controls collection for example), and users can create their own collections to organize and manipulate objects. Collections are a good way to keep track of objects that an application might need to dynamically create and destroy.

    A strongly typed collection is a collection that contains a known type. An application can inherit from the System.Collections.CollectionBase or System.Collections.ReadOnlyCollectionBase to implement a writable or read-only strongly typed collection. Similarly to an array, a strongly typed collection can be indexed like an array of a type, and a strongly typed collection implements IList and IEnumerable. Unlike an array, however, a strongly typed collection has an Add method that allows for adding objects and manages growing the collection dynamically. The main advantage of a strongly typed collection is that it supports dynamic resizing automatically.

    Since the business logic layer always returns strongly typed objects, it can be consumed in a consistent manner by both clients. For example, the business logic layer can return the data in the form of a collection object that can be directly used by the ASP.NET Web forms for data binding. The same object can be used by the ASP.NET Web services as well. In the ASP.NET Web services layer, we can take these objects and use the XML serialization to convert them into a XML format that we need. By returning strongly typed collection objects from the business logic layer, we can provide a consistent interface into the business logic layer that is not only efficient in terms of memory overhead but also reduces compilation and runtime errors.

    Before taking a look at the implementation, let us outline the overall architecture of an N-tier application and see how our approach fits into the big picture.

  • download source code

    Architecture of An N-Tier Application That Uses XML Serialization and Object Binding

    The following architecture diagram shows how collection objects can be used in an n-tier application.

    The above architecture consists of the following important components:

    • ASP.NET Web GUI - This layer is responsible for rendering the user interface of the Web application. As with any other ASP.NET application, this application uses ASP.NET server controls for displaying the data. The server side controls are directly bound to the strongly typed collection that is returned from the business services layer.
    • ASP.NET Web Service Layer - This layer wraps around the business logic layer and exposes the functionality of the application using industry standard protocols such as HTTP, XML, and SOAP. This layer also receives the strongly typed collection objects returned from the business logic layer and converts them into an XML document using the .NET XML serialization capabilities.
    • Business Services Layer - The business logic layer invokes the methods of the data access layer and converts the DataSet object into a strongly typed collection object, which is then passed on to the consumers of the business logic layer.
    • ADO.NET Data Services Layer - As the name suggests, this layer is responsible for executing SQL statements and stored procedures against the SQL Server database.
    • SQL Server Database - The SQL Server database contains all the stored procedures invoked by the data access layer.

    Implementation

    Now that we have had a look at the design architecture and understand the role of the collection objects in providing a consistent interface to the consumers of the business logic layer of the application, let us consider an example application that implements the above architecture. For the purposes of this article, we will create an end-to-end implementation that uses the Employees table of the Northwind database. We will display employees' details using the ASP.NET Web application and expose the employees' details using ASP.NET Web services layer. For this example, we will also implement the business logic layer and data access layer. We will start by looking at the data access layer.

    Data Access Layer Implementation

    The data access layer basically contains the methods that are used to execute SQL statements against the SQL Server database. For the purposes of this article, create a new Visual C# class library project named DataAccess. After the project is created, rename the default class from class1 to EmployeeDB. As the name suggests, EmployeeDB class performs operations against the Employees table in the Northwind database. In this example, we will just consider a Get method named GetEmployees that returns details of all the employees from the Northwind database. We will start by importing all the required namespaces.

    using System;

    using System.Configuration;

    using System.Data;

    using System.Data.SqlClient;

     

    namespace DataAccess

    {     

    public class EmployeeDB

    {

           public EmployeeDB()

           {

           }

           public DataSet GetEmployees()

           {

                  string connString =       

                  ConfigurationSettings.AppSettings["connectionString"];

                  using (SqlConnection conn = new SqlConnection(connString))

                  {

                         string sql = "Select EmployeeID, LastName,

                               FirstName, Title from Employees";

                         SqlDataAdapter adapter = new SqlDataAdapter(sql,conn);

                         DataSet employeesDataSet = new DataSet();

                         adapter.Fill(employeesDataSet);

                         return employeesDataSet;

                  }                   

           }

    }

    }

    In the GetEmployees method, we start by retrieving the connection string from the web.config file. After that we create an instance of the SqlConnection object and supply the connection string as an argument. Then we create an instance of the SqlDataAdapter object, passing in the SQL statement and the SqlConnection object as arguments to its constructor. Finally, we execute the SQL statement and fill the DataSet object with the results of the execution of the SQL query and then return the DataSet to the calling method.

    Business Logic Layer Implementation

    As mentioned before, the business logic layer contains all the business logic required for the application. In this example, we will create a new Visual C# class library project named BusinessLogic and rename the default class from class1 to EmployeeBiz. The EmployeeBiz contains a method named GetEmployees that invokes the EmployeeDB class of the data access layer for all of its functionalities. The code required for implementing the EmployeeBiz class is shown below.

    using System;

    using System.Data;

    using DataAccess;

    using ObjectDeclarations;

     

    namespace BusinessLogic

    {

    public class EmployeeBiz

    {

           public EmployeeBiz()

           {

           }

     

           public Employees GetEmployees()

           {

                  Employees empCol = new Employees();

                  EmployeeDB emp = new EmployeeDB();

                  DataSet employeesDataSet = emp.GetEmployees();

                  //Get reference to the first DataTable

                  DataTable employeesTable = employeesDataSet.Tables[0];

                  foreach(DataRow row in employeesTable.Rows)

                  {

                         Employee employee = new Employee();

                         employee.EmployeeID=Convert.ToInt32(row["EmployeeID"]);

                         employee.LastName = Convert.ToString(row["LastName"]);

                         employee.FirstName = Convert.ToString(row["FirstName"]);

                         employee.Title = Convert.ToString(row["Title"]);

                         empCol.Add(employee);

                  }

                  return empCol;

           }

    }

    }

    In the GetEmployees method, we invoke the data access layer method and get the employee details in the form of a DataSet object. After we get the DataSet object, we then loop through all the rows. Basically the Employees collection is a strongly typed collection object that acts as the placeholder for the Employee objects.

    Object Implementation

    In this section, we will consider the implementation of the Employee class as well as the Employees class that holds strongly typed Employee objects. We will start our discussion by looking at the implementation of the Employee class.

    Employee Class Implementation
    First let's create a new Visual C# class library project named ObjectDeclarations and rename the default class from class1 to Employee. As the name suggests, the Employee class holds details of an Employee and exposes the attributes of an employee by means of public properties. Here is the code of the Employee class.

    using System;

    namespace ObjectDeclarations

    {

           [Serializable]

           public class Employee

           {

                  private int _employeeID;

                  private string _lastName = "";

                  private string _firstName = "";

                  private string _title = "";

                  public Employee()

                  {                   

                  }

     

                  public int EmployeeID

                  {

                         get

                         {

                               return _employeeID;

                         }

                         set

                         {

                               _employeeID = value;

                         }

                  }

     

                  public string LastName

                  {

                         get

                         {

                               return _lastName;

                         }

                         set

                         {

                               _lastName = value;

                         }

                  }

     

                  public string FirstName

                  {

                         get

                         {

                               return _firstName;

                         }

                         set

                         {

                               _firstName = value;

                         }

                  }

     

                  public string Title

                  {

                         get

                         {

                               return _title;

                         }

                         set

                         {

                               _title = value;

                         }

                  }

           }

    }

    In the above lines of code, we decorate our class with the keyword Serializable to allow our class to be serializable. This attribute makes it possible to convert the UserObject into a linear sequence of bytes for either storage or transmission to another location. Apart from the constructor, we have also declared a number of public get/set properties.

    Employees Class Implementation
    Now that we have had a look at the Employee class, let us consider the implementation of the Employees class that acts as the placeholder for storing a collection of Employee objects. Here is the code of the Employees class.

    using System;

    using System.Collections;

    using System.IO;

    using System.Xml;

    using System.Xml.Serialization;

     

    namespace ObjectDeclarations

    {     

           [Serializable]

           [XmlRoot("Employees")]

           public class Employees:IEnumerator, ICollection

           {            

                  //Private member variable that holds the underlying Collection.

                  private ArrayList _employeesArray;

                  // Private member variable that holds the index of the current              //InformationCollection.

                  private int _index = -1;

     

                  public Employees()

                  {

                         _employeesArray = new ArrayList();

                  }

                 

                  public Employees(ArrayList theArrayList)

                  {

                         _employeesArray = theArrayList;

                  }

                 

                  public int Count

                  {

                         get

                         {

                               return _employeesArray.Count;

                         }

                  }

                 

                  public void Add(Employee obj)

                  {

                         _employeesArray.Add(obj);

                  }

                 

                  public void Remove(Employee obj)

                  {

                         _employeesArray.Remove(obj);

                  }

     

                  public Employee this[int indexer]

                  {

                         get

                         {

                               //Check if the indexer falls in allowable range.

                               if ((indexer >= 0) &&

                                      (indexer < _employeesArray.Count))

                                      return (Employee)_employeesArray[indexer];

                               else

                                      throw new

                                      System.IndexOutOfRangeException("Index must

                                      be between 0 and " +

                                      _employeesArray.Count.ToString() + ".");                            

                         }

                  }     

                 

                  public IEnumerator GetEnumerator()

                  {

                         return (IEnumerator) new Employees(_employeesArray);

                  }

                 

                  public object Current

                  {

                         get

                         {

                               return _employeesArray[_index];

                         }

                  }

                 

                  public bool MoveNext()

                  {

                         _index++;

                         return _index < _employeesArray.Count;

                  }

                 

                  public void Reset()

                  {

                         _index = -1;

                  }     

                 

                  public ArrayList GetArrayList()

                  {

                         return _employeesArray;

                  }

                 

                  public object SyncRoot

                  {

                         get{return this;}

                  }

                 

                  public bool IsSynchronized

                  {

                         get{return false;}

                  }            

                 

                  public void CopyTo(Array a, int index)

                  {

                         _employeesArray.CopyTo(a,index);               

                  }

           }

    }

    We start by deriving our collection class from IEnumerator and ICollection classes. After that we implement various properties and methods such as Count, IsSynchronized, SyncRoot, Current, MoveNext and Reset that are defined in the ICollection and IEnumerator interfaces.

    Implementation of an ASP.NET Application >>

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES