web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

MS Visual Studio 2015 Dynamics Plugin Template doesn t work with CRM On line

(0) ShareShare
ReportReport
Posted on by

/ <copyright file="PluginBase.cs" company="">
// Copyright (c) 2017 All Rights Reserved
// </copyright>
// <author></author>
// <date>5/31/2017 9:30:50 AM</date>
// <summary>Implements the PluginBase Workflow Activity.</summary>
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
// </auto-generated>
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;

namespace Plugins1
{
/// <summary>
/// Base class for all plug-in classes.
/// </summary>
public abstract class PluginBase : IPlugin
{
/// <summary>
/// Plug-in context object.
/// </summary>
protected class LocalPluginContext
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "LocalPluginContext")]
internal IServiceProvider ServiceProvider { get; private set; }

/// <summary>
/// The Microsoft Dynamics 365 organization service.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "LocalPluginContext")]
internal IOrganizationService OrganizationService { get; private set; }

/// <summary>
/// IPluginExecutionContext contains information that describes the run-time environment in which the plug-in executes, information related to the execution pipeline, and entity business information.
/// </summary>
internal IPluginExecutionContext PluginExecutionContext { get; private set; }

/// <summary>
/// Synchronous registered plug-ins can post the execution context to the Microsoft Azure Service Bus. <br/>
/// It is through this notification service that synchronous plug-ins can send brokered messages to the Microsoft Azure Service Bus.
/// </summary>
internal IServiceEndpointNotificationService NotificationService { get; private set; }

/// <summary>
/// Provides logging run-time trace information for plug-ins.
/// </summary>
internal ITracingService TracingService { get; private set; }

private LocalPluginContext() { }

/// <summary>
/// Helper object that stores the services available in this plug-in.
/// </summary>
/// <param name="serviceProvider"></param>
internal LocalPluginContext(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new InvalidPluginExecutionException("serviceProvider");
}

// Obtain the execution context service from the service provider.
PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

// Obtain the tracing service from the service provider.
TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

// Get the notification service from the service provider.
NotificationService = (IServiceEndpointNotificationService)serviceProvider.GetService(typeof(IServiceEndpointNotificationService));

// Obtain the organization factory service from the service provider.
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

// Use the factory to generate the organization service.
OrganizationService = factory.CreateOrganizationService(PluginExecutionContext.UserId);
}

/// <summary>
/// Writes a trace message to the CRM trace log.
/// </summary>
/// <param name="message">Message name to trace.</param>
internal void Trace(string message)
{
if (string.IsNullOrWhiteSpace(message) || TracingService == null)
{
return;
}

if (PluginExecutionContext == null)
{
TracingService.Trace(message);
}
else
{
TracingService.Trace(
"{0}, Correlation Id: {1}, Initiating User: {2}",
message,
PluginExecutionContext.CorrelationId,
PluginExecutionContext.InitiatingUserId);
}
}
}

/// <summary>
/// Gets or sets the name of the child class.
/// </summary>
/// <value>The name of the child class.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "PluginBase")]
protected string ChildClassName { get; private set; }

/// <summary>
/// Initializes a new instance of the <see cref="PluginBase"/> class.
/// </summary>
/// <param name="childClassName">The <see cref=" cred="Type"/> of the derived class.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "PluginBase")]
internal PluginBase(Type childClassName)
{
ChildClassName = childClassName.ToString();
}

/// <summary>
/// Main entry point for he business logic that the plug-in is to execute.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <remarks>
/// For improved performance, Microsoft Dynamics 365 caches plug-in instances.
/// The plug-in's Execute method should be written to be stateless as the constructor
/// is not called for every invocation of the plug-in. Also, multiple system threads
/// could execute the plug-in at the same time. All per invocation state information
/// is stored in the context. This means that you should not use global variables in plug-ins.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CrmVSSolution411.NewProj.PluginBase+LocalPluginContext.Trace(System.String)", Justification = "Execute")]
public void Execute(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new InvalidPluginExecutionException("serviceProvider");
}

// Construct the local plug-in context.
LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);

localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));

try
{
// Invoke the custom implementation
ExecuteCrmPlugin(localcontext);
// now exit - if the derived plug-in has incorrectly registered overlapping event registrations,
// guard against multiple executions.
return;
}
catch (FaultException<OrganizationServiceFault> e)
{
localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));

// Handle the exception.
throw new InvalidPluginExecutionException("OrganizationServiceFault", e);
}
finally
{
localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
}
}

/// <summary>
/// Placeholder for a custom plug-in implementation.
/// </summary>
/// <param name="localcontext">Context for the current plug-in.</param>
protected virtual void ExecuteCrmPlugin(LocalPluginContext localcontext)
{
// Do nothing.
}
}
}

*This post is locked for comments

I have the same question (0)
  • Community Member Profile Picture
    on at

    Problem with 2016 CRM PluginRegistration.exe  

  • Community Member Profile Picture
    on at

    This simple one works! :)

    using System;

    using System.ServiceModel;

    using Microsoft.Xrm.Sdk;

    public class MyPlugin: IPlugin

    {

       public void Execute(IServiceProvider serviceProvider)

       {

           // Extract the tracing service for use in debugging sandboxed plug-ins.

           // If you are not registering the plug-in in the sandbox, then you do

           // not have to add any tracing service related code.

           ITracingService tracingService =

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

           // Obtain the execution context from the service provider.

           IPluginExecutionContext context = (IPluginExecutionContext)

               serviceProvider.GetService(typeof(IPluginExecutionContext));

           // The InputParameters collection contains all the data passed in the message request.

           if (context.InputParameters.Contains("Target") &&

               context.InputParameters["Target"] is Entity)

           {

               // Obtain the target entity from the input parameters.

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

               // Verify that the target entity represents an entity type you are expecting.

               // For example, an account. If not, the plug-in was not registered correctly.

               if (entity.LogicalName != "account")

                   return;

               // Obtain the organization service reference which you will need for

               // web service calls.

               IOrganizationServiceFactory serviceFactory =

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

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

               try

               {

                   // Plug-in business logic goes here.

               }

               catch (FaultException<OrganizationServiceFault> ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);

               }

               catch (Exception ex)

               {

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

                   throw;

               }

           }

       }

    }

  • Thomas David Dayman Profile Picture
    11,323 on at

    Try downloading this:

    github.com/.../CRMDeveloperExtensions

    It works perfectly!

  • Community Member Profile Picture
    on at

    Tx, I have already installed it: is where the first template come from

  • Community Member Profile Picture
    on at

    I experienced the same problem when trying to use the PluginBase.cs (included with the Developer Toolkit).  The problem is that the base class is missing a default (parameterless) constructor which Dynamics apparently needs in order to instantiate the class.  I've added this line to PluginBase.cs, and it seems to now work, however I feel like there is going to be some negative side-effect from this as the ChildClassName property is not being initialized.   Here is what I added to PluginBase.cs:

    internal PluginBase()
    {
    }
    

    That's it.  Once I rebuilt and deployed the plug-in, it worked.

  • Suggested answer
    Community Member Profile Picture
    on at

    Actually, after a bit of experimentation, this works better.

    Replace this constructor in PluginBase.cs:

           internal PluginBase(Type childClassName)

           {

               ChildClassName = childClassName.ToString();

           }

    With this:

           internal PluginBase()

           {

               ChildClassName = this.GetType().Name;

           }

    Then remove any constructor override from your deriving class leaving ONLY the ExecuteCrmPlugin() method.

  • Lama Profile Picture
    37 on at

    Hello

    I am facing the same issue

    I tried the suggested solution and still having the plugin fire with object reference once it enters the execute

    Any help is highly appreciated

    Thanks

    Lama

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans