예제 #1
0
        public static Profile GetProfile(string ProfileName)
        {
            FilterExpression filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition(new ConditionExpression("appl_name", ConditionOperator.Equal, ProfileName));
            EntityCollection col = XrmCore.RetrieveByFilter("appl_profiledefinition", filter);

            if (col.Entities.Count != 1)
            {
                throw new Exception(string.Format("There are {0} profiles with the name {1}. 1 was expected", col.Entities.Count, ProfileName));
            }

            Guid ProfileDefinitionId = col.Entities.First().GetAttributeValue <Guid>("appl_profiledefinitionid");

            using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(XrmConnection.Connection))
            {
                IQueryable <Entity> query = from field in service.CreateQuery("appl_profilefield")
                                            join related in service.CreateQuery("appl_profilefield_appl_profiledefinitio") on field["appl_profilefieldid"] equals related["appl_profilefieldid"]
                                            join profiledef in service.CreateQuery("appl_profiledefinition") on related["appl_profiledefinitionid"] equals profiledef["appl_profiledefinitionid"]
                                            where (string)profiledef["appl_name"] == ProfileName
                                            select field;

                return(Profile.Factory(new EntityCollection(query.ToList()), ProfileDefinitionId));
            }
        }
예제 #2
0
        public static Guid CreateLead(string subject, string description, string firstName, string lastName, string companyName, string email, NameValueCollection otherFields, CrmConnection connection = null)
        {
            Entity lead = new Entity("lead", Guid.NewGuid());

            if (!string.IsNullOrEmpty(email))
            {
                lead["emailaddress1"] = email;
                EntityCollection contacts = XrmCore.RetrieveByAttribute("contact", "emailaddress1", email);
                if (contacts.Entities.Count > 0)
                {
                    Entity contact = contacts.Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).First();
                    lead["contactid"] = contact.ToEntityReference();
                    if (contact.Contains("accountid"))
                    {
                        lead["accountid"] = contact.GetAttributeValue <EntityReference>("accountid");
                    }
                }
            }
            lead["subject"]     = subject;
            lead["firstname"]   = firstName;
            lead["lastname"]    = lastName;
            lead["companyname"] = companyName;
            lead["description"] = description;

            if (otherFields != null && otherFields.Count > 0)
            {
                foreach (string key in otherFields.AllKeys)
                {
                    lead[key] = otherFields[key];
                }
            }

            return(XrmCore.CreateEntity(lead));
        }
예제 #3
0
        public static void AddToMarketingList(Guid[] listMembers, Guid listId)
        {
            AddListMembersListRequest request = new AddListMembersListRequest();

            request.MemberIds = listMembers;
            request.ListId    = listId;
            AddListMembersListResponse response = XrmCore.Execute <AddListMembersListRequest, AddListMembersListResponse>(request);
        }
예제 #4
0
        public static void RemoveFromMarketingList(Guid listMember, Guid listId)
        {
            RemoveMemberListRequest request = new RemoveMemberListRequest();

            request.EntityId = listMember;
            request.ListId   = listId;
            RemoveMemberListResponse response = XrmCore.Execute <RemoveMemberListRequest, RemoveMemberListResponse>(request);
        }
예제 #5
0
        public static bool UpdateUserProfile(UserProfile Profiles)
        {
            EntityCollection collection = new EntityCollection();

            collection.EntityName = "appl_membershipprofile";
            Profiles.Fields.ForEach(profile => collection.Entities.Add(profile.ToEntity()));
            return(XrmCore.BulkSave(collection));
        }
예제 #6
0
        public static Guid CreateLead(NameValueCollection formCollection)
        {
            string LeadId = formCollection.Get("leadid");
            Entity lead   = new Entity("lead", Guid.NewGuid());
            Guid   id     = Guid.Empty;

            if (!string.IsNullOrEmpty(LeadId) && Guid.TryParse(LeadId, out id))
            {
                lead = XrmCore.Retrieve("lead", id);
            }

            string Email = formCollection.Get("emailaddress1");

            if (!string.IsNullOrEmpty(Email))
            {
                EntityCollection contacts = XrmCore.RetrieveByAttribute("contact", "emailaddress1", Email);
                if (contacts.Entities.Count > 0)
                {
                    Entity contact = contacts.Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).First();
                    lead["contactid"] = contact.ToEntityReference();
                    if (contact.Contains("accountid"))
                    {
                        lead["accountid"] = contact.GetAttributeValue <EntityReference>("accountid");
                    }
                }
            }
            foreach (string key in formCollection.AllKeys.Except(new string[] { "leadid" }))
            {
                lead[key] = formCollection[key];
            }
            if (id.Equals(Guid.Empty))
            {
                id = XrmCore.CreateEntity(lead);
            }
            else
            {
                XrmCore.UpdateEntity(lead);
                id = lead.Id;
            }
            return(id);
        }
예제 #7
0
        private static EntityCollection GetUserProfiles(Guid ContactId, Guid?ProfileId)
        {
            if (ProfileId.HasValue)
            {
                OrganizationService srv = new OrganizationService(XrmConnection.Connection);
                using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv))
                {
                    IQueryable <Entity> query = from entity in service.CreateQuery("appl_membershipprofile")
                                                where (Guid)entity["appl_contactid"] == ContactId && (Guid)entity["appl_profiledefinitionid"] == ProfileId.Value
                                                select entity;

                    EntityCollection col = new EntityCollection(query.ToList());
                    col.EntityName = "appl_membershipprofile";
                    return(col);
                }
            }
            else
            {
                return(XrmCore.GetRelated(new Entity("contact", ContactId), "appl_membershipprofile", "appl_contactid", CacheResults: false));
            }
        }
예제 #8
0
        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);
        }
예제 #9
0
        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);
        }
예제 #10
0
        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;
            }
        }
예제 #11
0
        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;
            }
        }
예제 #12
0
        public static void ApplyAction(this Entity entity, KeyValuePair <string, string> action)
        {
            string[] actionArgs = action.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            switch (action.Key.ToUpper())
            {
            case "APPLYWORKFLOW":
                InputArgumentCollection workflowArgs = null;
                if (actionArgs.Length > 1)
                {
                    workflowArgs = new InputArgumentCollection();
                    for (int i = 1; i < actionArgs.Length; i++)
                    {
                        string[] workflowArg = actionArgs[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                        workflowArgs.Add(workflowArg[0], workflowArg[1]);
                    }
                }
                Guid g;
                if (Guid.TryParse(actionArgs[0], out g))
                {
                    XrmCore.ApplyWorkFlow(entity, g, workflowArgs);
                }
                else
                {
                    XrmCore.ApplyWorkFlow(entity, actionArgs[0], workflowArgs);
                }
                break;

            case "ADDTOMARKETINGLIST":
            case "REMOVEFROMMARKETINGLIST":
                bool remove = action.Key.Equals("REMOVEFROMMARKETINGLIST", StringComparison.OrdinalIgnoreCase);
                for (int i = 0; i < actionArgs.Length; i++)
                {
                    Entity list = XrmCore.RetrieveByAttribute("list", "listname", actionArgs[i], new ColumnSet("listid")).Entities.FirstOrDefault();
                    if (list == null)
                    {
                        throw new ArgumentException(string.Format("The Marketing list {0} could not be found", actionArgs[0]));
                    }
                    else
                    {
                        if (remove)
                        {
                            XrmMarketing.RemoveFromMarketingList(entity.Id, list.Id);
                        }
                        else
                        {
                            XrmMarketing.AddToMarketingList(new Guid[] { entity.Id }, list.Id);
                        }
                    }
                }
                break;

            case "ASSIGN":
                FilterExpression filter = new FilterExpression(LogicalOperator.Or);
                filter.AddCondition("fullname", ConditionOperator.Like, new object[] { actionArgs[0] });
                filter.AddCondition("internalemailaddress", ConditionOperator.Like, new object[] { actionArgs[0] });
                Entity owner = XrmCore.RetrieveByFilter("systemuser", filter, new ColumnSet("systemuserid")).Entities.FirstOrDefault();
                if (owner == null)
                {
                    throw new ArgumentException(string.Format("The System user with the name or email {0} could not be found", actionArgs[0]));
                }
                else
                {
                    AssignRequest request = new AssignRequest()
                    {
                        Assignee = owner.ToEntityReference(),
                        Target   = entity.ToEntityReference()
                    };
                    XrmCore.Execute <AssignRequest, AssignResponse>(request);
                }
                break;

            default:
                break;
            }
        }