Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Help with Pre-Operation Plug-In that Updates "Modified By" field based on a text field

Posted on by Microsoft Employee

I am trying to update the "Modified By" field based on a text field called "Prepared By", which contains the name of a user.  I've created a pre-operation plug-in to do this and believe I am close to done.  However, the "Modified By" field is still not successfully getting updated.  I am relatively new to coding and CRM, and could use some help modifying the code and figuring out how I can get this to work.

Below is my code:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Linq;
namespace TimClassLibrary1.Plugins
{
    public class CreateUpdateContact : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            tracingService.Trace("Start plugin");
            tracingService.Trace("Validate Target");
            if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                return;
            tracingService.Trace("Retrieve Target");
            var target = (Entity)context.InputParameters["Target"];
            String message = context.MessageName.ToLower();
            SetCreatedByAndModifiedBy(tracingService, service, target, message);
        }
        private void SetCreatedByAndModifiedBy(ITracingService tracingService, IOrganizationService service, Entity target, string message)
        {
            tracingService.Trace("Start SetPriceList");
            tracingService.Trace("Validate Message is Create or Update");
            if (!message.Equals("create", StringComparison.OrdinalIgnoreCase) && !message.Equals("update", StringComparison.OrdinalIgnoreCase))
                return;
            tracingService.Trace("Retrieve Attributes");
            var createdByReference = target.GetAttributeValue<EntityReference>("new_createdby");
            var modifiedByReference = target.GetAttributeValue<EntityReference>("new_modifiedby");
            tracingService.Trace("Retrieve And Set User for Created By");
            RetrieveAndSetUser(tracingService, service, target, createdByReference, "createdby");
            tracingService.Trace("Retrieve And Set User for Modified By");
            RetrieveAndSetUser(tracingService, service, target, modifiedByReference, "modifiedby");
        }
        private void RetrieveAndSetUser(ITracingService tracingService, IOrganizationService service, Entity target, EntityReference reference, string targetAttribute)
        {
            tracingService.Trace("Validating Reference");
            if (reference == null)
                return;
            tracingService.Trace("Retrieving and Validating User");
            var user = RetrieveUserByName(service, reference.Name, new ColumnSet(false));
            if (user == null)
                return;
            tracingService.Trace("Setting Target Attribute");
            target[targetAttribute] = user.ToEntityReference();
        }
        private Entity RetrieveUserByName(IOrganizationService service, string name, ColumnSet columns)
        {
            var query = new QueryExpression
            {
                EntityName = "systemuser",
                ColumnSet = columns,
                Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "fullname",
                            Operator = ConditionOperator.Equal,
                            Values = { name }
                        }
                    }
                }
            };
            var retrieveResponse = service.RetrieveMultiple(query);
            if (retrieveResponse.Entities.Count == 1)
            {
                return retrieveResponse.Entities.FirstOrDefault();
            }
            else
            {
                return null;
            }
        }
    }
}
Thank you!

*This post is locked for comments

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Help with Pre-Operation Plug-In that Updates "Modified By" field based on a text field

    You can also refer this thread - community.dynamics.com/.../update-modified-on-date-using-plugin

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Help with Pre-Operation Plug-In that Updates "Modified By" field based on a text field

    Hi,

    Check if you have any other plugin or workflow which is updating the entity. It is possible that your plugin is working fine but then the values are changing from some other process/plugin.

    Hope this helps.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans