I am trying to auto populate account lookup field in my form upon selection of contact lookup field but when i perform it shows entity does not contain the respective id but when i debug it shows the right account name can any one let me know where i am making mistake?
Entity task = (Entity)context.InputParameters["Target"];
EntityReference lookupValue = task.GetAttributeValue<EntityReference>("new_contact");
if (lookupValue != null)
{
string targetEntityName = lookupValue.LogicalName;
Guid targetEntityId = lookupValue.Id;
QueryExpression query_contactparty = new QueryExpression("contact");
query_contactparty.Criteria = new FilterExpression();
query_contactparty.ColumnSet.AddColumns("contactid");
query_contactparty.ColumnSet.AddColumns("fullname");
query_contactparty.ColumnSet.AddColumns("parentcustomerid");
query_contactparty.Criteria.AddCondition("contactid", ConditionOperator.Equal, targetEntityId);
LinkEntity accountLink = new LinkEntity("contact", "account", "parentcustomerid", "accountid", JoinOperator.Inner);
accountLink.Columns = new ColumnSet("name");
query_contactparty.LinkEntities.Add(accountLink);
EntityCollection contactparty = service.RetrieveMultiple(query_contactparty);
foreach (var con in contactparty.Entities)
{
Guid accountid = con.GetAttributeValue<Guid>("contactid");
string name = con.GetAttributeValue<string>("fullname");
EntityReference parentAccount = con.GetAttributeValue<EntityReference>("parentcustomerid");
if (parentAccount != null)
{
//throw new InvalidPluginExecutionException("Value found is:" + name + " and id is: " + accountid + " account :" + parentAccount.Name);
task["new_account"] = new EntityReference("new_kaispe", parentAccount.Id)
{
Name = parentAccount.Name
};
}
service.Update(task);
}
}
In a plugin pipeline handling the Update message, an EntityReference value can be set in the pre validation stage. The Entity found in the "Target" property of the InputParameters collection only needs to be modified. Do not try to update it using service.Update(task).
Just remove that line and register your plugin for the pre validation stage.
Related
I am getting error - no service provision, someone with experience please help me.
var clinic = new new_clinic();
clinic.new_name = "Medinet";
Account trust = new Account();
trust.Name = "bIRMINGHAM CITY hOSPITAL";
Guid trustID = (Guid)Service().Create(trust);
CrmEntityReference clinic_trust = new CrmEntityReference(trust.LogicalName, trustID);
clinic.new_Trust = clinic_trust;
clinic.new_ClinicDate = DateTime.Now;
new_hospital hospital = new new_hospital();
hospital.new_name = "Geek-guru";
Service().Create(hospital);
Guid hospitalID = (Guid)hospital.Id;
clinic.new_HostingHospital = new CrmEntityReference(hospital.LogicalName, hospitalID);
clinic.new_ClinicDate = new DateTime(2018, 07, 28);
new_serviceprovision ser_contract = new new_serviceprovision();
ser_contract.new_Trust = clinic_trust;
ser_contract.new_Specialty = new OptionSetValue(100000018);
Service().Create(ser_contract);
Guid ser_con_id = (Guid)ser_contract.Id;
clinic.new_ServiceContract = new CrmEntityReference(ser_contract.LogicalName, ser_con_id);
// Account account = (Account)GetOrgService().Retrieve(trust.LogicalName, trustID, new Microsoft.Xrm.Sdk.Query.ColumnSet("name"));
//retreive the default business unit needed to create the user
QueryExpression businessUnitQuery = new QueryExpression
{
EntityName = BusinessUnit.EntityLogicalName,
ColumnSet = new ColumnSet("businessunitid"),
Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } }
};
BusinessUnit businessUnit = Service().RetrieveMultiple(businessUnitQuery).Entities[0].ToEntity<BusinessUnit>();
//creating a user
SystemUser systemUser = new SystemUser();
systemUser.DomainName = "" + "Chika";
systemUser.FirstName = "Olabajo";
systemUser.LastName = "Boss";
systemUser.InternalEMailAddress = "onyebuchi#gmail.com";
systemUser.BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessUnit.Id);
Guid systemID = (Guid)Service().Create(systemUser);
// systemUser = (SystemUser)Service().Retrieve(systemUser.LogicalName, systemID, new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname"));
//this field is a lookup field to User. Assigned to the user created above
clinic.new_ClinicCoordinator = new CrmEntityReference(systemUser.LogicalName, systemID);
clinic.new_BookedBy = new OptionSetValue(100000001);
clinic.new_Type1 = new OptionSetValue(100000008);
clinic.new_Type2 = new OptionSetValue(100000001);
clinic.new_NumberofConsultants = 5;
clinic.new_NumberofNursesSuppliedByTrust = 6;
Service().Create(clinic);//getting error here
MessageBox.Show("Sucessfully added a clinic record");
I have been on these for weeks now, I would appreciate a little bit of help.
I am now having "no serviceprivison issue", A user has now been created, but still gettting error.
Go step by step. You have 3 things one after other like Creating user, Retrieving FullName column, then updating clinic.new_ClinicCoordinator field. Comment out the 2 steps & verify if user is getting created or not, if created successfully then retrieve next (this is not needed as you already have systemID which is needed for update)
Use try catch for better exception handling in code
Edit: CRM online interactive user cannot be created in code. Read more
Update:
Merge the below lines, as ser_contract object is not updated back with created Guid. Do the same for hospitalID as well.
Service().Create(ser_contract);
Guid ser_con_id = (Guid)ser_contract.Id;
This should be working:
Guid ser_con_id = Service().Create(ser_contract);
I want to create new opportunity record in CRM. Opportunity record will get created based on this condition. It will compare account in CRM with organization in pipedrive. If matching Name is found then it will directly create opportunity else it will first create account and then opportunity.
How Can I add value to Account field which is Lookup field in Opportunity?
Below is the Code which I have written till now.
For getting Account records from CRM:
public EntityCollection GetAccount()
{
QueryExpression query = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet("name", "accountid") };
EntityCollection accountname = this.crmService.RetrieveMultiple(query);
return accountname;
}
For checking account is already there or not:
int accountCount = account.Entities.Count;
string[] name = new string[accountCount];
for (int i = 0; i < accountCount; i++)
{
name[i] = account.Entities[i].Attributes["name"].ToString();
if (name[i] == message.Current.org_name || name[i].Contains(message.Current.org_name))
{
this.counter++;
this.flag = 1;
continue;
}
}
if (this.counter == 1)
{
c.CreateOpportunity(message);
}
else if (this.counter > 1)
{
c.CreateAccount(message);
c.CreateOpportunity(message);
}
if (this.flag == 0)
{
c.CreateAccount(message);
c.CreateOpportunity(message);
}
To Create Opportunity record:
public void CreateOpportunity(Message message)
{
Entity opportunity = new Entity("opportunity");
opportunity["name"] = message.Current.Title;
opportunity["estimatedvalue"] = message.Current.value;
this.crmService.Create(opportunity);
}
You have to use like below in CreateOpportunity method:
opportunity["CustomerId"] = new EntityReference("account", accountId);
"CustomerId" is logical name of customer attribute, "account" is logical name of Account entity, accountId should be passed from created account record PK Guid or matched account PK from entity collection you have
Guid accountId = account.Entities[i].Id;
I am very new to MS-CRM and I want to retreive all the details of the contact
var executeQuickFindRequest = new OrganizationRequest("ExecuteQuickFind");
executeQuickFindRequest.Parameters = new ParameterCollection();
var entities = new List<string> { "contact", "lead", "account" }; //specify search term
executeQuickFindRequest.Parameters.Add("SearchText", "maria");
//will cause serialisation exception if we don't convert to array
executeQuickFindRequest.Parameters.Add("EntityNames", entities.ToArray());
var executeQuickFindResponse = _orgService.Execute(executeQuickFindRequest);
var result = executeQuickFindResponse.Results;
The data here displayed contains display name's such as address_1_City,email_user
However I want to get there actual names like Address,Email etc etc.
Thanks
Just to extend what BlueSam has mentioned above.
EntityMetadata entityMetaData = retrieveEntityResponse.EntityMetadata;
for (int count = 0; count < entityMetaData.Attributes.ToList().Count; count++)
{
if (entityMetaData.Attributes.ToList()[count].DisplayName.LocalizedLabels.Count > 0)
{
string displayName = entityMetaData.Attributes.ToList()[count].DisplayName.LocalizedLabels[0].Label;
string logicalName = entityMetaData.Attributes.ToList()[count].LogicalName;
AttributeTypeCode dataType = (AttributeTypeCode)entityMetaData.Attributes.ToList()[count].AttributeType;
}
}
Above code will help you to get the display name, logical name and data type for each attribute in the entity. Similarly you can get other information as well from the entityMetaData object as per above code snippet.
As far as I know, you will need to pair it up with the attributes of the entities that are for that request. Here's a sample of how to retrieve an entity:
RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Entity,
LogicalName = entityName
};
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest);
You can do it easy as below
using (var service = new OrganizationService(CrmConnection.Parse("CRMConnectionString")))
{
var Res = service.Retrieve("sv_answer", new Guid("GUID Of Record"), new ColumnSet("ColumnName "));
}
The following code throws a KeyNotFoundException at WriteLine():
CrmConnection crmConnection = CrmConnection.Parse(_connectionString);
using (OrganizationService service = new OrganizationService(crmConnection))
{
QueryExpression query = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet("fullname", "new_customer_num", "new_is_customer"),
};
EntityCollection contacts = service.RetrieveMultiple(query);
if (contacts.Entities.Count > 0)
{
foreach (var e in contacts.Entities)
{
System.Diagnostics.Debug.WriteLine(
e.Attributes["fullname"].ToString() + "; " +
e.Attributes["new_is_customer"].ToString());
}
}
}
I've already added new_customer_num and new_is_customer (required) fields to Contact entity. If I deliberately misspell them, then FaultException is thrown at service.RetrieveMultiple(query); so I guess CRM "knows" my custom fields. Then why doesn't query result include them?
Well, to make it work, I had to add a condition:
QueryExpression query = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet("fullname", "ht_customer_num", "ht_is_customer"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "new_is_customer",
Operator = ConditionOperator.Equal,
Values = { true }
},
},
}
};
SDK Doc for ColumnSet says that query returns only non-null values.
This code helps to retrieve the contact records based on the relation 1:N from the account entity
I want to retrieve the records of another custom entity called company from the account entity however I don't know how to call custom data entities to use it in the RetrieveContact method
- contact is a standard entity and company is a custom entity
PS: the account lookup of the company entity is called cs_accountid
BusinessEntityCollection bec = RetrieveContact(Service, context, ((Key)(Account.Properties["accountid"])).Value.ToString(), "contact", "parentcustomerid");
if (bec.BusinessEntities.Count > 0)
{
foreach (contact c in bec.BusinessEntities)
{
c.parentcustomerid = new Customer();
c.parentcustomerid.type = "account";
c.parentcustomerid.Value = k.Value;
Service.Update(c);
}
}
private BusinessEntityCollection RetrieveContact(ICrmService service, IPluginExecutionContext context, string AccountID, string FromEntityName, string FromAttributeName)
{
// Create the ConditionExpression.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "accountid";
condition.Operator = ConditionOperator.Equal;
condition.Values = new string[] { AccountID };
// Create the Link entities
LinkEntity le = new LinkEntity();
le.LinkFromEntityName = FromEntityName;
le.LinkFromAttributeName = FromAttributeName;
le.LinkToEntityName = "account";
le.LinkToAttributeName = "accountid";
// Create the FilterExpression.
FilterExpression filter = new FilterExpression();
// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.AddCondition(condition);
le.LinkCriteria = filter;
// Create the QueryExpression object.
QueryExpression query = new QueryExpression();
// Set the properties of the QueryExpression object.
query.EntityName = FromEntityName;// EntityName.contact.ToString();
query.ColumnSet = new AllColumns();// cols;
query.LinkEntities.Add(le);
//query.AddOrder("lastname", OrderType.Ascending);
BusinessEntityCollection bec = service.RetrieveMultiple(query);
return bec;
}
private DynamicEntity RetournRecord(string entityname, Guid recordid, TargetRetrieveDynamic target, ICrmService Service)
{
target.EntityId = recordid;
target.EntityName = entityname;
RetrieveRequest retrieve = new RetrieveRequest();
retrieve.Target = target;
retrieve.ColumnSet = new AllColumns();
retrieve.ReturnDynamicEntities = true;
// Create a response reference and execute the retrieve request.
RetrieveResponse response1 = (RetrieveResponse)Service.Execute(retrieve);
return (DynamicEntity)response1.BusinessEntity;
}
Thank you for your help and your time!
I know this is old, but the problem with the createquery is due to a typo-> ["cs_accountid") It should end with a square bracket not a round one.
UPDATE:
this solution is for CRM 2011/2013 and not for CRM 4.0:
i never used earlybinding so this is my example for the latebinding (will work for you, too).
using Microsoft.Xrm.Sdk.Client;
...
var service = OrganizationServiceFactory.CreateOrganizationService(PluginExecutionContext.UserId);
using (var context = new OrganizationServiceContext(service))
{
List<Entity> myCompanyRecords = context.CreateQuery("cs_company").Where(o => ((EntityReference)o["cs_accountid").Id.Equals(id)).ToList();
}
the "id" is the Guid of your account-entity-record.
in your method you already have the parameter "service" and "context" so you can just use this:
List<Entity> myCompanyRecords = context.CreateQuery("cs_company").Where(o => ((EntityReference)o["cs_accountid").Id.Equals(id)).ToList();