Click here to Skip to main content
12,405,088 members (67,268 online)
Click here to Skip to main content
Add your own
alternative version

Stats

214.3K views
2.2K downloads
80 bookmarked
Posted

C# - Data Transfer Object

, 18 Nov 2004
Rate this:
Please Sign up or sign in to vote.
This article demonstrates how to use the serializable Data Transfer Object to transfer data throughout applications.

Introduction

The Data Transfer Object "DTO", is a simple serializable object used to transfer data across multiple layers of an application. The fields contained in the DTO are usually primitive types such as strings, boolean, etc. Other DTOs may be contained or aggregated in the DTO. For example, you may have a collection of BookDTOs contained in a LibraryDTO. I have created a framework used by multiple applications that utilizes DTOs to transfer data across tiers. The framework also relies on other OO patterns such as the Factory, Facade, etc. One of the great things about the DTO compared to a DataSet is that the DTO does not have to directly match a data table or view. The DTO can aggregate fields from another DTO.

Using the code

  1. Create a project that will be common for your application.
  2. Generate the abstract base class DTO.
  3. Generate the Serializer Helper class.
  4. Create your derived DTOs that inherit from the DTO base class.
  5. Create the Console Application to test your DTO and serialization.

*** Note: All of the code is available via the downloadable zip file.***

Abstract Base Class for all Data Transfer Objects

This is the base class for all Data Transfer Objects.

using System;

namespace DEMO.Common
{
    /// 
    /// This is the base class for all DataTransferObjects.
    /// 
    public abstract class DTO
    {
        public DTO()
        {
        }
    }
}

Data Transfer Object Serializer Helper Class

This is the helper class for a DTO. It has public methods to serialize and de-serialize a DTO.

using System;
using System.Xml.Serialization;
using System.IO;

namespace DEMO.Common
{
    /// 
    /// Summary description for DTOSerializerHelper.
    /// 
    public class DTOSerializerHelper
    {
        public DTOSerializerHelper()
        {
        }

        /// 
        /// Creates xml string from given dto.
        /// 
        /// DTO
        /// XML
        public static string SerializeDTO(DTO dto)
        {
            try
            {
                XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
                StringWriter sWriter = new StringWriter();
                // Serialize the dto to xml.
                xmlSer.Serialize(sWriter, dto);
                // Return the string of xml.
                return sWriter.ToString();
            }
            catch(Exception ex)
            {
                // Propogate the exception.
                throw ex;
            }
        }

        /// 
        /// Deserializes the xml into a specified data transfer object.
        /// 
        /// string of xml
        /// type of dto
        /// DTO
        public static DTO DeserializeXml(string xml, DTO dto)
        {
            try
            {
                XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
                // Read the XML.
                StringReader sReader = new StringReader(xml);
                // Cast the deserialized xml to the type of dto.
                DTO retDTO = (DTO)xmlSer.Deserialize(sReader);
                // Return the data transfer object.
                return retDTO;
            }
            catch(Exception ex)
            {
                // Propogate the exception.
                throw ex;
            }            
        }

    }
}

Derived Data Transfer Object Example

The DemoDTO is a derived class that inherits from the DTO base class. This class has some simple fields defined such as demoId, demoName, and demoProgrammer.

using System;
using System.Xml.Serialization;
using DEMO.Common;

namespace DEMO.DemoDataTransferObjects
{
    /// 
    /// Summary description for the DemoDTO.
    /// 
    public class DemoDTO : DTO
    {
        // Variables encapsulated by class (private).
        private string demoId = "";
        private string demoName = "";
        private string demoProgrammer = "";

        public DemoDTO()
        {
        }

        ///Public access to the DemoId field.
        ///String
        [XmlElement(IsNullable=true)]
        public string DemoId
        {
            get
            {
                return this.demoId;
            }
            set
            {
                this.demoId = value;
            }
        }

        ///Public access to the DemoId field.
        ///String
        [XmlElement(IsNullable=true)]
        public string DemoName
        {
            get
            {
                return this.demoName;
            }
            set
            {
                this.demoName = value;
            }
        }

        ///Public access to the DemoId field.
        ///String
        [XmlElement(IsNullable=true)]
        public string DemoProgrammer
        {
            get
            {
                return this.demoProgrammer;
            }
            set
            {
                this.demoProgrammer = value;
            }
        }

    }
}

Console App showing DTO example

The Console Application demonstrates how easy it is to create a DTO, serialize a DTO, and de-serialize a DTO.

using System;
using DEMO.Common;
using DEMO.DemoDataTransferObjects;

namespace DemoConsoleApplication
{
    /// 
    /// Summary description for DemoClass.
    /// 
    public class DemoClass
    {
        public DemoClass()
        {
        }

        public void StartDemo()
        {
            this.ProcessDemo();
        }

        private void ProcessDemo()
        {
            DemoDTO dto = this.CreateDemoDto();
            
            // Serialize the dto to xml.
            string strXml = DTOSerializerHelper.SerializeDTO(dto);
            
            // Write the serialized dto as xml.
            Console.WriteLine("Serialized DTO");
            Console.WriteLine("=======================");
            Console.WriteLine("\r");
            Console.WriteLine(strXml);
            Console.WriteLine("\r");

            // Deserialize the xml to the data transfer object.
            DemoDTO desDto = 
              (DemoDTO) DTOSerializerHelper.DeserializeXml(strXml, 
              new DemoDTO());
            
            // Write the deserialized dto values.
            Console.WriteLine("Deseralized DTO");
            Console.WriteLine("=======================");
            Console.WriteLine("\r");
            Console.WriteLine("DemoId         : " + desDto.DemoId);
            Console.WriteLine("Demo Name      : " + desDto.DemoName);
            Console.WriteLine("Demo Programmer: " + desDto.DemoProgrammer);
            Console.WriteLine("\r");
        }

        private DemoDTO CreateDemoDto()
        {
            DemoDTO dto = new DemoDTO();
            
            dto.DemoId            = "1";
            dto.DemoName        = "Data Transfer Object Demonstration Program";
            dto.DemoProgrammer    = "Kenny Young";

            return dto;
        }
    }
}
using System;
using DEMO.Common;
using DEMO.DemoDataTransferObjects;

namespace DemoConsoleApplication
{
    /// 
    /// Summary description for MainClass.
    /// 
    class MainClass
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main(string[] args)
        {
            DemoClass dc = new DemoClass();
            dc.StartDemo();

        }
    }
}

Output

Conclusion

This article demonstrated a simple way to use Data Transfer Objects. These objects are a small part of a common framework developed for multiple applications. The framework has multiple layers, but one common object used throughout is the DTO. There are objects in the framework that convert a DataReader into a Data Access Object. Once time permits, I will be posting more documents on Enterprise Architecture, and go into more detail about the framework.

References

  1. Patterns of Enterprise Application Architecture, Martin Fowler 2003.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Kenny Young
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
MaxKot27-May-15 1:24
memberMaxKot27-May-15 1:24 
QuestionXml Serialization Pin
Member 105004462-Jan-14 23:53
memberMember 105004462-Jan-14 23:53 
GeneralMy vote of 4 Pin
_learner21-May-13 17:19
member_learner21-May-13 17:19 
SuggestionEntitiesToDTOs Pin
ffernandez2323-Jan-13 15:58
memberffernandez2323-Jan-13 15:58 
GeneralMy vote of 1 Pin
B.Farivar8-Oct-12 19:38
memberB.Farivar8-Oct-12 19:38 
GeneralMy vote of 5 Pin
vishakhakhadse9-Aug-12 3:18
membervishakhakhadse9-Aug-12 3:18 
GeneralMy vote of 5 Pin
manoj kumar choubey9-Feb-12 21:13
membermanoj kumar choubey9-Feb-12 21:13 
GeneralMy vote of 4 Pin
rajeevtechnical1-Nov-11 6:51
memberrajeevtechnical1-Nov-11 6:51 
GeneralMy vote of 4 Pin
rvegah4-Jul-11 8:49
memberrvegah4-Jul-11 8:49 
GeneralMy vote of 2 Pin
cocowalla22-Apr-11 0:51
membercocowalla22-Apr-11 0:51 
GeneralRe: My vote of 2 Pin
rajeevtechnical1-Nov-11 6:48
memberrajeevtechnical1-Nov-11 6:48 
GeneralMy vote of 3 Pin
kj-dev13-Oct-10 1:46
memberkj-dev13-Oct-10 1:46 
GeneralPerformance Issue with XML Serialization Pin
kumar Umesh16-Sep-09 20:46
memberkumar Umesh16-Sep-09 20:46 
Questionhow to use transfer object in a servlet program Pin
doddlepeck11-May-08 20:08
memberdoddlepeck11-May-08 20:08 
Generalarray list of DTO Pin
kumar Umesh8-May-06 21:30
memberkumar Umesh8-May-06 21:30 
Generalnull values in the result object's attributes Pin
Pangestu Widodo11-Jan-06 22:05
memberPangestu Widodo11-Jan-06 22:05 
GeneralRe: null values in the result object's attributes Pin
Kenny Young12-Jan-06 2:38
memberKenny Young12-Jan-06 2:38 
GeneralDTO's and Martin Fowlers Book. Pin
MNutty29-Nov-04 1:21
memberMNutty29-Nov-04 1:21 
GeneralRe: DTO's and Martin Fowlers Book. Pin
Kenny Young29-Nov-04 2:51
memberKenny Young29-Nov-04 2:51 
GeneralRe: DTO's and Martin Fowlers Book. Pin
MNutty29-Nov-04 4:39
memberMNutty29-Nov-04 4:39 
GeneralRe: DTO's and Martin Fowlers Book. Pin
Marc Leger30-Nov-05 23:14
memberMarc Leger30-Nov-05 23:14 
GeneralRe: DTO's and Martin Fowlers Book. Pin
MNutty12-Jan-06 2:04
memberMNutty12-Jan-06 2:04 
GeneralRe: DTO's and Martin Fowlers Book. Pin
Roger J11-Jan-06 22:57
memberRoger J11-Jan-06 22:57 
GeneralRe: DTO's and Martin Fowlers Book. Pin
MNutty12-Jan-06 2:03
memberMNutty12-Jan-06 2:03 
GeneralRe: DTO's and Martin Fowlers Book. Pin
brian259-Aug-10 3:36
memberbrian259-Aug-10 3:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160721.1 | Last Updated 18 Nov 2004
Article Copyright 2004 by Kenny Young
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid