Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Run plugin when record is opened

(0) ShareShare
ReportReport
Posted on by

I need to run my plugin when user is opened the Account record.

I used Registration Tool to Register New Assembly.

I created a step:

Message - Retrieve

Primary Entity - account

Event Pipeline Stage of Execution - Pre-operation.

By when I open the account - the plugin doesn't run (

What should I do to solve it?

my code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;

namespace FormLoadCRM
{
public class SetForm : IPlugin
{


public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext pluginContext =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory servicefactory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService client = servicefactory.CreateOrganizationService(pluginContext.UserId);
//throw new InvalidPluginExecutionException("Execute Method called");
SetcForm(client, pluginContext.UserId, tracingService);
}

private void SetcForm(IOrganizationService service, Guid userId, ITracingService tracingService)
{
try
{
// throw new InvalidPluginExecutionException("Last form viwed");
RetrieveEntityRequest request = new RetrieveEntityRequest();
request.LogicalName = "Account";
// Retrieve the MetaData.
RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value;

var query = new QueryExpression("userentityuisettings");
query.Criteria.AddCondition("ownerid", ConditionOperator.Equal, userId);
query.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, objecttypecode);
query.ColumnSet.AddColumn("lastviewedformxml");
EntityCollection encol = service.RetrieveMultiple(query);
string last1 = encol[0].Attributes["lastviewedformxml"].ToString();
// throw new InvalidPluginExecutionException("Last form viwed: " + last1);


string idFormToUse = string.Empty;
var query2 = new QueryExpression("systemform");
query2.Criteria.AddCondition("name", ConditionOperator.Equal, "Account");
query2.ColumnSet = new ColumnSet("formid");

EntityCollection form = service.RetrieveMultiple(query2);
if (form != null)
{
string guidformateado = form[0].Id.ToString();
idFormToUse = string.Format("", guidformateado);

string last = encol[0].Attributes["lastviewedformxml"].ToString();

if (!idFormToUse.Equals(last, StringComparison.InvariantCultureIgnoreCase))
{
Entity userUI = new Entity("userentityuisettings");
userUI.Id = encol[0].Id;
userUI.Attributes["lastviewedformxml"] = idFormToUse;
//just for unit testing.
//throw new InvalidPluginExecutionException("Last form viwed: " + last + " form to use: " + idFormToUse);
service.Update(userUI);
}

}
else
{
return;
}
}
catch (Exception ex)
{

tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
}
}
}
}

*This post is locked for comments

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at
    RE: Run plugin when record is opened

    Hi Priti,

    I would suggest make hard code your form id  instead of retrieving systemform as this wont change anymore.

    You can get formid from account record , go to right hand side popout button  of account record and then press F11 , from URL of browser take the formid.

  • Suggested answer
    Shahbaaz Ansari Profile Picture
    6,211 on at
    RE: Run plugin when record is opened

    Hi Priti,

    i tried your query and it is prefect, just make sure that in your account entity you have form with the name "Account".

    Go to setting-->customiztion->entity-->account--form and check if you have form with name "account".

    Hope this helps!!!

    Best Regards,

    Shahbaaz

  • Community Member Profile Picture
    on at
    RE: Run plugin when record is opened

    Please help me to fix above mentioned issue. How we can query "systemform"  entity

    var query2 = new QueryExpression("systemform");

                  query2.Criteria.AddCondition("name", ConditionOperator.Equal, "account");

                  query2.ColumnSet = new ColumnSet("formid");

                  EntityCollection form = client.RetrieveMultiple(query2);

                  //testing purpose

                  tracingService.Trace("Retrieved {0} entities", form.Entities.Count);

  • Community Member Profile Picture
    on at
    RE: Run plugin when record is opened

    Hi Shajbaaz

    you are right.but i want to know why it is not return any entity. i need to write some logic after returning entity from "systemform": Please check my code

    try

               {

                   RetrieveEntityRequest request = new RetrieveEntityRequest();

                   request.LogicalName = "account";

                   //Retrieve the MetaData.

                   RetrieveEntityResponse response = (RetrieveEntityResponse)client.Execute(request);

                   int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value;

                   var query = new QueryExpression("userentityuisettings");

                   query.Criteria.AddCondition("ownerid", ConditionOperator.Equal, pluginContext.UserId);

                   query.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, objecttypecode);

                   query.ColumnSet.AddColumn("lastviewedformxml");

                   EntityCollection encol = client.RetrieveMultiple(query);

                   string last1 = encol[0].Attributes["lastviewedformxml"].ToString();

                   string idFormToUse = string.Empty;

                   var query2 = new QueryExpression("systemform");

                   query2.Criteria.AddCondition("name", ConditionOperator.Equal, "account");

                   query2.ColumnSet = new ColumnSet("formid");

                   EntityCollection form = client.RetrieveMultiple(query2);

                   //testing purpose

                   tracingService.Trace("Retrieved {0} entities", form.Entities.Count);

                   //tessting purpose end

                   if (form != null)

                   {

                       string guidformateado = form[0].Id.ToString();

                       idFormToUse = string.Format("", guidformateado);

                       string last = encol[0].Attributes["lastviewedformxml"].ToString();

                       if (!idFormToUse.Equals(last, StringComparison.InvariantCultureIgnoreCase))

                       {

                           Entity userUI = new Entity("userentityuisettings");

                           userUI.Id = encol[0].Id;

                           userUI.Attributes["lastviewedformxml"] = idFormToUse;

                           client.Update(userUI);

                       }

                   }

                   else

                   {

                       return;

                   }

               }

               catch (Exception ex)

               {

                   tracingService.Trace("FollowupPlugin: {0}", ex.ToString());

               }

  • Suggested answer
    Shahbaaz Ansari Profile Picture
    6,211 on at
    RE: Run plugin when record is opened

    Hi Priti,

    You can check condition like if form.Entity.Count > 0 then only allow it to go inside.

    var query2 = new QueryExpression("systemform");

      query2.Criteria.AddCondition("name", ConditionOperator.Equal, "account");

                  query2.ColumnSet = new ColumnSet("formid");

                  EntityCollection form = client.RetrieveMultiple(query2);

    if (form.Entities.Count > 0)

    {

    // you logic

    }

    Hope this helps!!!

    Best Regards,

    Shahbaaz

  • Community Member Profile Picture
    on at
    RE: Run plugin when record is opened

    Hi Goutam

    Thanks for suggestion. I figured out where is problem.

    issue is in below code: when i query "systemform" table it is return no record.

    var query2 = new QueryExpression("systemform");

       query2.Criteria.AddCondition("name", ConditionOperator.Equal, "account");

                   query2.ColumnSet = new ColumnSet("formid");

                   EntityCollection form = client.RetrieveMultiple(query2);

                   //testing purpose

                   tracingService.Trace("Retrieved {0} entities", form.Entities.Count);

    OUTPUT of above query is:   Retrieved 0 entities

    please help me on regarding this.

    Thanks

  • Verified answer
    gdas Profile Picture
    50,091 Moderator on at
    RE: Run plugin when record is opened

    Hi Priti,

    It might be happen that your plugin is executing and internally getting exception . So try to debug your plugin and enable trace log , write  some message with basic plugin first using below reference  . Most important try to write try catch block in your plugin.

    davecorun.com/.../crm-2011retrieve-plugin

    www.magnetismsolutions.com/.../ahmed-anwar&;s-blog/2015/06/04/tracing-and-logging-plugins-in-dynamics-crm-2015-online

  • sardar ahmed Profile Picture
    520 on at
    RE: Run plugin when record is opened

    Hi Priti,

    This plugin wont trigger on opening of a record.

    Check below link

    www.magnetismsolutions.com/.../Call-Action-in-CRM-2015-Easily-from-JavaScript-Library

  • David Jennaway Profile Picture
    14,065 on at
    RE: Run plugin when record is opened

    How do you know that the plugin is not executing ? I'd suggest writing trace messages to track the progress, rather than throwing exceptions - it's generally more useful, and it is possible that CRM is not displaying the exception messages on a Retrieve

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

Announcing the Engage with the Community forum!

This forum is your space to connect, share, and grow!

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Leaderboard > Microsoft Dynamics CRM (Archived)

#1
Mohamed Amine Mahmoudi Profile Picture

Mohamed Amine Mahmoudi 83 Super User 2025 Season 1

#2
Community Member Profile Picture

Community Member 54

#3
Victor Onyebuchi Profile Picture

Victor Onyebuchi 6

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans