CRM Plugins - Json Kullanımı

Working with JSON objects in Dynamics CRM Plugins


CRM üzerinde çalışan pluginlerimizde json formatında veri döndürdüğümüzü düşünelim .

Genellikle bu tür işlemler için .NET Frameworkun bize sunduğu Newtonsoft.json kütüphanesini kullanırız.

Eğer pluginimizi Sandbox a register edersek pluginde kullandığımız javascriptSerializer metodu aşağıdaki hatayı verecektir.

Unhandled Exception: Microsoft.Crm.CrmException: Unexpected exception from plug-in (Execute): XXXXXXXX.CRM2015.WorkflowActivities.XXXXXXXX: System.MethodAccessException: Attempt by security transparent method ‘XXXXXXXX.CRM2015.WorkflowActivities.XXXXXXXX.SetLocationInfo(Microsoft.Xrm.Sdk.IOrganizationService, Microsoft.Xrm.Sdk.ITracingService, System.String)’ to access security critical method ‘System.Web.Script.Serialization.JavaScriptSerializer..ctor()’ failed.
Assembly ‘XXXXXXXX.CRM2015.WorkflowActivities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3f9fc15734725b08′ is partially trusted, which causes the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself.  In order to access security critical code, this assembly must be fully trusted.
Assembly ‘System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ is a conditionally APTCA assembly which is not enabled in the current AppDomain.  To enable this assembly to be used by partial trust or security transparent code, please add assembly name ‘System.Web.Extensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100B5FC90E7027F67871E773A8FDE8938C81DD402BA65B9201D60593E96C492651E889CC13F1415EBB53FAC1131AE0BD333C5EE6021672D9718EA31A8AEBD0DA0072F25D87DBA6FC90FFD598ED4DA35E44C398C454307E8E33B8426143DAEC9F596836F97C8F74750E5975C64E2189F45DEF46B2A2B1247ADC3652BF5C308055DA9′ to the the PartialTrustVisibleAssemblies list when creating the AppDomain.
at Microsoft.Crm.Sandbox.SandboxCodeUnit.Execute(IExecutionContext context)

at Microsoft.Crm.Workflow.Services.ProxyCustomActivity.Execute(CodeActivityContext executionContext)


 Hatanın sebebi CRM contextinde 3.party dllere erişilememesidir.

Bu hatayı ILMerge kullanarak çözebiliriz. ( .NET dllerini tek bir dll olarak birleştiren araç)

Alternatif bir çözüm olarak ise ; 3.party çözüm kullanmayarak DataContractJsonSerializer kullanmaktır.

Biz örneğimizde DataContractJsonSerializer yöntemini kullanacağız.


CRM Plugininde DataContractJsonSerializer Kullanımı

Servisimizden gelen verileri tutacağımız bir DataContract classı tasarlayalım.


   [DataContract]
    public class JsonSalesServiceTest
    {
        //datamember name value indicates name of json field to which data will be serialized/from which data will be deserialize

        [DataMember(Name = "Status")]
        public string Status { get; set; }

        [DataMember(Name = "Source")]
        public string Source { get; set; }

        [DataMember(Name = "BusinessUnit")]
        public Reference1 BusinessUnit { get; set; }

        [DataMember(Name = "Customer")]
        public Reference1 Customer { get; set; }

        [DataMember(Name = "CustomerAddress")]
        public string CustomerAddress { get; set; }

        public JsonSalesServiceTest() { }
    }

Json dizimizdeki verileri classımıza atayalım.(Deserialize)

Deseriliaze

 #region Deserialize

                using (MemoryStream DeSerializememoryStream = new MemoryStream())
                {
                    //Json String that we get from web api 
                    string ResponseString = "{\"Status\":\"" + "Create" +
                                          "\",\"Source\":\"" + "Dynamics CRM London" + 
                                          "\",\"BusinessUnit\":\"" + "{\"Name\":null,\"Id\":\"01f4f959-ceea-e511-80ed-005056b503b5\"}" + 
                                          "\",\"Customer\":\"" + "{\"Name\":null,\"Id\":\"d43f26ff-8e2c-e611-80ff-005056b503b5\"}" +
                                          "\",\"CustomerAddress\":\"" + "400005" + "\"}";

                    //initialize DataContractJsonSerializer object and pass Student class type to it
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonSalesServiceTest));

                    //user stream writer to write JSON string data to memory stream
                    StreamWriter writer = new StreamWriter(DeSerializememoryStream);
                    writer.Write(ResponseString);
                    writer.Flush();

                    DeSerializememoryStream.Position = 0;
                    //get the Desrialized data in object of type Student
                    JsonSalesServiceTest SerializedObject = (JsonSalesServiceTest)serializer.ReadObject(DeSerializememoryStream);
                }
                #endregion

Seriliaze

Classımızdaki verileir Json formatına çevirelim.

   #region Serialize
               JsonSalesServiceTest json = new JsonSalesServiceTest();
               json.Status = PluginMessages.Cancel;
               json.Source ="Dynamics CRM AGC";

 if (order.OwningBusinessUnit != null && order.OwningBusinessUnit.Id != Guid.Empty)
                        json.BusinessUnit = new Reference1()
                        {
                            Name = order.OwningBusinessUnit.Name,
                            Id = order.OwningBusinessUnit.Id
                        };

                    if (order.CustomerId != null && order.CustomerId.Id != Guid.Empty)
                    {
                        json.Customer = new Reference1() { Name = order.CustomerId.Name, Id = order.CustomerId.Id };
                    }

 json.CustomerAddress = !string.IsNullOrEmpty(order.BillTo_Line1) ? order.BillTo_Line1 : " ";

                string parameter1 = "";
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonSalesServiceTest));
                    serializer.WriteObject(memoryStream, json);
                    parameter1 = Encoding.Default.GetString(memoryStream.ToArray());
                }

#endregion

Hiç yorum yok:

Yorum Gönder