private List<XmlAttribute> GetLookupAttributes(LookupAttributeMetadata lookupMeta)
        {
            // Need to use this to add additional attribute fields to ComplexType definition that contains complex types.
            List<XmlAttribute> attribs = new List<XmlAttribute>();
            XmlDocument doc = new XmlDocument();
            XmlAttribute typeAttrib = doc.CreateAttribute(CRM2011AdapterUtilities.LookupType);
            XmlAttribute fieldAttrib = doc.CreateAttribute(CRM2011AdapterUtilities.LookupField);
            if (lookupMeta.Targets.Length > 0)
            {
                string[] types = lookupMeta.Targets;

                for (int i = 0; i < types.Count(); i++)
                {
                    typeAttrib.Value += types[i];

                    if (types[i].Equals("transactioncurrency"))
                    {
                        fieldAttrib.Value += "isocurrencycode";
                    }
                    else if (types[i].Equals("systemuser"))
                    {
                        // Things like systemuser should be modified to utilize a different value captured in the config utility.
                        // thereby allowing the user to select the matching field prior to having the config created and
                        // requiring manual modifications later.
                        fieldAttrib.Value += "fullname";
                    }
                    else if (types[i].Equals("businessunit") || types[i].Equals("uom") || types[i].Equals("uomschedule"))
                    {
                        fieldAttrib.Value += "name";
                    }
                    else if (types.Last().Equals("activitypointer"))
                    {
                        fieldAttrib.Value += "activityid";
                    }
                    else
                    {
                       var entityMetaDataRequest = new RetrieveEntityRequest()
                       {
                            LogicalName = types[i].ToString(),
                            EntityFilters = EntityFilters.Entity
                       };

                       var entityMetaDataResponse = this.InstallAdapter.OrganizationService.Execute(entityMetaDataRequest) as RetrieveEntityResponse;

                        if (entityMetaDataResponse != null)
                        {
                            fieldAttrib.Value += entityMetaDataResponse.EntityMetadata.PrimaryIdAttribute;
                        }
                        else
                        {
                            fieldAttrib.Value += types[i] + "id";
                        }
                    }

                    if (types.Count() > 0 && i < types.Count() - 1)
                    {
                        typeAttrib.Value += ",";
                        fieldAttrib.Value += ",";
                    }

                    if (string.CompareOrdinal(typeAttrib.Value, "systemuser") == 0)
                    {
                        XmlAttribute skipValidation = doc.CreateAttribute(CRM2011AdapterUtilities.ReferenceValidationSkip);
                        skipValidation.Value = true.ToString(CultureInfo.InvariantCulture).ToUpperInvariant();
                        attribs.Add(skipValidation);
                    }
                }

                attribs.Add(typeAttrib);
                attribs.Add(fieldAttrib);
            }

            return attribs;
        }
示例#2
0
        private static EntityMetadata LoadEntityMetadata(string entityLogicalName)
        {
            string cacheKey = entityLogicalName;
            EntityMetadata metaData = (EntityMetadata)_entityMetaData[cacheKey];

            if (metaData == null)
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest();
                request.EntityFilters = EntityFilters.Entity;
                request.LogicalName = entityLogicalName;
                request.RetrieveAsIfPublished = true;
                request.MetadataId = new Guid("00000000-0000-0000-0000-000000000000");

                RetrieveEntityResponse response = (RetrieveEntityResponse)OrganizationServiceProxy.Execute(request);
                metaData = response.EntityMetadata;
                _entityMetaData[cacheKey] = metaData;
            }
            return metaData;
        }
        private List<ObjectProvider> GetObjectProviders()
        {
            if (this.InstallAdapter.MetadataTimestamp != this.InstallAdapter.RetrieveMetadataTimestamp())
            {
                List<ObjectProvider> MtoMAvailableProviders = new List<ObjectProvider>();

                this.availableProviders = new List<ObjectProvider>();
                RetrieveAllEntitiesRequest retrieveAll = new RetrieveAllEntitiesRequest();
                RetrieveAllEntitiesResponse response = new RetrieveAllEntitiesResponse();
                RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();

                this.PublishPreConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.StartRetrievingEntityMetadata));
                response = this.InstallAdapter.OrganizationService.Execute(retrieveAll) as RetrieveAllEntitiesResponse;
                foreach (EntityMetadata crmMetadata in response.EntityMetadata)
                {
                    entityRequest.MetadataId = crmMetadata.MetadataId.Value;
                    entityRequest.EntityFilters = EntityFilters.Relationships;
                    RetrieveEntityResponse entityResponse = this.InstallAdapter.OrganizationService.Execute(entityRequest) as RetrieveEntityResponse;
                    if (entityResponse.EntityMetadata.DisplayName.LocalizedLabels.Count > 0 && !entityResponse.EntityMetadata.LogicalName.StartsWith("dynamics_deleted", StringComparison.OrdinalIgnoreCase) && entityResponse.EntityMetadata.IsCustomizable.Value)
                    {
                        this.availableProviders.Add(new DynamicObjectProvider() { Adapter = this.InstallAdapter, Id = crmMetadata.MetadataId.Value, DisplayName = entityResponse.EntityMetadata.DisplayName.LocalizedLabels[0].Label, Name = entityResponse.EntityMetadata.LogicalName });
                    }

                    List<ManyToManyRelationshipMetadata> entityMToMRelationships = (from meta in entityResponse.EntityMetadata.ManyToManyRelationships
                                                                                         where (meta.IsCustomRelationship.Value == true)
                                                                                         || (meta.SecurityTypes == SecurityTypes.ParentChild && meta.IsCustomRelationship.Value == false)
                                                                                         select meta).ToList();
                    if (entityMToMRelationships.Count > 0)
                    {
                        foreach (ManyToManyRelationshipMetadata relation in entityMToMRelationships)
                        {
                            if (!MtoMAvailableProviders.Any(f => f.DisplayName == relation.SchemaName))
                            {
                                MtoMAvailableProviders.Add(new DynamicObjectProvider() { Adapter = this.InstallAdapter, Id = relation.MetadataId.Value, DisplayName = relation.SchemaName, Name = relation.SchemaName + ",Relationship" });
                            }
                        }
                    }
                }

                foreach (ObjectProvider relationObjectProvider in MtoMAvailableProviders)
                {
                    this.availableProviders.Add(relationObjectProvider);
                }

                this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.FinishedRetreivingEntityMetadata));
                this.InstallAdapter.MetadataTimestamp = this.InstallAdapter.RetrieveMetadataTimestamp();
                this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.MetadataTimeStamp, this.InstallAdapter.MetadataTimestamp));
            }

            return this.availableProviders;
        }
        private void FillObjectDef(ObjectDefinition objDef)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest() { LogicalName = objDef.RootDefinition.TypeName, EntityFilters = EntityFilters.Attributes | EntityFilters.Relationships, RetrieveAsIfPublished = true };
            RetrieveEntityResponse response = this.InstallAdapter.OrganizationService.Execute(request) as RetrieveEntityResponse;

            this.GenerateObjectDefinitionEntries(objDef, response, objDef.RootDefinition.TypeName);
            List<OneToManyRelationshipMetadata> parentChildRelationships = (from meta in response.EntityMetadata.OneToManyRelationships
                                                                            where (meta.CascadeConfiguration.Reparent.Value == CascadeType.NoCascade && meta.IsCustomRelationship.Value == true)
                                                                            || (meta.SecurityTypes == SecurityTypes.ParentChild && meta.IsCustomRelationship.Value == false)
                                                                            || meta.ReferencingEntity == "customeraddress"
                                                                            select meta).ToList();

            foreach (OneToManyRelationshipMetadata relation in parentChildRelationships)
            {
                if (!(relation.ReferencedEntity == "account" || relation.ReferencedEntity == "contact"))
                {
                    TypeDefinition typeDef = new CollectionType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>[]), Name = relation.SchemaName };
                    FieldDefinition tempDef = new FieldDefinition() { Name = relation.SchemaName, DisplayName = typeDef.Name.Replace('_', ' '), TypeDefinition = typeDef, TypeName = typeDef.ClrTypeName };
                    if ("salesorder_details" != tempDef.Name && "invoice_details" != tempDef.Name && "price_level_product_price_levels" != tempDef.Name)
                    {
                        AddTypes(objDef, tempDef, typeDef, objDef.RootInstance.Name);
                        FieldDefinition itemDef = new FieldDefinition() { Name = "item", DisplayName = relation.SchemaName.Replace('_', ' ').TrimEnd('s'), TypeName = relation.ReferencingEntity };
                        ((CollectionType)typeDef).Item = itemDef;
                        if (objDef.Types.Find(f => f.Name.ToUpperInvariant() == relation.ReferencingEntity.ToUpperInvariant()) == null)
                        {
                            objDef.Types.Add(new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = relation.ReferencingEntity });
                        }
                    }
                }

                request = new RetrieveEntityRequest() { EntityFilters = EntityFilters.All, LogicalName = relation.ReferencingEntity, RetrieveAsIfPublished = true };
                response = this.InstallAdapter.OrganizationService.Execute(request) as RetrieveEntityResponse;

                this.GenerateObjectDefinitionEntries(objDef, response, relation.ReferencingEntity);
                XmlDocument doc = new XmlDocument();
                XmlAttribute parentAttrib = doc.CreateAttribute(CRM2011AdapterUtilities.IsParentField);
                parentAttrib.Value = true.ToString(CultureInfo.InvariantCulture).ToUpperInvariant();
                var referencingType = objDef.Types.SingleOrDefault(t => t.Name == relation.ReferencingEntity);
                if (referencingType != null)
                {
                    var fieldDef = referencingType.Children.SingleOrDefault(field => field.Name == relation.ReferencingAttribute);
                    if (fieldDef != null)
                    {
                        // Add the parent attribute to the additional attributes array
                        List<XmlAttribute> attribs = fieldDef.AdditionalAttributes != null ? fieldDef.AdditionalAttributes.ToList() : new List<XmlAttribute>();
                        var existingAttrib = attribs.FirstOrDefault(att => att.Name == parentAttrib.Name);
                        if (existingAttrib == null)
                        {
                            attribs.Add(parentAttrib);
                            fieldDef.AdditionalAttributes = attribs.ToArray();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Read an <c>object</c> from the stream
        /// </summary>
        /// <param name="key">The key for the <c>object</c> to be read</param>
        /// <returns>An instance of the <c>object</c> provided by this <c>ObjectProvider</c> that has the key provided</returns>
        public object ReadObject(object key)
        {
            if (key == null || key.GetType() != typeof(Guid))
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.SuppliedKeyTypeExceptionMessage), new ArgumentException(Resources.SuppliedKeyTypeExceptionMessage, "key")) { ExceptionId = ErrorCodes.SuppliedKeyCastException };
            }

            Guid metaKey = (Guid)key;

            // Will throw exception if the GUID is not related to a Entity but rather to a global option set.
            try
            {
                RetrieveEntityRequest entityRequest = new RetrieveEntityRequest() { EntityFilters = EntityFilters.Attributes, MetadataId = metaKey, RetrieveAsIfPublished = true };
                RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)this.CallMetadataExecuteWebMethod(entityRequest);
                var anyPicklist = entityResponse.EntityMetadata.Attributes.Where(x => x.AttributeType == AttributeTypeCode.Picklist);

                if (anyPicklist.Count() > 0)
                {
                    Dictionary<string, object> parentDictionary = new Dictionary<string, object>();
                    Dictionary<string, object> childDictionary = new Dictionary<string, object>();

                    foreach (var attributeMeta in anyPicklist)
                    {
                        var picklistMeta = attributeMeta as PicklistAttributeMetadata;
                        if (picklistMeta.OptionSet.IsGlobal.Value != true)
                        {
                            var options = new List<string>();
                            foreach (var option in picklistMeta.OptionSet.Options)
                            {
                                if (option.Label.LocalizedLabels.Count > 0)
                                {
                                    options.Add(option.Label.LocalizedLabels[0].Label);
                                }
                            }

                            childDictionary.Add(attributeMeta.LogicalName, options.ToArray<string>());
                        }
                    }

                    parentDictionary.Add(entityResponse.EntityMetadata.DisplayName.LocalizedLabels[0].Label.Replace(" ", string.Empty), childDictionary);

                    return parentDictionary;
                }
                else
                {
                    return null;
                }
            }
            catch (AdapterException)
            {
                var optionSetMetaRequest = new RetrieveOptionSetRequest() { MetadataId = metaKey };
                var optionSetMetaResponse = (RetrieveOptionSetResponse)this.CallMetadataExecuteWebMethod(optionSetMetaRequest);
                var optionSetMeta = (OptionSetMetadata)optionSetMetaResponse.OptionSetMetadata;
                var metaOptions = optionSetMeta.Options;

                var options = new List<string>();

                foreach (var option in metaOptions)
                {
                    options.Add(option.Label.LocalizedLabels[0].Label);
                }

                Dictionary<string, object> optionSet = new Dictionary<string, object>();
                optionSet.Add(optionSetMeta.Name, options.ToArray<string>());
                return optionSet;
            }
        }