Update child entity / Attach entity to context - dynamics-crm-2011

I am creating a pre event plugin for CRM 2011 that sets the account owner and updates all the child contacts with the same owner. The plugin is installed correctly and updates the main account record correctly but the child contact owner does not change . I have pushed the owner name into another field of the contact to check I have the correct details and that field is updating.
I'm sure its something to do with attaching the child contacts to the correct context but so far I have drawn a blank.
//Set new account owner - Works fine
account.OwnerId = new EntityReference(SystemUser.EntityLogicalName, ownerId);
//Pass the same owner into the contacts - Does not get updated
UpdateContacts(account.Id, ownerId, service, tracingService);
The system is successfully updating the account owner and the description label of the child record.
public static void UpdateContacts(Guid parentCustomerId, Guid ownerId, IOrganizationService service, ITracingService tracingService)
{
// Create the FilterExpression.
FilterExpression filter = new FilterExpression();
// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.AddCondition(new ConditionExpression("parentcustomerid", ConditionOperator.Equal, parentCustomerId));
// Create the QueryExpression object.
QueryExpression query = new QueryExpression();
// Set the properties of the QueryExpression object.
query.EntityName = Contact.EntityLogicalName;
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;
// Retrieve the contacts.
EntityCollection results = service.RetrieveMultiple(query);
tracingService.Trace("Results : " + results.Entities.Count);
SystemUser systemUser = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, ownerId, new ColumnSet(true));
tracingService.Trace("System User : " + systemUser.FullName);
XrmServiceContext xrmServiceContext = new XrmServiceContext(service);
for (int i = 0; i < results.Entities.Count; i++)
{
Contact contact = (Contact)results.Entities[i];
contact.OwnerId = new EntityReference(SystemUser.EntityLogicalName, systemUser.Id);
contact.Description = systemUser.FullName;
xrmServiceContext.Attach(contact);
xrmServiceContext.UpdateObject(contact);
xrmServiceContext.SaveChanges();
tracingService.Trace("Updating : " + contact.FullName);
}
}
The tracing service prints out everything I would expect. Do I need to also attach the system user and somehow attach the entity reference to the context?
Any help appreciated.

You have to make a separate web service call using AssignRequest to change the ownership of a record. Unfortunately you cannot just change the Owner attribute.

I think I was getting myself into all sorts of mess with this plugin as by default changing the account owner automatically changes the associated contacts owner. I was therefore trying to overwrite something that it was already doing.
By using the AssignRequest to set the account owner rather than the child records it worked fine. Credit given to Chris as he pointed me in the right direction.
All that was needed was to change the first line of my code to use AssignRequest and the entire UpdateContacts method became obselete.

Related

Assign a Record to a team in dynamics crm 2013

Assign a record to user is fine but how to assign a record to team i'm unable to find the teamownershipid could you have any ideas.
You still need to use the AssignRequest, the only change is the LogicalName inside the EntityReference for the Assignee, instead of systemuser you need to put team.
An example:
Guid accountId = new Guid("90F8889F-EB95-E781-8417-000C44420CBC");
Guid teamId = new Guid("A8AA28B4-9015-DF11-8062-000E0CA08051");
AssignRequest assignRequest = new AssignRequest
{
Assignee = new EntityReference("team", teamId),
Target = new EntityReference("account", accountId)
};
service.Execute(assignRequest);

How to get id of saved entity

Dynamics CRM 2011 on premise
I can barely believe I can't find this out by Googling. MSDN is useless.
Here is some C# from a plugin:
integ_creditpayment creditpayment = new integ_creditpayment();
creditpayment.integ_Amount = totalPay;
//set more properties
context.AddObject(creditpayment);
context.SaveChanges();
Now I want to get the value of the id field in integ_creditpayment.
Can I get this immediately from creditpayment.id? (As in, does context.SaveChanges() cause the creditpayment variable to be updated with the new id?)
I'm assuming your real code is more complicated, but there is no need to use the context in your example code:
integ_creditpayment creditpayment = new integ_creditpayment();
creditpayment.integ_Amount = totalPay;
//set more properties
creditpayment.Id = service.Create(creditpayment);
You can also use a type initializer and get rid of your object all together if you'd like:
Guid id = service.Create(new integ_creditpayment
{
integ_Amount = totalPay;
});
service in this case is of type IOrganizationService
After the SaveChanges() you can get the record id with:
Guid justCreatedId = creditpayment.Id;

OrganizationServiceContext: System.InvalidOperationException: The context is already tracking the 'contact' entity

I'm trying to create a plugin that changes all related contacts' address fields if the parent account's address field is changed in account form. I created a plugin to run in pre operation stage (update message against account entity) synchronously.
I used LINQ query to retrieve all related contacts and it works. Then I'm using foreach loop to loop trough all contacts and change them address fields. I'm using OrganizationServiceContext.AddObject(); function to add every contact to the tracking pipeline (or whatever it's called) and finally I'm using OrganizationServiceContext.SaveChanges(); to trying to save all contacts. But that's when I'm getting this error:
System.InvalidOperationException: The context is already tracking the 'contact' entity.
Here's my code
// Updating child contacts' fields
if (context.PreEntityImages.Contains("preAccount") && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) {
if (((Entity)context.InputParameters["Target"]).Contains("address2_name")) {
Entity account = (Entity)context.InputParameters["Target"];
Entity preAccount = (Entity)context.PreEntityImages["preAccount"];
if (account["address2_name"] != preAccount["address2_name"]) {
EntityReference parentCustomer = new EntityReference(account.LogicalName, account.Id);
Contact[] childContacts = orgService.ContactSet.Where(id => id.ParentCustomerId == parentCustomer).ToArray();
foreach (Contact contact in childContacts) {
contact.Address2_Name = (string)account["address2_name"];
orgService.AddObject(contact);
}
orgService.SaveChanges();
}
}
}
What I'm doing wrong?
You already attached the entities to the context when you retrieved the contacts with the query
Contact[] childContacts = orgService.ContactSet.Where(id => id.ParentCustomerId == parentCustomer).ToArray();
so you don't need to add again the entities to the context, instead you need to update them, by:
orgService.UpdateObject(contact); // this row instead of orgService.AddObject(contact);

unable to change the account reference inside the contact using sdk in crm2011

I am unable to change the client by updating the contact using crm 2011 sdk.Here is the code i am using to do that :
Entity contact = new Entity();
contact.LogicalName = "contact";
contact.Attributes = new AttributeCollection();
EntityReference clientLookup = new EntityReference();
clientLookup.Id = NewClientBId;
clientLookup.LogicalName = "account";
contact.Attributes.Add("parentcustomerid", clientLookup);
contact.Attributes.Add("contactid", workItem.Id);
SynchronousUtility.UpdateDynamicEntity(CrmConnector.Service, contact);
The code runs fine without any error but when i go to web portal and check the record ,it still points to the old account though updated the modofication time stamp.I also checked the sql profiler query which shows up as below :
exec sp_executesql N'update [ContactBase] set
[ModifiedOn]=#ModifiedOn0, [ModifiedBy]=#ModifiedBy0,
[ModifiedOnBehalfBy]=NULL where ([ContactId] =
#ContactId0)',N'#ModifiedOn0 datetime,#ModifiedBy0
uniqueidentifier,#ContactId0
uniqueidentifier',#ModifiedOn0='2013-07-04
09:21:02',#ModifiedBy0='2F8D969F-34AB-E111-9598-005056947387',#ContactId0='D80ACC4E-A185-E211-AB64-002324040068'
as can be seen above the column i have updated is not even there in the set clause of the update query.Can anyone help me with this ?
I tested your code and it works:
Entity contact = new Entity();
contact.LogicalName = "contact";
contact.Attributes = new AttributeCollection();
EntityReference clientLookup = new EntityReference();
clientLookup.Id = new Guid("3522bae7-5ae5-e211-9d27-b4b52f566dbc");
clientLookup.LogicalName = "account";
contact.Attributes.Add("parentcustomerid", clientLookup);
contact.Attributes.Add("contactid", new Guid("16dc4143-5ae5-e211-9d27-b4b52f566dbc"));
As you can see I used existing Id in my environment, and to perform the update I used
service.Update(contact);
Reasons why your code is not working:
NewClientBId is not the right account Guid
workItem.Id is not the right contact Guid
the function SynchronousUtility.UpdateDynamicEntity has errors

How to update the Owner of a Case/Incident record

I'm writing a workflow activity that operates against an Incident record.The activity is intended to change the ownerid from a User to a Team that the User is a member of. I have retrieved this Team succesfully. The OwnerId field is the standard Owner type. I have tried the following:
if (results.Entities.Count > 0)
{
var er = new EntityReference("team",new Guid(results[0].Attributes["teamid"].ToString()));
er.Name = results[0].Attributes["name"].ToString();
updatedEnquiry.OwnerId = er;
Service.Update(updatedEnquiry);
}
results is an EntityCollection
Service is an IOrganizationService
Incident, Team and User entities are out of the box CRM 2011 entities.
After the workflow concludes on the Incident record, the Owner has not changed.
How can I update this Owner field with the new data?
To update the owner you need to use the AssignRequest and is not necessary to specify the name attribute for an EntityReference
// incidentId holds the record ID Guid to update
if (results.Entities.Count > 0)
{
// get the right team
Entity team = results.Entities[0];
AssignRequest assignRequest = new AssignRequest
{
Assignee = new EntityReference("team", team.Id),
Target = new EntityReference("incident", incidentId)
};
Service.Execute(assignRequest);
}

Resources