Showing posts with label Dynamics CRM. Show all posts
Showing posts with label Dynamics CRM. Show all posts

Tuesday, 2 December 2025

Secure and Unsecure configuration in Dynamics CRM 365.

Overview: In Dynamics CRM, when we create a plugin, we sometimes need to pass data to that plugin, instead of writing this data inside the plugin code. We can pass it using Secure and Unsecure configurations. 

Advantge  

Security - Protect sensitive information like API Key.

Flexibility -Easily change configuration values without modifying the Plugin code.

Reusability - Use the same plugin in different environments with different configuration values. 

Sample Code 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Text.Json.Serialization;

using System.Threading.Tasks;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Newtonsoft.Json;

namespace SendCustomerData

{

    public class SendCustomerDataUnSecureAndSecureConfig : IPlugin

    {

        private readonly string _unsecureString;

        private readonly string _secureString;

        public SendCustomerDataUnSecureAndSecureConfig(string unsecureString, string secureString)

        {

            _unsecureString = unsecureString;

            _secureString = secureString;

        }

        public void Execute(IServiceProvider serviceProvider)

        {

            IPluginExecutionContext context =

                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory =

                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));


            ITracingService tracingService =

                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("Unsecure Config: {0}", _unsecureString);

            tracingService.Trace("Secure Config: {0}", _secureString);

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);


            //Ensure that the plugin is trigger on Create Mesage .

            if (context.MessageName != "Create" || context.PrimaryEntityName.ToLower() != "contact")

            {

                return;


            }

            //Get the contact details from the input parameters

            Entity contact = (Entity)context.InputParameters["Target"];

            string firstName = contact.Contains("firstname") ? contact["firstname"].ToString() : string.Empty;

            string lastName = contact.Contains("lastname") ? contact["lastname"].ToString() : string.Empty;

            string email = contact.Contains("emailaddress1") ? contact["emailaddress1"].ToString() : string.Empty;


            //Prepare the customer data to be sent

            var customerdata = new

            {

                FirstName = firstName,

                LastName = lastName,

                Email = email

            };

            string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(customerdata);

            tracingService.Trace("Customer Data JSON: {0}", jsonData);

            try

            {

                using (HttpClient client = new HttpClient())

                {

                    client.BaseAddress = new Uri(_unsecureString);

                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_secureString}");

                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = client.PostAsync("addCustomInfo", content).Result;

                    if (response.IsSuccessStatusCode)

                    {

                        tracingService.Trace("Customer data sent successfully.");

                    }

                    else

                    {

                        tracingService.Trace("Failed to send customer data. Status Code: {0}, Reason: {1}",

                            response.StatusCode, response.ReasonPhrase);



                    }

                }

            }

            catch (Exception ex)

            {

                tracingService.Trace("An error occurred while sending customer data.");

                throw new InvalidPluginExecutionException("An error occurred in SendCustomerDataUnSecureAndSecureConfig plugin.", ex);


            }


        }

    }


}



Saturday, 16 August 2025

Retrieves the record GUID (ID) using isDirty function.

isDirty() → This function is used to check whether the form data has been changed but not yet saved.

// JavaScript source code

function retrieveEntityInfo(executionContext) {

    if (executionContext != null) {

        var formContext = executionContext.getFormContext();

        var accountId = formContext.data.entity.getId();

        if (accountId) {

            alert("Account GUID: " + accountId);

        } else {

            alert("This Account record has not been saved yet (no GUID).");

        }

    }

}


Monday, 23 June 2025

How to convert plugin assembly (dll) into base 64 bytes using console application (C#).

 using System;

using System.IO;

using System.ServiceModel.Description;

using Microsoft.Rest;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Tooling.Connector;

namespace ConsoleApp2

{

    internal class Program

    {

        static void Main(string[] args)

        {

            string connectionString = @"AuthType=OAuth;

                Username=*****************;

                Password=*****************;

                Url=https://*****************.crm8.dynamics.com;

                AppId=*****************;

                 LoginPrompt=Auto";

            Console.WriteLine("Connecting to Dynamics 365..");


            using (CrmServiceClient serviceClient = new CrmServiceClient(connectionString))

            {

                if (!serviceClient.IsReady)

                {

                    Console.WriteLine("Failed to connect: " + serviceClient.LastCrmError);

                    return;

                }

                IOrganizationService service = (IOrganizationService)serviceClient.OrganizationWebProxyClient ?? (IOrganizationService)serviceClient.OrganizationServiceProxy;

                Console.WriteLine("connected to Dynamics Crm ");

                QueryExpression query = new QueryExpression("pluginassembly")

                {

                    ColumnSet = new ColumnSet("name", "content")

                };

                EntityCollection results = service.RetrieveMultiple(query);


                foreach (Entity plugin in results.Entities)

                {

                    string name = plugin.GetAttributeValue<string>("name");

                    string content = plugin.GetAttributeValue<string>("content");

                    if (string.IsNullOrEmpty(content))

                    {

                        Console.WriteLine($"Assembly '{name}' has no content.");

                        continue;

                    }

                    byte[] dllBytes = Convert.FromBase64String(content);

                    string fileName = $"{name}.dll";

                    File.WriteAllBytes(fileName, dllBytes);

                    Console.WriteLine($"Downloaded: {fileName}");

                }

                Console.WriteLine("All assemblies downloaded successfully.");

            }

        }

    }

}

Notes -Replace credentials as per your  CRM environment.

Secure and Unsecure configuration in Dynamics CRM 365.

Overview : In Dynamics CRM, when we create a plugin, we sometimes need to pass data to that plugin, instead of writing this data inside the ...