{"id":3703,"date":"2016-10-07T15:40:54","date_gmt":"2016-10-07T10:10:54","guid":{"rendered":"https:\/\/www.inogic.com\/blog\/?p=3703"},"modified":"2022-07-19T16:18:44","modified_gmt":"2022-07-19T10:48:44","slug":"working-with-json-objects-in-dynamics-crm-plugins","status":"publish","type":"post","link":"https:\/\/www.inogic.com\/blog\/2016\/10\/working-with-json-objects-in-dynamics-crm-plugins\/","title":{"rendered":"Working with JSON objects in Dynamics CRM Plugins"},"content":{"rendered":"<p>While working with Dynamics CRM plugin, we encountered a scenario where we were calling a Web API, which returns data in JSON format.<\/p>\n<p>Normally .NET framework provides many methods to use JSON in C# code, many third party solutions such as\u00a0<a href=\"http:\/\/www.newtonsoft.com\/json\" target=\"_blank\" rel=\"noopener noreferrer\">Newtonsoft.Json<\/a>\u00a0library are available. Mostly we use JavaScriptSerializer to read JSON data.<\/p>\n<p>However, when we register Plugin inside Sandbox, and if we try to use javascriptSerializer method in plugin, it will throw security exception error as show below:<\/p>\n<p>The error message we get:<\/p>\n<p>Unhandled Exception: Microsoft.Crm.CrmException: Unexpected exception from plug-in (Execute): XXXXXXXX.CRM2015.WorkflowActivities.XXXXXXXX: System.MethodAccessException: Attempt by security transparent method &#8216;XXXXXXXX.CRM2015.WorkflowActivities.XXXXXXXX.SetLocationInfo(Microsoft.Xrm.Sdk.IOrganizationService, Microsoft.Xrm.Sdk.ITracingService, System.String)&#8217; to access security critical method &#8216;System.Web.Script.Serialization.JavaScriptSerializer..ctor()&#8217; failed.<\/p>\n<p>Assembly &#8216;XXXXXXXX.CRM2015.WorkflowActivities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3f9fc15734725b08&#8217; is partially trusted, which causes the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself.\u00a0 In order to access security critical code, this assembly must be fully trusted.<\/p>\n<p>Assembly &#8216;System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&#8217; is a conditionally APTCA assembly which is not enabled in the current AppDomain.\u00a0 To enable this assembly to be used by partial trust or security transparent code, please add assembly name &#8216;System.Web.Extensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100B5FC90E7027F67871E773A8FDE8938C81DD402BA65B9201D60593E96C492651E889CC13F1415EBB53FAC1131AE0BD333C5EE6021672D9718EA31A8AEBD0DA0072F25D87DBA6FC90FFD598ED4DA35E44C398C454307E8E33B8426143DAEC9F596836F97C8F74750E5975C64E2189F45DEF46B2A2B1247ADC3652BF5C308055DA9&#8217; to the the PartialTrustVisibleAssemblies list when creating the AppDomain.<br \/>\nat Microsoft.Crm.Sandbox.SandboxCodeUnit.Execute(IExecutionContext context)<br \/>\nat Microsoft.Crm.Workflow.Services.ProxyCustomActivity.Execute(CodeActivityContext executionContext)<\/p>\n<p>This error occurs since we cannot access third party dll\u2019s in CRM context.<\/p>\n<p>To resolve this, we can use either ILMerge(utility for merging multiple .NET assemblies into a single one).<\/p>\n<p>However there is an alternate way to get it done without using third party solution, by using DataContractJsonSerializer in CRM plugin.<\/p>\n<p>Below code will demonstrate you how to use DataContractJsonSerializer in CRM plugin.<\/p>\n<p>To use JSON in CRM plugin<\/p>\n<ol>\n<li>Create a DataContract class that will define datamodel for JSON data that we receive from Web API.\n<pre class=\"lang:default decode:true\">[DataContract]\r\n    public class Student\r\n    {\r\n        [DataMember]\r\n        public string FullName { get; set; }\r\n        [DataMember]\r\n        public string JobTitle { get; set; }\r\n        [DataMember]\r\n        public string Contact { get; set; }\r\n        [DataMember]\r\n        public string Country { get; set; }\r\n        [DataMember]\r\n        public string ZIPCode { get; set; }\r\n       \r\n    }<\/pre>\n<\/li>\n<\/ol>\n<ul>\n<li>Deserialize Data obtained in JSON string to an object<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">using (MemoryStream DeSerializememoryStream = new MemoryStream())\r\n                {\r\n                    \/\/Json String that we get from web api \r\n                    string ResponseString = \"{\\\"FullName\\\":\\\"\" + \"Sam\" + \"\\\",\\\"JobTitle\\\":\\\"\" + \"Developer\" + \"\\\",\\\"Contact\\\":\\\"\" + \"808-124567\" + \"\\\",\\\"Country\\\":\\\"\" + \"India\" + \"\\\",\\\"ZIPCode\\\":\\\"\" + \"400005\" + \"\\\"}\";\r\n\r\n                    \/\/initialize DataContractJsonSerializer object and pass Student class type to it\r\n                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Student));\r\n\r\n                    \/\/user stream writer to write JSON string data to memory stream\r\n                    StreamWriter writer = new StreamWriter(DeSerializememoryStream);\r\n                    writer.Write(ResponseString);\r\n                    writer.Flush();\r\n\r\n                    DeSerializememoryStream.Position = 0;\r\n                    \/\/get the Desrialized data in object of type Student\r\n                    Student SerializedObject = (Student)serializer.ReadObject(DeSerializememoryStream);\r\n                }<\/pre>\n<ul>\n<li>Serialize Data in JSON string<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \">using (MemoryStream SerializememoryStream = new MemoryStream())\r\n                {\r\n                    \/\/create a sample data of type Student Class add details\r\n                    Student NewStudent = new Student();\r\n                    NewStudent.FullName = \"Sam\";\r\n                    NewStudent.JobTitle = \"Developer\";\r\n                    NewStudent.Contact = \"808-2125454\";\r\n                    NewStudent.Country = \"India\";\r\n                    NewStudent.ZIPCode = \"400005\";\r\n\r\n                    \/\/initialize DataContractJsonSerializer object and pass Student class type to it\r\n                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Student));\r\n                    \/\/write newly created object(NewStudent) into memory stream\r\n                    serializer.WriteObject(SerializememoryStream, NewStudent);\r\n                    \r\n                    \/\/use stream reader to read serialized data from memory stream\r\n                    StreamReader sr = new StreamReader(SerializememoryStream);\r\n                    \r\n                    \/\/get JSON data serialized in string format in string variable \r\n                    string Serializedresult = sr.ReadToEnd();\r\n                }\r\n<\/pre>\n<p>Hope this will help you in using JSON data in Dynamics CRM plugin!<\/p>\n<h2 style=\"text-align: left;\"><div class=\"su-heading su-heading-style-default su-heading-align-center\" id=\"\" style=\"font-size:15px;margin-bottom:5px\"><div class=\"su-heading-inner\">70% of global 2000 companies apply gamification to improve productivity and returns!<\/div><\/div><\/h2>\n<p><em><strong><a href=\"https:\/\/bit.ly\/3RD4lYW\" target=\"_blank\" rel=\"noopener noreferrer\">Gamifics365<\/a> <\/strong>\u2013 Spin the magic of games within Microsoft Dynamics 365 CRM to improve user adoption, enhance productivity, and achieve company goals!<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>While working with Dynamics CRM plugin, we encountered a scenario where we were calling a Web API, which returns data in JSON format. Normally .NET framework provides many methods to use JSON in C# code, many third party solutions such as\u00a0Newtonsoft.Json\u00a0library are available. Mostly we use JavaScriptSerializer to read JSON data. However, when we register\u2026 <span class=\"read-more\"><a href=\"https:\/\/www.inogic.com\/blog\/2016\/10\/working-with-json-objects-in-dynamics-crm-plugins\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[19,24,42],"tags":[974,975,976],"class_list":["post-3703","post","type-post","status-publish","format-standard","hentry","category-dynamics-crm","category-dynamics-crm-2016","category-plugin","tag-json-deserialization-dynamics-crm-plugin","tag-json-dynamics-crm-plugin","tag-json-serialization-dynamics-crm-plugin"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/3703","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/comments?post=3703"}],"version-history":[{"count":0,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/3703\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/media?parent=3703"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/categories?post=3703"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/tags?post=3703"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}