Skip to content

Instantly share code, notes, and snippets.

@BetimBeja
Created January 9, 2019 07:55
Show Gist options
  • Save BetimBeja/832924babb4dc8355b730c43cb9ec61a to your computer and use it in GitHub Desktop.
Save BetimBeja/832924babb4dc8355b730c43cb9ec61a to your computer and use it in GitHub Desktop.
Simple serialization and deserialization of an XRM Entity with XrmEntitySerializer
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel;
using XrmEntitySerializer;
namespace Test_XrmEntitySerializer
{
class Program
{
public static void Main(string[] args)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (CrmServiceClient _client = new
CrmServiceClient(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString))
{
IOrganizationService orgService = _client.OrganizationServiceProxy;
QueryByAttribute query = new QueryByAttribute("account");
query.Attributes.Add("statuscode");
query.Values.Add(1);
query.TopCount = 1;
query.ColumnSet = new ColumnSet(true);
Entity account = orgService.RetrieveMultiple(query).Entities.FirstOrDefault();
EntitySerializer serializer = new EntitySerializer();
using (JsonTextWriter writer = new JsonTextWriter(new StreamWriter("account.json")))
{
serializer.Serialize(writer, account);
}
Entity deserializedAccount = default(Entity);
using (JsonTextReader reader = new JsonTextReader(new StreamReader("account.json")))
{
deserializedAccount = serializer.Deserialize<Entity>(reader);
}
Console.WriteLine("Account Name: " + deserializedAccount.GetAttributeValue<string>("name"));
Console.ReadKey();
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
string message = ex.Message;
throw;
}
}
}
}
@BetimBeja
Copy link
Author

BetimBeja commented Jan 9, 2019

Sample project created with D365DeveloperExtensions.
XrmEntitySerializer can be easily installed from NuGet with the following command: Install-Package XrmEntitySerializer.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment