public static XrmLeadResult CreateLead(Dictionary <string, string> properties, IDictionary <string, string> settings, IDictionary <string, string> actions, CrmConnection connection = null) { XrmLeadResult result = new XrmLeadResult(); bool match = Convert.ToBoolean(settings.GetValueOrDefault <string>("match", bool.FalseString)); Entity lead = new Entity("lead", Guid.NewGuid()); string email = properties.GetValueOrDefault <string>("emailaddress1", ""); string accountId = properties.GetValueOrDefault <string>("accountid", properties.GetValueOrDefault <string>("companyname", "")); Entity contact = null; Entity account = null; if (match && !string.IsNullOrEmpty(email)) { if (!string.IsNullOrEmpty(accountId)) { Guid g; if (Guid.TryParse(accountId, out g)) { account = XrmCore.Retrieve("account", g); } else { account = XrmCore.RetrieveByAttribute("account", "name", accountId).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault(); } } contact = XrmCore.RetrieveByAttribute("contact", "emailaddress1", email).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault(); if (contact != null) { lead["parentcontactid"] = contact.ToEntityReference(); result.ContactId = contact.Id.ToString(); if (accountId == null && contact.Contains("parentcustomerid")) { account = XrmCore.Retrieve("account", contact.GetAttributeValue <EntityReference>("parentcustomerid").Id); } //if (string.IsNullOrEmpty(accountId)) //{ // accountId = contact.GetAttributeValue<string>("parentcustomerid_name"); //} } if (account != null) { lead["parentaccountid"] = account.ToEntityReference(); result.AccountId = account.Id.ToString(); } } result.CompanyName = properties.GetValueOrDefault <string>("companyname", account != null && account.Contains("name") ? account.GetAttributeValue <string>("name") : ""); result.Email = email; result.FullName = properties.GetValueOrDefault <string>("fullname", contact != null && contact.Contains("fullname") ? contact.GetAttributeValue <string>("fullname") : ""); // Apply properties EntityMetadata meta = XrmCore.RetrieveMetadata("lead", EntityFilters.All, connection); foreach (KeyValuePair <string, string> kv in properties) { lead.SetAttributeMetaValue(kv, settings, meta); } Guid Id = XrmCore.CreateEntity(lead); result.LeadId = Id.ToString(); // Apply actions foreach (KeyValuePair <string, string> kv in actions) { lead.ApplyAction(kv); } return(result); }
public static void SetAttributeField(Entity entity, EntityMetadata metadata, AttributeMetadata att, string attributeName, string attributeValue) { Guid g; switch (att.AttributeType.Value) { case AttributeTypeCode.Boolean: entity[attributeName] = Convert.ToBoolean(attributeValue); break; case AttributeTypeCode.DateTime: DateTime dt; if (DateTime.TryParse(attributeValue, out dt)) { entity[attributeName] = dt; } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Decimal: case AttributeTypeCode.Money: decimal dec; if (decimal.TryParse(attributeValue, out dec)) { if (att.AttributeType.Value == AttributeTypeCode.Money) { entity[attributeName] = new Money(dec); } else { entity[attributeName] = dec; } } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Double: double dou; if (double.TryParse(attributeValue, out dou)) { entity[attributeName] = dou; } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Integer: int i; if (int.TryParse(attributeValue, out i)) { entity[attributeName] = i; } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.BigInt: long l; if (long.TryParse(attributeValue, out l)) { entity[attributeName] = l; } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Lookup: case AttributeTypeCode.Customer: //Guid g; //string[] v = attributeValue.Split(','); //if (Guid.TryParse(v[0], out g)) //{ // entity[attributeName] = new EntityReference(v[1], g)); //} //else //{ // throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); //} OneToManyRelationshipMetadata mto1 = metadata.ManyToOneRelationships.FirstOrDefault(x => x.ReferencedAttribute.Equals(attributeName, StringComparison.OrdinalIgnoreCase)); if (mto1 == null) { throw new InvalidOperationException(string.Format("The Many-To-One relationship for the attribute '{0}' does not exist", attributeName)); } Entity lookup = null; Guid gLookup; EntityMetadata mto1Meta = XrmCore.RetrieveMetadata(mto1.ReferencedEntity, EntityFilters.Entity); if (Guid.TryParse(attributeValue, out gLookup)) { lookup = XrmCore.Retrieve(mto1.ReferencingEntity, gLookup, new ColumnSet(mto1Meta.PrimaryIdAttribute)); } else { if (!string.IsNullOrEmpty(attributeValue)) { lookup = XrmCore.RetrieveByAttribute(mto1.ReferencedEntity, mto1Meta.PrimaryNameAttribute, attributeValue, new ColumnSet(mto1Meta.PrimaryIdAttribute)).Entities.FirstOrDefault(); } } if (!string.IsNullOrEmpty(attributeValue) && lookup == null && att.AttributeType.Value == AttributeTypeCode.Lookup) { lookup = new Entity(mto1Meta.LogicalName, Guid.NewGuid()); lookup[mto1Meta.PrimaryNameAttribute] = attributeValue; lookup.Id = XrmCore.CreateEntity(lookup); } if (lookup != null) { entity[attributeName] = lookup.ToEntityReference(); } break; case AttributeTypeCode.Memo: case AttributeTypeCode.String: { entity[attributeName] = attributeValue; } break; case AttributeTypeCode.Owner: if (Guid.TryParse(attributeValue, out g)) { entity[attributeName] = new EntityReference("systemuser", g); } else { Entity owner = XrmCore.RetrieveByAttribute("systemuser", "fullname", attributeValue, new ColumnSet("systemuserid")).Entities.FirstOrDefault(); if (owner == null) { throw new InvalidOperationException(string.Format("The system user '{0}' does not exist", attributeValue)); } entity[attributeName] = owner.ToEntityReference(); } break; case AttributeTypeCode.Picklist: case AttributeTypeCode.State: case AttributeTypeCode.Status: int iOption; if (int.TryParse(attributeValue, out iOption)) { entity[attributeName] = new OptionSetValue(iOption); } else { OptionMetadata opMeta = null; if (att.AttributeType.Value == AttributeTypeCode.Picklist) { opMeta = (att as PicklistAttributeMetadata).OptionSet.Options.FirstOrDefault(x => x.Label.LocalizedLabels.Any(lab => lab.Label.Equals(attributeValue, StringComparison.OrdinalIgnoreCase)) || x.Label.UserLocalizedLabel.Label.Equals(attributeValue, StringComparison.OrdinalIgnoreCase)); } else if (att.AttributeType.Value == AttributeTypeCode.State) { opMeta = (att as StateAttributeMetadata).OptionSet.Options.FirstOrDefault(x => x.Label.LocalizedLabels.Any(lab => lab.Label.Equals(attributeValue, StringComparison.OrdinalIgnoreCase)) || x.Label.UserLocalizedLabel.Label.Equals(attributeValue, StringComparison.OrdinalIgnoreCase)); } else if (att.AttributeType.Value == AttributeTypeCode.Status) { opMeta = (att as StatusAttributeMetadata).OptionSet.Options.FirstOrDefault(x => x.Label.LocalizedLabels.Any(lab => lab.Label.Equals(attributeValue, StringComparison.OrdinalIgnoreCase)) || x.Label.UserLocalizedLabel.Label.Equals(attributeValue, StringComparison.OrdinalIgnoreCase)); } if (opMeta == null) { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } else { entity[attributeName] = opMeta.Value.Value; } } break; case AttributeTypeCode.Uniqueidentifier: if (Guid.TryParse(attributeValue, out g)) { entity[attributeName] = g; } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", attributeName, attributeValue, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.PartyList: case AttributeTypeCode.CalendarRules: case AttributeTypeCode.Virtual: case AttributeTypeCode.ManagedProperty: case AttributeTypeCode.EntityName: throw new NotImplementedException(string.Format("The attribute type {0} is not supported", att.AttributeType.Value.ToString())); default: break; } }
public static XrmLeadResult CaptureLead(Dictionary <string, string> properties, IDictionary <string, string> settings, IDictionary <string, string> actions, CrmConnection connection = null) { XrmLeadResult result = new XrmLeadResult(); bool match = Convert.ToBoolean(settings.GetValueOrDefault <string>("match", bool.FalseString)); Entity lead = new Entity("lead", Guid.NewGuid()); string email = properties.GetValueOrDefault <string>("emailaddress1", ""); result.Email = email; string accountId = properties.GetValueOrDefault <string>("accountid", properties.GetValueOrDefault <string>("companyname", "")); Entity contact = null; Entity account = null; contact = XrmCore.RetrieveByAttribute("contact", "emailaddress1", email, CacheResults: false).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault(); if (contact != null) { result.ContactId = contact.Id.ToString(); result.FullName = contact.GetAttributeValue <string>("fullname"); if (contact.Contains("parentcustomerid")) { EntityReference accountReference = contact.GetAttributeValue <EntityReference>("parentcustomerid"); result.AccountId = accountReference.Id.ToString(); result.CompanyName = accountReference.Name; lead["parentaccountid"] = accountReference; } // return matched contact result return(result); } else { // No contact match. Match against an existing lead EntityCollection leadCollection = XrmCore.RetrieveByAttribute("lead", "emailaddress1", email, new Microsoft.Xrm.Sdk.Query.ColumnSet("createdon", "fullname", "parentcontactid", "parentaccountid", "companyname"), CacheResults: false); if (leadCollection.Entities.Count > 0) { lead = leadCollection.Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).First(); result.LeadId = lead.Id.ToString(); if (lead.Contains("fullname")) { result.FullName = lead.GetAttributeValue <string>("fullname"); } EntityReference er = null; if (lead.Contains("parentaccountid")) { er = lead.GetAttributeValue <EntityReference>("parentaccountid"); Entity parentAccount = XrmCore.Retrieve("account", er.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("statecode")); if (parentAccount != null && parentAccount.GetAttributeValue <OptionSetValue>("statecode").Value == 0) { result.AccountId = er.Id.ToString(); result.CompanyName = er.Name; } } else if (lead.Contains("companyname")) { result.CompanyName = lead.GetAttributeValue <string>("companyname"); } if (lead.Contains("parentcontactid")) { er = lead.GetAttributeValue <EntityReference>("parentcontactid"); Entity parentContact = XrmCore.Retrieve("contact", er.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("statecode")); if (parentContact != null && parentContact.GetAttributeValue <OptionSetValue>("statecode").Value == 0) { result.ContactId = er.Id.ToString(); } } // result matched lead result return(result); } } // // No contact or lead match. Create a new lead in the system // if (!string.IsNullOrEmpty(accountId)) { Guid g; if (Guid.TryParse(accountId, out g)) { account = XrmCore.Retrieve("account", g); } else { account = XrmCore.RetrieveByAttribute("account", "name", accountId).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault(); } if (account != null) { lead["parentaccountid"] = account.ToEntityReference(); properties.Remove("accountid"); result.AccountId = account.Id.ToString(); result.CompanyName = account.GetAttributeValue <string>("name"); } } if (account == null) { result.CompanyName = properties.GetValueOrDefault <string>("companyname", ""); } result.FullName = properties.GetValueOrDefault <string>("fullname", ""); if (string.IsNullOrEmpty(result.FullName)) { if (properties.ContainsKey("firstname") && properties.ContainsKey("lastname")) { result.FullName = string.Concat(properties.GetValueOrDefault <string>("firstname", ""), " ", properties.GetValueOrDefault <string>("lastname", "")); } } // Apply properties EntityMetadata meta = XrmCore.RetrieveMetadata("lead", EntityFilters.All, connection); foreach (KeyValuePair <string, string> kv in properties) { lead.SetAttributeMetaValue(kv, settings, meta); } Guid Id = XrmCore.CreateEntity(lead); result.LeadId = Id.ToString(); // Apply actions foreach (KeyValuePair <string, string> kv in actions) { lead.ApplyAction(kv); } return(result); }
public static void SetAttributeMetaValue(this Entity entity, KeyValuePair <string, string> kv, IDictionary <string, string> settings, EntityMetadata metadata = null) { if (metadata == null) { entity[kv.Key] = kv.Value; return; } AttributeMetadata att = metadata.Attributes.FirstOrDefault(x => x.LogicalName.Equals(kv.Key, StringComparison.OrdinalIgnoreCase)); string setting = ""; if (att == null) { // check special field rules setting = settings.GetValueOrDefault <string>(kv.Key + "_propertyalias", ""); if (setting != null) { att = metadata.Attributes.FirstOrDefault(x => x.LogicalName.Equals(setting, StringComparison.OrdinalIgnoreCase)); } if (att == null) { throw new InvalidOperationException(string.Format("Unknown attibute for {2}: '{0} with the value of {1}", kv.Key, kv.Value, entity.LogicalName)); } } else if (!att.AttributeType.HasValue) { entity[kv.Key] = kv.Value; return; } switch (att.AttributeType.Value) { case AttributeTypeCode.Boolean: entity.SetAttributeValue(kv.Key, Convert.ToBoolean(kv.Value)); break; case AttributeTypeCode.DateTime: DateTime dt; if (DateTime.TryParse(kv.Value, out dt)) { entity.SetAttributeValue(kv.Key, dt); } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Decimal: case AttributeTypeCode.Money: decimal dec; if (decimal.TryParse(kv.Value, out dec)) { if (att.AttributeType.Value == AttributeTypeCode.Money) { entity.SetAttributeValue(kv.Key, new Money(dec)); } else { entity.SetAttributeValue(kv.Key, dec); } } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Double: double dou; if (double.TryParse(kv.Value, out dou)) { entity.SetAttributeValue(kv.Key, dou); } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Integer: int i; if (int.TryParse(kv.Value, out i)) { entity.SetAttributeValue(kv.Key, i); } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.BigInt: long l; if (long.TryParse(kv.Value, out l)) { entity.SetAttributeValue(kv.Key, l); } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.Lookup: case AttributeTypeCode.Customer: OneToManyRelationshipMetadata mto1 = metadata.ManyToOneRelationships.FirstOrDefault(x => x.ReferencedAttribute.Equals(kv.Key, StringComparison.OrdinalIgnoreCase)); if (mto1 == null) { throw new InvalidOperationException(string.Format("The Many-To-One relationship for the attribute '{0}' does not exist", kv.Key)); } Entity lookup = null; Guid gLookup; EntityMetadata mto1Meta = XrmCore.RetrieveMetadata(mto1.ReferencedEntity, EntityFilters.Entity); if (Guid.TryParse(kv.Value, out gLookup)) { lookup = XrmCore.Retrieve(mto1.ReferencedEntity, gLookup, new ColumnSet(mto1Meta.PrimaryIdAttribute)); } else { if (!string.IsNullOrEmpty(kv.Value)) { lookup = XrmCore.RetrieveByAttribute(mto1.ReferencedEntity, mto1Meta.PrimaryNameAttribute, kv.Value, new ColumnSet(mto1Meta.PrimaryIdAttribute)).Entities.FirstOrDefault(); } } if (!string.IsNullOrEmpty(kv.Value) && lookup == null && att.AttributeType.Value == AttributeTypeCode.Lookup) { lookup = new Entity(mto1Meta.LogicalName, Guid.NewGuid()); lookup[mto1Meta.PrimaryNameAttribute] = kv.Value; lookup.Id = XrmCore.CreateEntity(lookup); } if (lookup != null) { entity.SetAttributeValue(kv.Key, lookup.ToEntityReference()); } break; case AttributeTypeCode.Memo: case AttributeTypeCode.String: setting = settings.GetValueOrDefault <string>(kv.Key + "_appendformat", ""); if (!string.IsNullOrEmpty(setting)) { entity.SetAttributeValue(att.LogicalName, (entity.GetAttributeValue <string>(att.LogicalName) ?? "") + string.Format(setting, kv.Value)); } else { entity.SetAttributeValue(att.LogicalName, kv.Value); } break; case AttributeTypeCode.Owner: Guid g; if (Guid.TryParse(kv.Value, out g)) { entity.SetAttributeValue(kv.Key, new EntityReference("systemuser", g)); } else { Entity owner = XrmCore.RetrieveByAttribute("systemuser", "fullname", kv.Value, new ColumnSet("systemuserid")).Entities.FirstOrDefault(); if (owner == null) { throw new InvalidOperationException(string.Format("The system user '{0}' does not exist", kv.Value)); } entity.SetAttributeValue(kv.Key, owner.ToEntityReference()); } break; case AttributeTypeCode.Picklist: case AttributeTypeCode.State: case AttributeTypeCode.Status: int iOption; if (int.TryParse(kv.Value, out iOption)) { entity.SetAttributeValue(kv.Key, new OptionSetValue(iOption)); } else { OptionMetadata opMeta = null; if (att.AttributeType.Value == AttributeTypeCode.Picklist) { opMeta = (att as PicklistAttributeMetadata).OptionSet.Options.FirstOrDefault(x => x.Label.LocalizedLabels.Any(lab => lab.Label.Equals(kv.Value, StringComparison.OrdinalIgnoreCase)) || x.Label.UserLocalizedLabel.Label.Equals(kv.Value, StringComparison.OrdinalIgnoreCase)); } else if (att.AttributeType.Value == AttributeTypeCode.State) { opMeta = (att as StateAttributeMetadata).OptionSet.Options.FirstOrDefault(x => x.Label.LocalizedLabels.Any(lab => lab.Label.Equals(kv.Value, StringComparison.OrdinalIgnoreCase)) || x.Label.UserLocalizedLabel.Label.Equals(kv.Value, StringComparison.OrdinalIgnoreCase)); } else if (att.AttributeType.Value == AttributeTypeCode.Status) { opMeta = (att as StatusAttributeMetadata).OptionSet.Options.FirstOrDefault(x => x.Label.LocalizedLabels.Any(lab => lab.Label.Equals(kv.Value, StringComparison.OrdinalIgnoreCase)) || x.Label.UserLocalizedLabel.Label.Equals(kv.Value, StringComparison.OrdinalIgnoreCase)); } if (opMeta == null) { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } else { entity.SetAttributeValue(kv.Key, opMeta.Value.Value); } } break; case AttributeTypeCode.Uniqueidentifier: if (Guid.TryParse(kv.Value, out g)) { entity.SetAttributeValue(kv.Key, g); } else { throw new InvalidOperationException(string.Format("The {2} attribute '{0}' contains an invalid value of {1}", kv.Key, kv.Value, att.AttributeType.Value.ToString())); } break; case AttributeTypeCode.PartyList: case AttributeTypeCode.CalendarRules: case AttributeTypeCode.Virtual: case AttributeTypeCode.ManagedProperty: case AttributeTypeCode.EntityName: throw new NotImplementedException(string.Format("The attribute type {0} is not supported", att.AttributeType.Value.ToString())); default: break; } }