Change record owner in Dynamics CRM plugin - dynamics-crm

I am writing a Post PLugin changing the owner. When the owner has a substitution manager, the owner is changed to the substitution manager. I tried a service.Update and an AssignRequest, but these throw an exception.
When I post the request my entity cannot update (and then throws "The request channel time out while waiting for reply after 10:00:00"). But like I see there is no recursion, because when I logged it I have only one repetition of log and it has stopped before or on line with update.
var assignedIncident = new AssignRequest
{
Assignee = substManagerRef, //get it throw another method, alreay checked in test it`s correct
Target = new EntityReference ("incident", incedentId)
};
service.Execute(assignedIncident);
I tried to write target in another way
Target = postEntityImage.ToEntityReference()
I tried to write simple update but the problem is the same.
Entity incident = new Entity("incident" , incidentId);
incident["ownerid"] = substManagerRef:
service.Update(incident);
Can somebody help me with that? Or maybe show the way to solve it)

The plugin is triggering itself and gets in a loop. The system only allows a maximum of 8 calls deep within plugins and that is the reason it throws an error and rolls back the transaction.
To solve this issue redesign your plugin in the following way:
Register your plugin on the Update message of your entity in the PreValidation stage.
In the plugin pick up the Target property from the InputParameters collection.
This is an Entity type. Modify or set the ownerid attribute on this Entity object.
That is all. You do not need to do an update, your modification is now passed into the plugin pipeline.
Note: for EntityReference attributes this technique only works when your plugin is registered in the PreValidation stage. For other regular attributes it also works in the PreOperation stage.

Related

Retrieve Plugin not getting triggered

We are on Dynamics CRM 2016 On-Premise. Using a plugin I'm trying to automatically update a field when a user open the CRM Account form, in this example to value "5". Here's my code:
var targetEntity = (Entity)context.OutputParameters["BusinessEntity"];
if (targetEntity == null)
throw new InvalidPluginExecutionException(OperationStatus.Failed, "Target Entity cannot be null");
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);
if (targetEntity.Attributes.Contains("MyField"))
fedTaxId = targetEntity.Attributes["MyField"].ToString();
targetEntity.Attributes.Add("MyField"d, "5");
targetEntity["MyField"] = "5";
service.Update(targetEntity);
I list this in message type 10 (Before Main Operation Outside Transaction).
In Plugin Registration I list this as Post Operation stage and Synchronous.
However when I open the Account form, the page blinks once but the value did not get automatically populated. There is no javascript that would've manipulated this form or value either.
Any suggestion? Thanks.
Two options:
Add a script on the form setting the field value on load. Keep in mind this script should only do its thing if the form type = 2.
(Not recommended) Register a plugin on the synchronous post retrieve message for the entity. Make sure this step sets the field value on the entity object in the OutputParameters collection. Now, keep in mind your form will not be aware of the fact that this field has been modified, so it will not be flagged dirty and it will not automatically be submitted when record changes are being saved. So, in this scenario you would still need to add some JavaScript OR you would need an extra plugin registered on the pre update message of the entity setting the field as desired.

Ignore Duplicate Dection Rules in CRM upon Creation of an Account Within Plugin

I'm attempting to create an account within a Qualification Event Plugin. If I am creating an account with a name that matches exactly a name of an existing account, my Duplicate Detection Rule kicks in, and causes an exception to be thrown.
It was my understanding that duplicate detection rules were always warnings, not errors, and by default, you wouldn't get any errors or even notifications when running from a Plugin/SDK call Is this a new change to CRM? Is there a way to ignore Duplicate Detection Rules from a plugin?
Apparently you have to set the "SupressDuplicateDetection" Attribute in the create request:
Entity target = new Entity("account");
target["name"] = "I am a clone";
CreateRequest req = new CreateRequest();
req.Target = target;
req["SuppressDuplicateDetection"] = true;
CreateResponse response = (CreateResponse)_service.Execute(req);
This is intended, and apparently long standing behaviour based on MSDN documentation Run duplicate detection (listed as far back at CRM 2011).
Pass the duplicate detection optional parameter
SuppressDuplicateDetection by adding a value to the Parameters
property of the CreateRequest and UpdateRequest message requests. The
SuppressDuplicateDetection parameter value determines whether the
Create or Update operation can be completed:
true – Create or update the record, if a duplicate is found.
false - Do not create or update the record, if a duplicate is found.
Assuming false is the default as its a bool.
If the duplicate detection optional parameter is set to false and a
duplicate is found, an exception is thrown and the record is not
created or updated.

Updating opportunity when opportunity is won

I've got the task of updating a CRM plugin for a system migrating from cm 2013 to 2016. The plugin fails because it tries to set the opportunity state to won, simply by updating the field. And you need to use the WinOpporunityRequest to do so.
The logic is as follows:
When the opportunity is won the plugin executes and runs on the opportunityclose entity
The plugin creates a new custom entity record (project) and updates several other records.
It gets the current opportunity by using the opportunityid of the opportunityclose entity
It updates a field on the opportunity with a reference to the newly created project record.
That update is done through the Update() method.
On 5 it fails because when at 3 it gets the current opportunity it already has the state of won. And if you try to update the record with a new state it fails.
My question is, how can I get the opportunity when acting on the opportunityclose entity and update only the one single field. I do not need to set the state as this is done in the standard CRM flow.
--Edit
The line of code that fetches the opportunity:
Xrm.Opportunity currentOpportunityObjectToUpdate = serviceContext.CreateQuery<Xrm.Opportunity>().First(x => x.Id == entityRef.Id);
The platform allows you to update closed opportunities, I just tried it to verify. What is the error you are getting?
In step #5, make sure you're only sending the attributes you're trying to update (opportunityid and lookup to project). So, when you issue the update, don't use any preexisting opportunity object that you either retrieved or created...doing so sends all attributes that are on the object and the platform will process each attribute as if it were being changed even if the value is unchanged. Instead, create a new opportunity object with just the id and project specified, something like this:
context.AddObject(new Opportunity() {
Id = idOfOpportunity, // you may have to specify id both here...
OpportunityId = idOfOpportunity, // ...and here, can never remember. Doesn't hurt to specify in both places.
new_ProjectId = idOfProject
});
context.SaveChanges();
If you get stuck, you always have an easy workaround option: take the logic from #4 and move it to an async plugin on create of project (even a workflow should work).

SharePoint Business Connectiviy Data Model Update method failing

I have an external list in SharePoint that references a BCDM I created inside visual studio. The entity as an ID that is auto generated in the database, which means it's read-only.
Create and read method works fine, I'm trying to implement the update method. I have set an input parameter that match my entity and I'm getting this error.
Failed to update a list item for this external list based on the Entity(External Content Type) ‘Notification’ in EntityNamespace ‘Namespace’. Details: The TypeDescriptor with name ‘Id’ in the Method ‘Microsoft.SharePoint.BusinessData.MetadataModel.Static.Method’ on Entity (External Content Type) with Name ‘Namespace’ in Namespace ‘Notification’ is marked ‘PreUpdaterField’, but is contained by another TypeDescriptor marked ‘PreUpdaterField’.
I tried every possible combinaison to make this work, make the id type descriptor read only, pre-updater field = true/ false/, updater field = true/false, removing it, adding another parameter outside the entity. NOTHING WORKS !!! Obviously, I'm about to commit a murder as something so simple just turned out to be the biggest waste of time in my programmation history. What can I do to make this works??
This has been resolved and is explained here:
http://www.dotnetmikael.com/2014/02/sharepoint-2013-bcdm-with-visual-studio.html

Read Only Error on incident form in plugin CRM 2011 Plugin

I have a problem, which I'm really trying to figure out how I could best solve this. I have read various posts regarding this error and seems you can avoid this by using JavaScript by using:
Xrm.Page.getAttribute("name").setSubmitMode("always");
which doesn't work for me or inside the plugin. Now to my problem, I have an update plugin firing on my incident form, which updates some fields. However when I try to resolve the case or cancel it I get the error from my update plugin "The object cannot be updated because it is read-only" I have tried the following and would appreciate if somone could advice me what I'm doing wrong. My code for a plugin I'm registering as SetState on pre-operation against the incident form:
SetStateRequest setState = new SetStateRequest();
setState.EntityMoniker = new EntityReference();
setState.EntityMoniker.Id = incidentId; //Id which needs to be resolved/canceld
setState.EntityMoniker.Name = "statecode";
setState.EntityMoniker.LogicalName = "incident";
setState.State = new OptionSetValue();
setState.Status = new OptionSetValue();
SetStateResponse setStateResponse = (SetStateResponse)service.Execute(setState); }
On the state and status I'm quite confused to what value I have to set it to. I'm just getting an error when my incident is on Active and I'm trying to resolve and cancel the case. I would appreciate if someone could help me out here. Thanks in advance.
I think there are a few areas of confusion in your post...
Xrm.Page.getAttribute("name").setSubmitMode("always");
This is clientside code and will never have any bearing on the behaviour of your (serverside) plugin. It merely forces an attribute on the form to be submitted whether it has changed or not, during a save. If the record is in a read-only state, it will not change that fact.
I'm not at all clear what you are trying to acheive in your code. You mention that an update plugin is failing; you have posted code which would attempt to set the state of the incident to something (as #glosrob suggests, you are not providing any values in the OptionSetValue objects for State and Status so as you might already know, the code you have posted is invalid); you then state that you have registered your plugin on the SetState request. This means that it would fire if the user tries to set the state of the incident. Given that your code is itself trying to set the status of the incident, I'm not sure that it makes sense...
It sounds like what you want to do is, on update of an incident, set certain values. If the incident is in a read-only state, make it readable first, and then update the values. Do you then need to restore the state of the entity to it's former state? It sounds awkward and might perhaps suggest that there is a better way to meet your core requirement.
Maybe start with what you are trying to achieve and we can work from there :)
You should remove
setState.EntityMoniker.Name = "statecode";
from your code. This field Name has other purpose.
Also, you should add
setState.State.Value = 1;
setState.Status.Value = -1;

Resources