1

Closed

Mutex Is Not Supported in CRM Online

description

The Mutex is not supported in sandbox mode. To fix this you can replace the mutex with a locking object.
 
// Fields
    //private static Mutex _sync = new Mutex(false, "CRM.Plugin.SequenceGenerator.SequenceGeneratorPlugins");
    private static object _lockingObject = new object();

    // Methods
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        ITracingService service = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
        IOrganizationService service2 = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(context.UserId));
        if (context.InputParameters.Contains("Target") && (context.InputParameters["Target"] is Entity))
        {
            Entity entity = context.InputParameters["Target"] as Entity;
            //_sync.WaitOne();
            try
            {
                lock (_lockingObject)
                {
                    SequenceHelper settings = SequenceHelper.GetSettings(service2, entity.LogicalName);
                    if ((settings != null) && !entity.Attributes.Contains(settings.PropertyName))
                    {
                        int next = settings.CurrentPosition + 1;
                        string str = "";
                        if ((settings.Prefix != "") && (settings.Postfix != ""))
                        {
                            throw new InvalidPluginExecutionException("The configuration is invalid. Prefix and Postfix are both provided. Please contact adminsitrator with the issue.");
                        }
                        if (settings.Prefix != "")
                        {
                            str = settings.Prefix + next.ToString();
                        }
                        else if (settings.Postfix != "")
                        {
                            str = settings.Postfix + next.ToString();
                        }
                        else
                        {
                            str = next.ToString();
                        }
                        entity.Attributes.Add(settings.PropertyName, str);
                        settings.Increment(service2, next);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new InvalidPluginExecutionException(exception.ToString());
            }
        }
    }
}
Thanks,
Andrew
Closed Jul 30, 2012 at 10:31 AM by jaimieji
changed to lock object and plugin transaction statement

comments