Created
January 9, 2019 07:55
-
-
Save BetimBeja/832924babb4dc8355b730c43cb9ec61a to your computer and use it in GitHub Desktop.
Simple serialization and deserialization of an XRM Entity with XrmEntitySerializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample project created with
D365DeveloperExtensions
.XrmEntitySerializer can be easily installed from NuGet with the following command: Install-Package XrmEntitySerializer.9