Data transfer object pattern

data transfer object c#
dto acronym
java dto best practices
dto vs dao
dto wrapper
android dto example
wrapper vs dto
advantages of using dto

i'm sorry i'm newbie to enterprise application as well as the design pattern. might be this question occcur lack of knowledge about design pattern. i found that its better to use DTO to transfer data.

my business entity class as below:

public class Patient
{    
    public string ID { get; set; }
    public string FullName { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
}

so in my application user only give ID and HospitalID. so it calls for another web service and get person information

 public class PersonDTO
 {
     public string NIC { get; set; }
     public string FullName { get; set; }
     public string FirstName { get; set; }
     public string BirthPlace { get; set; }
     public string BirthCertificateID { get; set; }
 }

so based on these information im going to Patient object. (Using DTO pattern)

so i thought of write new class to convert this as follows.

public class PatientDO
{
    public static Patient ConvertToEntity(
        PatientRegistrationDTO pregDTO,
        PersonDTO person
    )
    {
        Patient p = new Patient();
        p.NIC = pregDTO.NIC;
        p.FullName = person.FullName;
        p.FirstName = person.FirstName;
        return p;
    }
}

but lately i read few articles and they used Serializer Helper class as well as the XmlSerializer i can't understand why they used somthing like that.

for the DTO pattern is that need to use XmlSerializer and why it is used?

Design Pattern - Transfer Object Pattern, The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. DTO (Data Transfer objects) is a data container for moving data between layers. They are also termed as transfer objects. DTO is only used to pass data and does not contain any business logic. They only have simple setters and getters. For example, below is an Entity class or a business class. You can see that it has business logic in the setters.

There is a nice, yet simple demo in CodeProject. It is worthy going through it. Newbies can get a basic idea of designing DTOs.

http://www.codeproject.com/Articles/8824/C-Data-Transfer-Object

Here's a summary of the content:

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

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

This is a derived class from DTO:

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

namespace DEMO.DemoDataTransferObjects
{
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;
        }
    }

}

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

}

Now begin Serialization / Deserialization:

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

namespace DemoConsoleApplication
{
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;
    }
}

Finally this code is executed in the main application

static void Main(string[] args)
{
    DemoClass dc = new DemoClass();
    dc.StartDemo();
}

P of EAA: Data Transfer Object, Many people in the Sun community use the term "Value Object" for this pattern. I use it to mean something else. See the discussion on page 487. Although the  A data transfer object (DTO) is an object that carries data between processes. The motivation for its use is that communication between processes is usually done resorting to remote interfaces (e.g., web services), where each call is an expensive operation.

An XmlSerializer or JsonSerializer can be used for serializing (loading) XML or Json data from a source (webservice). Or explaining the name DTO: you serialize (transfer) data from a source (webservice) to a (general DTO) object. So DTOs are general purpose objects. Sometimes its clever to make a wide as possible DTO object and fill that completely so you can use from that object whatever you like and copy that to your "own" program objects.

Example: I developped a program for showing transport navigation data. I serialize the whole xml or json messsage in a DTO object. In this DTO object is more information then I will need in my program and it can be in a different form, so I will use only whats needed. DTO objects makes it more easy to extract data from sources (webservices).

I dont want to use AutoMapper because of the name "Auto". I want to know what I am doing and think where my data is going to.

Data transfer object, The DTO pattern is the Data Transfer Object pattern. It is a very old pattern which i believe somewhat originated from the world of J2EE (now  Explanation The Data Transfer Object pattern is a design pattern in which a data transfer object is used Transfer Object is a simple POJO class having getter/setter methods and is serializable Server Side business class normally fetches data from the database and fills Client can create

Dissecting the DTO pattern - Colin But, DTO is a pattern and it is implementation (POJO/POCO) independent. DTO says, since each call to any remote interface is expensive, response to each call  The Transfer Object pattern addresses the need of getting data from BusinessObjects across tiers. This certainly is one aspect of design considerations for entity beans. The Composite Entity pattern discusses issues involved in designing coarse-grained entity beans.

What is the point of using DTO (Data Transfer Objects)?, There is a popular design pattern, especially in Java, called the data transfer object (DTO). The idea is to have a simple class to transfer data between tiers in a  Data Transfer Object. An object that carries data between processes in order to reduce the number of method calls. For a full description see P of EAA page 401 When you're working with a remote interface, such as Remote Facade (388), each call to it is expensive. As a result you need to reduce the number of calls,

Data Transfer Object, Transfer objects exchange data between J2EE clients and Enterprise Java Beans. 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.

Comments
  • Note that you do need to review performance considerations. You could use AutoMapper. not Should.
  • imo, most performance issues I've seen from AutoMapper have come from poorly defined mappings ( written by me! ). Biggest prob I've had is when AutoMapper crawls an nHibernate object graph and makes loads of DB calls.
  • That is why i've upvoted you answer. However, as he said he is new, I just want to point out this is a good approach but no strict requirement.
  • this could be a very good read about automapper devtrends.co.uk/blog/…
  • Though I have'nt used this personally yet this autoprojecting using Linq queries may give you an idea. lostechies.com/jimmybogard/2011/02/09/…