Serialize and Deserialize Entities

banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

This sample shows how to do standard serialization in Microsoft.NET Framework using Microsoft Dynamics CRM objects.

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\Entities\SerializeAndDeserialize.cs
Server\HowTo\VB\Entities\SerializeAndDeserialize.vb

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

Example

[C#]
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
   /// <summary>
   /// The following sample demonstrates how to serialize a Microsoft Dynamics CRM contact into XML.
   /// and then how to deserialize the XML back into a Microsoft Dynamics CRM contact.  The sample performs
   /// the following steps:
   /// 
   /// - Creates a contact to serialize.
   /// - Retrieves the contact from Microsoft Dynamics CRM.
   /// - Serializes the contact and writes the resulting XML to a file.
   /// - Loads the XML file and deserializes it back into a Microsoft Dynamics CRM contact.
   /// - Updates the contact in Microsoft Dynamics CRM.
   /// 
   /// NOTE: This process does not create Microsoft Dynamics CRM v1.x compatible XML.
   /// </summary>
   public class SerializeAndDeserialize
   {
      static void Main(string[] args)
      {
         // TODO: Change the server URL and organization to match your Microsoft
         // Dynamics CRM Server and Microsoft Dynamics CRM organization.
         SerializeAndDeserialize.Run("https://localhost:5555", "CRM_SDK");
      }

      public static bool Run(string crmServerUrl, string orgName)
      {
         // Set up the CRM Service.
         CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
         
         #region Setup Data Required for this Sample

         bool success = false;

         #endregion

         try
         {
            #region Create a temporary contact for this sample

            // Create a contact entity that will be serialized into XML.
            contact contactCreate = new contact();
            contactCreate.firstname = "Jesper";
            contactCreate.lastname = "Aaberg";
            contactCreate.jobtitle = "Doctor";

            // Create the entity in Microsoft Dynamics CRM and get its ID.
            Guid contactId = service.Create(contactCreate);

            #endregion

            #region Retrieve the contact from CRM

            // Create the column set object that indicates the fields to be retrieved.
            ColumnSet columns = new ColumnSet();
            columns.Attributes = new string [] {"contactid",
                                       "firstname",
                                       "lastname",
                                       "jobtitle"};

            // Retrieve the contact from Microsoft Dynamics CRM
            // using the ID of the record that was just created.
            // The EntityName indicates the EntityType of the object being retrieved.
            contact contact = (contact)service.Retrieve(EntityName.contact.ToString(), 
                                             contactId,
                                             columns);

            #endregion

            #region Serialize the contact into XML and save it

            // Serialize the contact into XML and write it to the hard drive.
            XmlSerializer serializer = new XmlSerializer(typeof(contact));

            // Create a unique file name for the XML.
            string filename = "Contact_" + contact.contactid.Value.ToString("B") + ".xml";

            // Create an instance of StreamWriter to write text to a file.
            // The using statement also closes the StreamWriter.
            using (StreamWriter writer = new StreamWriter(filename)) 
            {
               // Write the XML to disk.
               serializer.Serialize(writer, contact);
            }

            #endregion

            #region Deserialize the CRM contact from XML

            // Declare a Microsoft Dynamics CRM contact.
            contact restoredContact;

            using (StreamReader reader = new StreamReader(filename)) 
            {
               // Deserialize the contact object.
               object tmp = serializer.Deserialize(reader);

               // Cast the object into a Microsoft Dynamics CRM contact.
               restoredContact = tmp as contact;
            }
            
            #endregion

            #region Update contact in CRM

            // Update the contact in Microsoft Dynamics CRM to verify that the deserialization worked.
            restoredContact.jobtitle = "Plumber";
            service.Update(restoredContact);

            #endregion

            #region Delete Data Required for this Sample
            service.Delete(EntityName.contact.ToString(), contactId);
            #endregion

            #region Unit Test: Check if all is ok (test suite)

            // If some key things are OK, return true.
            if (filename != null &&
               filename.Length > "Contact_.XML".Length &&
               restoredContact != null)
            {
               return true;
            }
            else
            {
               return false;
            }

            #endregion
         }
         catch (System.Web.Services.Protocols.SoapException)
         {
            // Add your error handling code here.
         }

         return success;
      }
   }
}

[Visual Basic .NET]
Imports System
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO

Imports CrmSdk
Imports Microsoft.Crm.Sdk.Utility

Namespace Microsoft.Crm.Sdk.HowTo
   ' <summary>
   ' The following sample demonstrates how to serialize a Microsoft Dynamics CRM contact into XML
   ' and then how to deserialize XML back into a Microsoft Dynamics CRM contact. The sample performs
   ' the following steps:
   '
   ' - Creates a contact to serialize.
   ' - Retrieves the contact from Microsoft Dynamics CRM.
   ' - Serializes the contact and writes the resulting XML to a file.
   ' - Loads the XML file and deserializes it back into a Microsoft Dynamics CRM contact.
   ' - Updates the contact in Microsoft Dynamics CRM.
   ' </summary>

   Public Class SerializeAndDeserialize

      Sub Main()

         ' TODO: Change the server URL and organization to match your Microsoft
         ' Dynamics CRM Server and Microsoft Dynamics CRM organization.
         SerializeAndDeserialize.Run("https://localhost:5555", "CRM_SDK")

      End Sub

      Public Shared Function Run(ByVal crmServerUrl As String, ByVal orgName As String) As Boolean
      
         ' Set up the CRM Service.
         Dim service As CrmService =  CrmServiceUtility.GetCrmService(crmServerUrl,orgName)
         
         '---- Setup Data Required for this Sample ------------------------------
         Dim success As Boolean = False
         '-----------------------------------------------------------------------

         Try
            '---- Create a temporary contact for this sample -----------------------

            ' Create a contact entity that will be serialized into XML.
            Dim contactCreate As New contact()
            contactCreate.firstname = "Jesper"
            contactCreate.lastname = "Aaberg"
            contactCreate.jobtitle = "Doctor"

            ' Create the entity in Microsoft Dynamics CRM and get its ID.
            Dim contactId As Guid = service.Create(contactCreate)
            '-----------------------------------------------------------------------

            '---- Retrieve the contact from CRM ------------------------------------
            ' Create the column set object that indicates the fields to be retrieved.
            Dim columns As New ColumnSet()
            columns.Attributes = New String() {"contactid", "firstname", "lastname", "jobtitle"}

            ' Retrieve the contact from Microsoft Dynamics CRM using the ID of the record that was just created.
            ' The EntityName indicates the EntityType of the object being retrieved.
            Dim contact As contact = CType(service.Retrieve(EntityName.contact.ToString(), contactId, columns), contact)
            '-----------------------------------------------------------------------

            '---- Serialize the contact into XML and save it -----------------------
            ' Serialize the Contact into XML and write it to the hard drive
            Dim serializer As New XmlSerializer(GetType(contact))

            ' Create a unique file name for the XML.
            Dim filename As String = "Contact_" + contact.contactid.Value.ToString("B") + ".xml"

            ' Create an instance of StreamWriter to write text to a file.
            ' The using statement also closes the StreamWriter.
            Dim writer As New StreamWriter(filename)
            Try
               ' Write the XML to disk.
               serializer.Serialize(writer, contact)
            Finally
               writer.Close()
            End Try
            '-----------------------------------------------------------------------

            '---- Deserialize the CRM contact from XML -----------------------------
            ' Declare a CRM contact
            Dim restoredContact As contact

            Dim reader As New StreamReader(filename)
            Try
               ' Deserialize the contact object.
               Dim tmp As Object = serializer.Deserialize(reader)

               ' Cast the object into a Microsoft Dynamics CRM contact.
               restoredContact = CType(tmp, contact)
            Finally
               reader.Close()
            End Try
            '-----------------------------------------------------------------------

            '---- Update contact in CRM --------------------------------------------
            ' Update the contact in Microsoft Dynamics CRM to prove that the deserialization worked.
            restoredContact.jobtitle = "Plumber"
            service.Update(restoredContact)
            '-----------------------------------------------------------------------

            '---- Delete Data Required for this Sample -----------------------------
            service.Delete(EntityName.contact.ToString(), contactId)
            '-----------------------------------------------------------------------

            '---- Unit Test: Check if all is ok (test suite) ----------------------
            ' If some key things are OK, return true.
            If Not (filename Is Nothing) AndAlso filename.Length > "Contact_.XML".Length AndAlso Not (restoredContact Is Nothing) Then
               Return True
            Else
               Return False
            End If
            '-----------------------------------------------------------------------
         Catch e As System.Web.Services.Protocols.SoapException
         End Try
         ' Add your error handling code here.

         Return success
      End Function 'Run
   End Class 'SerializeAndDeserialize
End Namespace 'Microsoft.Crm.Sdk.HowTo

© 2010 Microsoft Corporation. All rights reserved.