How to add a new entity to MS CRM - dynamics-crm-2011

I want to create an new entity in crm
OrganizationService_orgService ;
var connection = CrmConnection.Parse(conn);
_orgService = new OrganizationService(connection);
Entity newEntity = new Entity("this_is_a_new_entity");
Guid newEntityID = _orgService.Create(newEntity);
I wrote the above code where the conn is the connection string in the format which is correct (i checked)
string conn = "Url=https://damnidiot.crm5.dynamics.com; Username=XXXXXXXX#damnidiot.onmicrosoft.com; Password=XXXXXXXXX;";
but when i run the code i get an exception {"The entity with a name = 'this_is_a_new_entity' was not found in the MetadataCache."}
i am asuming i got this error because my crm does not have defination for the entity this_is_a_new_entity .
Is it possible to retrive And update the metadata cache of my MS CRM ?(I AM USING Microsoft Dynamics CRM 2013 )

If you use new Entity("new_entity_name") you are telling the code that you want to create a new record inside the already existing entity named new_entity_name.
To create a new entity altogether you have to issue a CreateEntityRequest (link to MSDN)
// PART OF THE LINKED SAMPLE
CreateEntityRequest createrequest = new CreateEntityRequest
{
//Define the entity
Entity = new EntityMetadata
{
SchemaName = _customEntityName,
DisplayName = new Label("Bank Account", 1033),
DisplayCollectionName = new Label("Bank Accounts", 1033),
Description = new Label("An entity to store information about customer bank accounts", 1033),
OwnershipType = OwnershipTypes.UserOwned,
IsActivity = false,
},
// Define the primary attribute for the entity
PrimaryAttribute = new StringAttributeMetadata
{
SchemaName = "new_accountname",
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
MaxLength = 100,
Format = StringFormat.Text,
DisplayName = new Label("Account Name", 1033),
Description = new Label("The primary attribute for the Bank Account entity.", 1033)
}
};

To create new entity you should use Create Entity Request. Your code creates record of this_is_a_new_entity.

Related

Qualify Lead in MS CRM 2011

I'm newbie to CRM. I want to qualify a lead to create opportunity. I'm passing following parameters as request
CreateOpportunity
CreateAccount
CreateContact
customerid
targetentityname
targetentityid
requestname
transactioncurrencyid
statuscode
subject
fullname
lastname
companyname
createdby
campaignid
But am getting Insufficient parameter error as response.
Can anybody help me out by providing the missing parameters?
In case you need to create only opportunity from your lead it's completely enough to pass next parameters to QualifyLeadRequest:
1. CreateOpportunity
2. OpportunityCurrencyId
3. OpportunityCustomerId
4. Status
5. LeadId
Please take a look at sample code below
C#:
var rmc = new RetrieveMultipleRequest()
{
Query = new QueryExpression("organization")
{
ColumnSet = new ColumnSet("basecurrencyid")
}
};
var rmc_r = (RetrieveMultipleResponse)serviceProxy.Execute(rmc);
//Qualify lead
var qlr = new QualifyLeadRequest()
{
CreateOpportunity = true,
OpportunityCurrencyId = rmc_r.EntityCollection.Entities[0].GetAttributeValue<EntityReference>("basecurrencyid"),
OpportunityCustomerId = new EntityReference("account", new Guid(<your-existing-account-guid>)),
//3 is statuscode value "Qualified" for lead entity
Status = new OptionSetValue(3),
LeadId = new EntityReference("lead", new Guid(<your-existing-account-guid>))
};
Please take a look at SOAPLogger (SDK\SampleCode\CS\Client\SOAPLogger) tool distributed with Dynamics CRM SDK to get request XML string and send as request payload from your client extensions (JavaScript).
via

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);

Associate Multiple records to subgrid using plugin in Dynamics crm

I'm associating record to some other entity using AssociateRequest.My question is how to Associate multiple records to subgrid.could you plz anyone clarify me.
Entity en=(Entity)context.InputParameters["Target"];
AssociateRequest assreq = new AssociateRequest();
assreq.Target = new EntityReference(en.LogicalName,en.Id);
assreq.RelatedEntities = new EntityReferenceCollection();
assreq.RelatedEntities.Add(new EntityReference("contact", new Guid("72C8B80B-FEF1-E311-9345-D89D67642EB0")));
assreq.Relationship = new Relationship("contact_customer_accounts");
AssociateResponse assresponse = (AssociateResponse)service.Execute(assreq);
The AssociateRequest can only be used to create a relationship between two records. If you need to associate a record multiple times, you will have to repeat the procedure for every single relationship.
You can pack the AssociateRequest's into an ExecuteMultipleRequest and save some roundtrips to the server. Please, keep in mind: the requests that are in the ExecuteMultipleRequest do not participate in the same database transaction.
OrganizationRequestCollection associateRequestCollection = new OrganizationRequestCollection();
Entity en = (Entity)context.InputParameters["Target"];
you will have to create AssociateRequest for every single
relationship and add them int associateRequestCollection object like below
AssociateRequest assreq = new AssociateRequest();
assreq.Target = new EntityReference(en.LogicalName, en.Id);
assreq.RelatedEntities = new EntityReferenceCollection();
assreq.RelatedEntities.Add(new EntityReference("contact", new Guid("72C8B80B-FEF1-E311-9345-D89D67642EB0")));
assreq.Relationship = new Relationship("contact_customer_accounts");
associateRequestCollection.Add(assreq);
//Process the Create Multiple emails against Contact Ids;
ExecuteMultipleResponse emResponses = ExecuteCRMMultipleRequest(associateRequestCollection);
private ExecuteMultipleResponse ExecuteCrmMultipleRequest(OrganizationRequestCollection associateRequestCollection)
{
ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest
{
Requests = associateRequestCollection,
Settings = new ExecuteMultipleSettings
{
ContinueOnError = true,
ReturnResponses = true
}
};
return (ExecuteMultipleResponse)service.Execute(emRequest);
}

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);
}

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