How to get id of saved entity - dynamics-crm-2011

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;

Related

Error during run OrganizationRequest 'RetrieveAllEntities'

I got this error during execute, could anyone give suggestion? Thanks
OrganizationRequest oreq = new OrganizationRequest();
oreq.RequestName = "RetrieveAllEntities";// please google for available Request Names
oreq.Parameters = new ParameterCollection();
oreq.Parameters.Add(new KeyValuePair<string, object>("EntityFilters", EntityFilters.Entity));
oreq.Parameters.Add(new KeyValuePair<string, object>("RetrieveAsIfPublished", false));
OrganizationResponse respo = orgProxy.Execute(oreq);
"The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter schemas.microsoft.com/xrm/2011/Contracts/Services:ExecuteResult. The InnerException message was 'Error in line 1 position 727. Element 'schemas.datacontract.org/2004/07/System.Collections.Generic:value' contains data of the 'schemas.microsoft.com/xrm/2011/Metadata:ArrayOfEntityMetadata' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'ArrayOfEntityMetadata' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details."
Add a reference to Microsoft.Crm.Sdk.Proxy and Microsoft.Xrm.Sdk. Visual Studio may tell you that you need to add an additional couple System.* references - add them.
Use this code:
IOrganizationService service = GetCrmService(connectionString); //This is a helper, just need to setup the service
var request = new Microsoft.Xrm.Sdk.Messages.RetrieveAllEntitiesRequest()
{
EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.All,
RetrieveAsIfPublished = false
};
var response = (Microsoft.Xrm.Sdk.Messages.RetrieveAllEntitiesResponse)service.Execute(request);
Get it work finally there is two KnownTypeAttribute need to be added to the proxy class
**[System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityMetadata[]))]**
public partial class OrganizationRequest : object, System.Runtime.Serialization.IExtensibleDataObject
....
**[System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityMetadata[]))]**
public partial class OrganizationResponse : object, System.Runtime.Serialization.IExtensibleDataObject
Thank you for help.

Retrieve Current ID Crm Online

Entity title = new Entity();
title = service.Retrieve("incident",((Guid)((Entity)context.InputParameters["Target"]).Id), new ColumnSet("title"));
I am using this code to get the current id of an Incident while i'am closing it!
But received this error :
Unexpected exception from plug-in (Execute): FecharIncidente.Plugins.PostIncidenteClose: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
One of my mates uses exactly the same code and is working on his crm !
Some help !?!
Apparently your InputParameters collection doesn't have a "Target" key value. Check that the request that you're using has a "Target" InputParameter.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
title = service.Retrieve("incident", ((Entity)context.InputParameters["Target"]).Id, new ColumnSet("title"));
Bet you "Target" in not Contained in InputParameters, resulting in KeyNotFoundException - "The given key was not present in the dictionary."
your can check for Target like Daryl explained or use the context available from the workflow rather like so ...
protected override void Execute(CodeActivityContext executionContext)
{
// Create the context
var context = executionContext.GetExtension<IWorkflowContext>();
var title = new Entity();
//context.PrimaryEntityName - should hold string incident
//context.PrimaryEntityId - should hold your guid
title = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet("title"));
}

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 discover all Entity Types? One of each?

I need to write a service that connects to CRM, and returns with a list of all of the entity available on the server (custom or otherwise).
How can I do this? To be clear, I am not looking to return all data for all entities. Just a list of every type, regardless of whether any actually exist.
You need to use RetrieveAllEntitiesRequest
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
{
EntityFilters = EntityFilters.Entity,
RetrieveAsIfPublished = true
};
// service is the IOrganizationService
RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request);
foreach (EntityMetadata currentEntity in response.EntityMetadata)
{
string logicalName = currentEntity.LogicalName;
// your logic here
}
note that you will get also system or hidden entities, like wizardpage or recordcountsnapshot
You will probably find these sections of the MSDN useful:
Customize Entity Metadata (lookout for the samples linked on that page).
Retrieve and Detect Changes to Metadata.

Update child entity / Attach entity to context

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.

Resources