Friday, July 24, 2015

Override/ Persist the Modified Date / Actual End date in entities in CRM 2015/ 2013/ 2011.


We can override or persist modifiedon date / actual end date in crm in Pre Operation.

In below sample am overriding modifiedon date on update of notes. Same way you can override actualend date in CRM 2015/ 2013/ 2011

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Client;

namespace Plugin
{
    public class NotePlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IOrganizationService service = null;

            Entity entity = null;
            ITracingService tracingService = null;

            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                switch (context.MessageName)
                {
                    case "Update":
                        {

                            DateTime? createdon = null;
                            if (entity.Attributes.Contains("createdon"))
                            {
                                createdon = entity.GetAttributeValue("createdon");
                            }
                            else if (context.PreEntityImages.Contains("PreImage"))
                            {
                                Entity PreImage = context.PreEntityImages["PreImage"];

                                if (PreImage.Contains("createdon"))
                                {
                                    createdon = PreImage.GetAttributeValue("createdon");
                                }
                            }

                            if (createdon != null && entity.Attributes.Contains("modifiedon"))
                            {
                                entity["modifiedon"] = createdon;
                            }
                            else if (createdon != null)
                            {
                                entity.Attributes.Add("modifiedon", createdon);
                            }
                        }
                        break;
                }
            }
            catch (FaultException ex)
            {
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }




No comments: