/// <summary>
        /// Gets the option sets.
        /// </summary>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <returns>Result.</returns>
        public Result GetOptionSets(string entityName, string attributeName)
        {
            try
            {
                logSystem.CreateLog(System.Reflection.MethodBase.GetCurrentMethod().ToString() + " is called");

                string AttributeName     = attributeName;
                string EntityLogicalName = entityName;
                RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName   = EntityLogicalName
                };
                RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)xrmService.Execute(retrieveDetails);
                Microsoft.Xrm.Sdk.Metadata.EntityMetadata            metadata         = retrieveEntityResponseObj.EntityMetadata;
                Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
                                                                                                                               (attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;

                foreach (OptionMetadata item in picklistMetadata.OptionSet.Options)
                {
                    ObjectCarrier.SetValue(item.Value.ToString(), item.Label.UserLocalizedLabel.Label);
                }

                return(new Result(false, string.Empty, ObjectCarrier.GetAllValues(), logSystem));
            }
            catch (Exception ex)
            {
                return(new Result(true,
                                  MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex),
                                  null, logSystem));
            }
        }
        public static EntityReference RetrieveWorkflowRecordOwner(IWorkflowContext workflowContext, IOrganizationService service)
        {
            EntityReference       recordOwner = null;
            RetrieveEntityRequest request     = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
                LogicalName   = workflowContext.PrimaryEntityName
            };

            RetrieveEntityResponse  metadataResponse = service.Execute(request) as RetrieveEntityResponse;
            LookupAttributeMetadata ownerAttribute   = metadataResponse.EntityMetadata.Attributes.FirstOrDefault(att => att.AttributeType != null && (int)att.AttributeType.Value == 9) as LookupAttributeMetadata;

            if (ownerAttribute != null)
            {
                Entity entity = workflowContext.PostEntityImages.Values.FirstOrDefault();
                if (entity == null)
                {
                    entity = workflowContext.PreEntityImages.Values.FirstOrDefault();
                    if (entity == null)
                    {
                        entity = service.Retrieve(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId, new ColumnSet(ownerAttribute.LogicalName));
                    }
                }

                if (entity != null && entity.Contains(ownerAttribute.LogicalName))
                {
                    recordOwner = entity[ownerAttribute.LogicalName] as EntityReference;
                }
            }

            return(recordOwner);
        }
        /// <summary>
        /// Gets the option set text.
        /// </summary>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <param name="optionSetValue">The option set value.</param>
        /// <returns>Result.</returns>
        public Result GetOptionSetText(string entityName, string attributeName, int?optionSetValue)
        {
            try
            {
                logSystem.CreateLog(System.Reflection.MethodBase.GetCurrentMethod().ToString() + " is called");

                string AttributeName     = attributeName;
                string EntityLogicalName = entityName;
                RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName   = EntityLogicalName
                };
                RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)xrmService.Execute(retrieveDetails);
                Microsoft.Xrm.Sdk.Metadata.EntityMetadata            metadata         = retrieveEntityResponseObj.EntityMetadata;
                Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
                                                                                                                               (attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
                Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
                IList <OptionMetadata> OptionsList = (from o in options.Options
                                                      where o.Value.Value == optionSetValue
                                                      select o).ToList();
                string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
                return(new Result(false, string.Empty, optionsetLabel, logSystem));
            }
            catch (Exception ex)
            {
                return(new Result(true,
                                  MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex),
                                  null, logSystem));
            }
        }
        public void GetAttributeDotNetTypeManagedProperty()
        {
            string entityName    = "contactadntManagedProperty";
            string attributeName = "contactadntManagedProperty";

            var attributeMetaDataItem = new AttributeMetadata {
                LogicalName = attributeName
            };

            SetFieldValue(attributeMetaDataItem, "_attributeType", AttributeTypeCode.ManagedProperty);

            var attributes = new List <AttributeMetadata> {
                attributeMetaDataItem
            };

            RetrieveEntityResponse response = InjectMetaDataToResponse(new RetrieveEntityResponse(), attributes);

            MockOrganizationService.Setup(a => a.Execute(It.IsAny <OrganizationRequest>())).Returns(response);
            Type actual = null;

            FluentActions.Invoking(() => actual = systemUnderTest.GetAttributeDotNetType(entityName, attributeName))
            .Should()
            .Throw <ValidationException>();

            MockOrganizationService.VerifyAll();
        }
Пример #5
0
        private void AddOrUpdateCRMEntityWithDataStructure(IOrganizationService serviceProxy, string crmEntityName, SimpleFlowStructure simpleFlowStructure)
        {
            RetrieveEntityResponse crmEntity = GetEntityInformationFromCRMClient(serviceProxy, crmEntityName);

            if (crmEntity != null)
            {
                log.Info("CRM entity fetched successfully from server");
                List <AttributeMetadata>         entityAttributes = crmEntity.EntityMetadata.Attributes.Where(t => t.IsValidForCreate == true).ToList();
                List <CRMEntityField>            entityFields;
                List <DefinedDataTypeDataMember> memberList;

                GetEntityFieldsFromCRMEntityAttributes(entityAttributes, crmEntityName, out entityFields, out memberList);

                simpleFlowStructure.Children = memberList.ToArray();
                CRMEntityFields = entityFields.ToArray();
                string displayName;
                if (crmEntity.EntityMetadata.DisplayName.LocalizedLabels != null && crmEntity.EntityMetadata.DisplayName.LocalizedLabels.Count > 0)
                {
                    displayName = crmEntity.EntityMetadata.DisplayName.LocalizedLabels[0].Label;
                }
                else
                {
                    displayName = crmEntity.EntityMetadata.LogicalName;
                }
                CRMEntityDisplayName = displayName;
                DataStructureService.Instance.AddDataStructure(UserContextHolder.GetRootUserContext(), simpleFlowStructure);
                log.Info(string.Format("Entity with name {0} added successfully to the database", crmEntityName));
            }
        }
Пример #6
0
        /// <summary>
        /// Retrieve Metadata properties based on RetrieveEntityRequest
        /// </summary>
        /// <param name="entityName">Entity Logical Name</param>
        /// <param name="attributes">String Attributes[]</param>
        /// <returns></returns>
        private List <AttributeCardModel> RetrieveAttributes(string entityName, string[] attributes)
        {
            List <AttributeCardModel> attributeCards = new List <AttributeCardModel>();

            RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest()
            {
                LogicalName           = entityName,
                EntityFilters         = EntityFilters.Attributes,
                RetrieveAsIfPublished = true
            };

            RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)ServiceAdmin.Execute(retrieveEntityRequest);
            EntityMetadata         entityMetadata         = retrieveEntityResponse.EntityMetadata;

            foreach (var attributeMetadata_ in entityMetadata.Attributes)
            {
                var attributeMetadata = (AttributeMetadata)attributeMetadata_;
                var match             = attributes.Where(w => w.Equals(attributeMetadata.LogicalName)).FirstOrDefault();
                if (!String.IsNullOrEmpty(match))
                {
                    attributeCards.Add(attributeMetadata.ToCard());
                }
            }

            return(attributeCards);
        }
        public void ExternalLookup_Data()
        {
            // Verify that a lookup external to schema doesn't add anything.
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);
            Entity AccountWithExternalLookup = new Entity("account", Guid.NewGuid());

            AccountWithExternalLookup["createdby"] = new EntityReference("systemuser", Guid.NewGuid());

            fakedContext.Initialize(AccountWithExternalLookup);
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata         = fakedContext.GetEntityMetadataByName(SupportMethods.AccountLogicalName);
                entityMetadata.DisplayName = new Label(SupportMethods.AccountDisplayName, 1033);

                var response = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };
                return(response);
            });

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData("<fetch><entity name='account'><attribute name='accountid'/><attribute name='createdby'/></entity></fetch>");

            Assert.IsTrue(DataBuilder.BuildDataXML().SelectSingleNode("entities/entity[@name='contact']") == null);
        }
Пример #8
0
        private List <OptionalValue> GetOptionSet(string entityName, string fieldName, IOrganizationService service)
        {
            RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest();

            retrieveDetails.EntityFilters = EntityFilters.All;
            retrieveDetails.LogicalName   = entityName;

            RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
            EntityMetadata         metadata = retrieveEntityResponseObj.EntityMetadata;
            var attribiuteMetadata          = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, fieldName, StringComparison.OrdinalIgnoreCase));

            if (attribiuteMetadata == null)
            {
                return(new List <OptionalValue>());
            }
            EnumAttributeMetadata picklistMetadata = attribiuteMetadata as EnumAttributeMetadata;
            OptionSetMetadata     options          = picklistMetadata.OptionSet;

            return((from o in options.Options
                    select new OptionalValue
            {
                Value = o.Value,
                Text = o.Label.UserLocalizedLabel.Label
            }).ToList());
        }
        internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef)
        {
            var request = MakeRequest <RetrieveEntityRequest>(orgRequest);

            if (request.LogicalName == null && request.MetadataId == Guid.Empty)
            {
                throw new FaultException("Entity logical name is required when MetadataId is not specified");
            }

            EntityMetadata entityMetadata = null;

            if (request.LogicalName != null && metadata.EntityMetadata.ContainsKey(request.LogicalName))
            {
                entityMetadata = metadata.EntityMetadata[request.LogicalName];
            }
            else if (request.MetadataId != Guid.Empty)
            {
                entityMetadata = metadata.EntityMetadata.FirstOrDefault(x => x.Value.MetadataId == request.MetadataId).Value;
            }
            else
            {
                throw new FaultException($"Could not find entity with logicalname {request.LogicalName} or metadataid {request.MetadataId}");
            }

            var resp = new RetrieveEntityResponse();

            resp.Results["EntityMetadata"] = entityMetadata;
            return(resp);
        }
Пример #10
0
        public void GetDisplayNameAndLogicalNameOfFields(string selectedEntityName)
        {
            // Create the request
            RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();

            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            // entityRequest.RetrieveAsIfPublished = false;
            entityRequest.LogicalName   = selectedEntityName;
            entityRequest.EntityFilters = EntityFilters.Entity;
            entityRequest.EntityFilters = EntityFilters.Attributes;


            // Execute the request
            RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest);

            // Access the retrieved entity
            EntityMetadata retrievedEntityMetadata       = entityResponse.EntityMetadata;
            List <EntitiyFieldNameModel> entityFieldList = new List <EntitiyFieldNameModel>();

            //get the display name

            foreach (var attribute in retrievedEntityMetadata.Attributes)
            {
                entityFieldList.Add(new EntitiyFieldNameModel {
                    FieldName = attribute.DisplayName.UserLocalizedLabel != null ? attribute.DisplayName.UserLocalizedLabel.Label : "Field name not found", Value = attribute.LogicalName
                });
            }
        }
Пример #11
0
        public void AppendDataUsingDictionariesLikePowerShell_Works()
        {
            // StringType           description                        knowledgearticle
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);
            fakedContext.Initialize(SupportMethods.GetStringTypeEntity());
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata         = fakedContext.GetEntityMetadataByName(SupportMethods.KnowledgeArticleLogicalName);
                entityMetadata.DisplayName = new Label(SupportMethods.KnowledgeArticleDisplayName, 1033);
                var response = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };
                return(response);
            });

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData(SupportMethods.KnowledgeArticleLogicalName, SupportMethods.GetStringTypePowerShellObjects());
            Assert.AreEqual(
                DataBuilder.BuildDataXML().InnerXml,
                SupportMethods.GetStringTypeExpectedData());
        }
        /// <summary>
        /// retrieves the entity type code for the specified entity name
        /// </summary>
        /// <param name="entityName">name of the entity</param>
        /// <param name="service">target organization service</param>
        /// <returns>entity type code</returns>
        private static int GetTypeCode(string entityName, IOrganizationService service, out string errorMessage)
        {
            errorMessage = null;

            // save as static collection to avoid round trips
            if (_objectTypeCodes == null)
            {
                _objectTypeCodes = new Dictionary <string, int>();
            }

            if (!_objectTypeCodes.ContainsKey(entityName))
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest();
                request.LogicalName = entityName;

                // Retrieve the MetaData, OTC for the entity name
                // cheesy... catch the exception if the ETN is not found
                try {
                    RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
                    _objectTypeCodes.Add(entityName, response.EntityMetadata.ObjectTypeCode.Value);
                }
                catch {
                    errorMessage = $"Error occurred locating Entity Type {entityName} on the current instance";
                    return(-1);
                }
            }
            return(_objectTypeCodes[entityName]);
        }
Пример #13
0
        public string GetLogicalSetName(string LogicalName, IOrganizationService service)
        {
            try
            {
                if (!string.IsNullOrEmpty(LogicalName))
                {
                    RetrieveEntityRequest retrieveRecordMetadataRequest = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.Entity,
                        LogicalName   = LogicalName
                    };
                    RetrieveEntityResponse retrieveRecordMetadataResponse = (RetrieveEntityResponse)service.Execute(retrieveRecordMetadataRequest);
                    EntityMetadata         recordMetadata = retrieveRecordMetadataResponse.EntityMetadata;

                    return(recordMetadata.CollectionSchemaName.ToLower());
                }
                else
                {
                    return("");
                }
            }
            catch (Exception)
            {
                return("Please Enter correct logical name in ActivityPartyEntityLogicalName property");
            }
        }
Пример #14
0
        public static Dictionary <AttributeTypeCode, List <entityParam> > getEntityFields(IOrganizationService service, String entityTechnicalName, String entityName, BackgroundWorker worker)
        {
            entityInfo = new EntityInfo();
            _data      = new Dictionary <AttributeTypeCode, List <entityParam> >();
            RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters         = EntityFilters.All,
                LogicalName           = entityTechnicalName,
                RetrieveAsIfPublished = true
            };

            worker.ReportProgress(0, "Retrieving Entity MetaData...");
            RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveBankAccountEntityRequest);

            formatList(retrieveEntityResponse, _data);

            getEntityRecords(service, worker, _data, entityTechnicalName, entityInfo);

            worker.ReportProgress(0, "Analysing ...");
            entityInfo.entityName           = entityName;
            entityInfo.entityTechnicalName  = entityTechnicalName;
            entityInfo.entityDateOfCreation = retrieveEntityResponse.EntityMetadata.CreatedOn != null ? (DateTime)retrieveEntityResponse.EntityMetadata.CreatedOn.Value.Date : DateTime.MinValue.Date;

            return(CalculatePercentageOfUse(entityInfo.entityRecordsCount, _data));
        }
Пример #15
0
        public void UniqueidentifierType()
        {
            // UniqueidentifierType stageid                            knowledgearticle
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);
            fakedContext.Initialize(SupportMethods.GetUniqueIdentifierTypeEntity());
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata         = fakedContext.GetEntityMetadataByName(SupportMethods.KnowledgeArticleLogicalName);
                entityMetadata.DisplayName = new Label(SupportMethods.KnowledgeArticleDisplayName, 1033);
                entityMetadata.Attributes.First(a => a.LogicalName == "stageid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Uniqueidentifier);

                var response = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };
                return(response);
            });

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData(SupportMethods.GetUniqueIdentifierTypeFetch());
            Assert.AreEqual(
                DataBuilder.BuildDataXML().InnerXml,
                SupportMethods.GetUniqueIdentifierTypeExpectedData());
        }
        public void GetAttribute()
        {
            string entityName    = "contactatt";
            string attributeName = "contactattid";

            AttributeMetadata attributeMetaDataItem = new AttributeMetadata
            {
                LogicalName = attributeName
            };

            var attributes = new List <AttributeMetadata>
            {
                attributeMetaDataItem
            };

            RetrieveEntityResponse response = InjectMetaDataToResponse(new RetrieveEntityResponse(), attributes);

            MockOrganizationService.Setup(a => a.Execute(It.IsAny <OrganizationRequest>())).Returns(response);

            AttributeMetadata actual = null;

            FluentActions.Invoking(() => actual = systemUnderTest.GetAttribute(entityName, attributeName))
            .Should()
            .NotThrow();

            MockOrganizationService.VerifyAll();

            actual.LogicalName.Should().Be(attributeName);
        }
Пример #17
0
        private void SetupMetadataHandlersForAccount(Mock <IOrganizationService> orgSvc)
        {
            EntityMetadata entityMetadata = new EntityMetadata();

            entityMetadata.LogicalName   = "account";
            entityMetadata.SchemaName    = "account";
            entityMetadata.EntitySetName = "accounts";
            entityMetadata.DisplayName   = new Label("Account", 1033);
            entityMetadata.DisplayName.UserLocalizedLabel           = new LocalizedLabel("Account", 1033);
            entityMetadata.DisplayCollectionName                    = new Label("Accounts", 1033);
            entityMetadata.DisplayCollectionName.UserLocalizedLabel = new LocalizedLabel("Accounts", 1033);
            System.Reflection.PropertyInfo proInfo = entityMetadata.GetType().GetProperty("ObjectTypeCode");
            if (proInfo != null)
            {
                proInfo.SetValue(entityMetadata, 1, null);
            }

            RetrieveEntityResponse retrieveEntityResponse = new RetrieveEntityResponse();

            retrieveEntityResponse.Results.Add("EntityMetadata", entityMetadata);

            List <EntityMetadata> entities = new List <EntityMetadata>();

            entities.Add(entityMetadata);

            RetrieveAllEntitiesResponse retrieveAllEntitiesResponse = new RetrieveAllEntitiesResponse();

            retrieveAllEntitiesResponse.Results.Add("EntityMetadata", entities.ToArray());

            orgSvc.Setup(f => f.Execute(It.IsAny <RetrieveEntityRequest>())).Returns(retrieveEntityResponse);
            orgSvc.Setup(f => f.Execute(It.IsAny <RetrieveAllEntitiesRequest>())).Returns(retrieveAllEntitiesResponse);
        }
Пример #18
0
        /// <summary>
        /// Creates a new instance of the Dynamics365Entity class from an entity with the specified logical name in the specified Dynamics instance.
        /// </summary>
        /// <param name="logicalName"></param>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static Dynamics365Entity Create(string logicalName, Dynamics365Connection connection)
        {
            ConnectionCache   cache    = new ConnectionCache(connection);
            string            cacheKey = string.Format("GetEntity:{0}", logicalName);
            Dynamics365Entity entity   = (Dynamics365Entity)cache[cacheKey];

            if (entity == null)
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest()
                {
                    LogicalName           = logicalName,
                    EntityFilters         = EntityFilters.Attributes,
                    RetrieveAsIfPublished = false
                };

                using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy)
                {
                    RetrieveEntityResponse response = (RetrieveEntityResponse)proxy.Execute(request);
                    entity = CreateFromMetadata(response.EntityMetadata, connection, true);
                }

                cache[cacheKey] = entity;
            }

            return(entity);
        }
Пример #19
0
        public EntityMetadata GetEntityMetadata(Dynamics365Connection connection)
        {
            ConnectionCache cache          = new ConnectionCache(connection);
            string          cacheKey       = string.Format("GetEntityMetadata:{0}", LogicalName);
            EntityMetadata  entityMetadata = (EntityMetadata)cache[cacheKey];

            if (entityMetadata == default(EntityMetadata))
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest()
                {
                    EntityFilters         = EntityFilters.Attributes,
                    LogicalName           = LogicalName,
                    RetrieveAsIfPublished = true
                };

                using (OrganizationServiceProxy proxy = (connection).OrganizationServiceProxy)
                {
                    RetrieveEntityResponse response = (RetrieveEntityResponse)proxy.Execute(request);
                    entityMetadata = response.EntityMetadata;
                }

                cache[cacheKey] = entityMetadata;
            }

            return(entityMetadata);
        }
Пример #20
0
        public void Can_get_entity_metadata_generic()
        {
            var entityMetadata            = new EntityMetadata();
            RetrieveEntityRequest request = null;
            var context = Substitute.For <ITransactionContext <Entity> >();

            context.Service.Execute(Arg.Any <RetrieveEntityRequest>())
            .Returns(ci =>
            {
                request      = ci.ArgAt <RetrieveEntityRequest>(0);
                var response = new RetrieveEntityResponse
                {
                    ["EntityMetadata"] = entityMetadata
                };
                return(response);
            });

            var retrievedEntityMetadata = context.GetMetadata <xts_relatedentity>();

            Assert.Same(entityMetadata, retrievedEntityMetadata);
            Assert.Equal("xts_relatedentity", request.LogicalName);
            Assert.Equal(EntityFilters.Default, request.EntityFilters);
            Assert.False(request.RetrieveAsIfPublished);

            context.GetMetadata <xts_relatedentity>(EntityFilters.Attributes);
            Assert.Equal(EntityFilters.Attributes, request.EntityFilters);
        }
        public void MissingMetadata_Throws()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);
            fakedContext.Initialize(SupportMethods.GetCustomerTypeEntity());
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata = fakedContext.GetEntityMetadataByName(String.Empty);
                var response       = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };
                return(response);
            });

            IOrganizationService fakedService = new Client.Services.OrganizationService(new Client.CrmConnection()); // fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            var ex = Assert.ThrowsException <Exception>(() => DataBuilder.AppendData(SupportMethods.GetCustomerTypeFetch()));
        }
Пример #22
0
        public void AddExistingEntity(string entityLogicalName, bool addRequiredComponents, bool doNotIncludeSubcomponents)
        {
            using (var svc = new CrmServiceClient(connection))
            {
                RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest()
                {
                    LogicalName = entityLogicalName
                };
                RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)svc.Execute(retrieveEntityRequest);

                AddSolutionComponentRequest addRequest = new AddSolutionComponentRequest()
                {
                    ComponentType             = (int)ComponentType.Entity,
                    ComponentId               = (Guid)retrieveEntityResponse.EntityMetadata.MetadataId,
                    SolutionUniqueName        = "samplesolution",
                    AddRequiredComponents     = addRequiredComponents,
                    DoNotIncludeSubcomponents = doNotIncludeSubcomponents
                };
                svc.Execute(addRequest);

                AddExistingComponentToSolution(ComponentType.SystemForm, "EA01497A-3AFD-45AF-8824-05179E65241F", "samplesolution");

                AddExistingComponentToSolution(ComponentType.Attribute, "D2C12E2D-D487-EB11-A812-000D3A4C1CE8", "samplesolution");
            }
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as RetrieveEntityRequest;

            if (string.IsNullOrWhiteSpace(req.LogicalName))
            {
                throw new Exception("A logical name property must be specified in the request");
            }

            if (req.EntityFilters.HasFlag(Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity) ||
                req.EntityFilters.HasFlag(Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes))
            {
                if (!ctx.EntityMetadata.ContainsKey(req.LogicalName))
                {
                    throw new Exception($"Entity '{req.LogicalName}' is not found in the metadata cache");
                }

                var entityMetadata = ctx.GetEntityMetadataByName(req.LogicalName);

                var response = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };

                return(response);
            }

            throw new Exception("Entity Filter not supported");
        }
        public void GetAttributeDotNetTypeUniqueidentifier()
        {
            string entityName    = "contactadntguid1";
            string attributeName = "contactadntid";

            var attributeMetaDataItem = new AttributeMetadata {
                LogicalName = attributeName
            };

            SetFieldValue(attributeMetaDataItem, "_attributeType", AttributeTypeCode.Uniqueidentifier);

            var attributes = new List <AttributeMetadata> {
                attributeMetaDataItem
            };

            RetrieveEntityResponse response = InjectMetaDataToResponse(new RetrieveEntityResponse(), attributes);

            MockOrganizationService.Setup(a => a.Execute(It.IsAny <OrganizationRequest>())).Returns(response);

            Type actual = null;

            FluentActions.Invoking(() => actual = systemUnderTest.GetAttributeDotNetType(entityName, attributeName))
            .Should()
            .NotThrow();

            MockOrganizationService.VerifyAll();
            Assert.AreEqual(typeof(Guid), actual);
        }
Пример #25
0
        public List <string> getEntityAttributesToClone(string entityName, IOrganizationService service,
                                                        ref string PrimaryIdAttribute)
        {
            List <string>         atts = new List <string>();
            RetrieveEntityRequest req  = new RetrieveEntityRequest()
            {
                EntityFilters = EntityFilters.Attributes,
                LogicalName   = entityName
            };

            RetrieveEntityResponse res = (RetrieveEntityResponse)service.Execute(req);

            PrimaryIdAttribute = res.EntityMetadata.PrimaryIdAttribute;

            foreach (AttributeMetadata attMetadata in res.EntityMetadata.Attributes)
            {
                if ((attMetadata.IsValidForCreate.Value || attMetadata.IsValidForUpdate.Value) &&
                    !attMetadata.IsPrimaryId.Value)
                {
                    //tracingService.Trace("Tipo:{0}", attMetadata.AttributeTypeName.Value.ToLower());
                    if (attMetadata.AttributeTypeName.Value.ToLower() == "partylisttype")
                    {
                        atts.Add("partylist-" + attMetadata.LogicalName);
                        //atts.Add(attMetadata.LogicalName);
                    }
                    else
                    {
                        atts.Add(attMetadata.LogicalName);
                    }
                }
            }

            return(atts);
        }
Пример #26
0
        public OrganizationResponse Execute(OrganizationRequest request)
        {
            OrganizationResponse res = null;

            if (request != null)
            {
                if (request.GetType() == typeof(WhoAmIRequest))
                {
                    if (_connectionString == "INCORRECT_CONNECTION_STRING")
                    {
                        throw new Exception("incorrect connection string");
                    }
                    res = new WhoAmIResponse();
                    res["BusinessUnitId"] = new Guid("73174763-ed0e-4aeb-b02a-9f6dc078260a");
                    res["OrganizationId"] = new Guid("73174763-ed0e-4aeb-b02a-9f6dc078260a");
                    res["UserId"]         = new Guid("73174763-ed0e-4aeb-b02a-9f6dc078260a");
                }
                else if (request.GetType() == typeof(RetrieveEntityRequest))
                {
                    var em = new EntityMetadata()
                    {
                        SchemaName = "myEntity"
                    };
                    AttributeMetadata attr1 = (AttributeMetadata)typeof(AttributeMetadata).GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new Type[] { typeof(AttributeTypeCode), typeof(string) }, null)
                                              .Invoke(new Object[] { AttributeTypeCode.Integer, "prop1" });
                    attr1.LogicalName = "prop1";
                    var attrs = new AttributeMetadata[] { attr1 };
                    em.GetType().GetProperty("Attributes").SetValue((object)em, (object)attrs);
                    res = new RetrieveEntityResponse();
                    res["EntityMetadata"] = em;
                }
            }
            return(res);
        }
Пример #27
0
        public Dictionary <string, string> GetAttributes(string entityName)
        {
            Dictionary <string, string> attributesData = new Dictionary <string, string>();

            RetrieveEntityRequest  metaDataRequest  = new RetrieveEntityRequest();
            RetrieveEntityResponse metaDataResponse = new RetrieveEntityResponse();

            metaDataRequest.EntityFilters = EntityFilters.Attributes;
            metaDataRequest.LogicalName   = entityName;
            metaDataResponse = (RetrieveEntityResponse)Service.Execute(metaDataRequest);

            foreach (AttributeMetadata a in metaDataResponse.EntityMetadata.Attributes)
            {
                //if more than one label for said attribute, get the one matching the languade code we want...
                if (a.DisplayName.LocalizedLabels.Count() > 1)
                {
                    attributesData.Add(a.LogicalName + " : " + a.AttributeType, a.DisplayName.LocalizedLabels.SingleOrDefault().Label);
                }

                //else, get the only one available regardless of languade code...
                if (a.DisplayName.LocalizedLabels.Count() == 1)
                {
                    attributesData.Add(a.LogicalName + " : " + a.AttributeType, a.DisplayName.LocalizedLabels[0].Label);
                }
            }

            return(attributesData);
        }
Пример #28
0
        /// <summary>
        /// Retrieves the list of all custom fields that are not on the form by default and are able to be added to the form
        /// </summary>
        /// <param name="service">CRM Organization service</param>
        /// <param name="entity">The string representation of the entity name</param>
        /// <returns>List of AttributeMetaData (fields)</returns>
        private IOrderedEnumerable <AttributeMetadata> GetAttributeMetaData(IOrganizationService service, string entity)
        {
            try
            {
                RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
                {
                    LogicalName           = entity,
                    EntityFilters         = EntityFilters.Attributes,
                    RetrieveAsIfPublished = true
                };

                RetrieveEntityResponse entityResponse         = (RetrieveEntityResponse)service.Execute(entityRequest);
                IOrderedEnumerable <AttributeMetadata> fields = entityResponse.EntityMetadata.Attributes
                                                                .Where(a => a.IsCustomAttribute == true)
                                                                .Where(a => a.IsPrimaryId == false)
                                                                .Where(a => a.IsPrimaryName == false)
                                                                .Where(a => a.IsValidForUpdate == true)
                                                                .OrderBy(a => a.LogicalName);
                return(fields);
            }
            catch (FaultException <OrganizationServiceFault> )
            {
                throw;
            }
        }
Пример #29
0
        //</snippetAuditing2>

        /// <summary>
        /// Enable auditing on an entity.
        /// </summary>
        /// <param name="entityLogicalName">The logical name of the entity.</param>
        /// <param name="flag">True to enable auditing, otherwise false.</param>
        /// <returns>The previous value of the IsAuditEnabled attribute.</returns>
        //<snippetAuditing3>
        private bool EnableEntityAuditing(string entityLogicalName, bool flag)
        {
            // Retrieve the entity metadata.
            RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
            {
                LogicalName   = entityLogicalName,
                EntityFilters = EntityFilters.Attributes
            };

            RetrieveEntityResponse entityResponse =
                (RetrieveEntityResponse)_service.Execute(entityRequest);

            // Enable auditing on the entity. By default, this also enables auditing
            // on all the entity's attributes.
            EntityMetadata entityMetadata = entityResponse.EntityMetadata;

            bool oldValue = entityMetadata.IsAuditEnabled.Value;

            entityMetadata.IsAuditEnabled = new BooleanManagedProperty(flag);

            UpdateEntityRequest updateEntityRequest = new UpdateEntityRequest {
                Entity = entityMetadata
            };

            UpdateEntityResponse updateEntityResponse =
                (UpdateEntityResponse)_service.Execute(updateEntityRequest);

            return(oldValue);
        }
        public List <OptionsetField> GetLocalOptionSet(string optionSetName, string entityName)
        {
            List <OptionsetField> optionSets = new List <OptionsetField>();
            ServerConnection      cnx        = new ServerConnection();

            try
            {
                RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.All,
                    LogicalName   = entityName
                };

                RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)cnx.Service.Execute(retrieveDetails);
                EntityMetadata         metadata = retrieveEntityResponseObj.EntityMetadata;

                PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals
                                                                                                    (attribute.LogicalName, optionSetName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata;

                picklistMetadata.OptionSet.Options.ToList().ForEach
                    (l =>
                    optionSets.Add(new OptionsetField()
                {
                    Label = l.Label.UserLocalizedLabel.Label,
                    Value = Convert.ToInt32(l.Value)
                })
                    );
            }
            catch (Exception ex)
            {
                cnx = null;
                throw new CrmDataException(ex);
            }
            return(optionSets);
        }
        private RetrieveEntityResponse ExecuteInternal(RetrieveEntityRequest request)
        {
            var name = new LocalizedLabel(request.LogicalName, Info.LanguageCode);
            var response = new RetrieveEntityResponse();
            response.Results["EntityMetadata"] = new EntityMetadata
            {
                DisplayCollectionName = new Label(name, new [] { name }),
            };

            return response;
        }
Пример #32
0
 public OrganizationResponse Execute(OrganizationRequest request)
 {
     OrganizationResponse res = null;
     if (request != null)
     {
         if (request.GetType() == typeof(WhoAmIRequest))
         {
             if (_connectionString == "INCORRECT_CONNECTION_STRING") throw new Exception("incorrect connection string");
             res = new WhoAmIResponse();
             res["BusinessUnitId"] = new Guid("73174763-ed0e-4aeb-b02a-9f6dc078260a");
             res["OrganizationId"] = new Guid("73174763-ed0e-4aeb-b02a-9f6dc078260a");
             res["UserId"] = new Guid("73174763-ed0e-4aeb-b02a-9f6dc078260a");
         }
         else if (request.GetType() == typeof(RetrieveEntityRequest))
         {
             var em = new EntityMetadata() { SchemaName = "myEntity" };
             AttributeMetadata attr1 = (AttributeMetadata)typeof(AttributeMetadata).GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new Type[] { typeof(AttributeTypeCode), typeof(string) }, null)
                                         .Invoke(new Object[] { AttributeTypeCode.Integer, "prop1" });
             attr1.LogicalName = "prop1";
             var attrs = new AttributeMetadata[] { attr1 };
             em.GetType().GetProperty("Attributes").SetValue(em, attrs);
             res = new RetrieveEntityResponse();
             res["EntityMetadata"] = em;
         }
     }
     return res;
 }