public void Can_generate_get_related_multi_lookup() { var lookupAttributeMetadata = new LookupAttributeMetadata { DisplayName = new Label { UserLocalizedLabel = new LocalizedLabel("User Label", 1033) }, LogicalName = "xts_lookupid", SchemaName = "Xts_SchemaLookupId", Targets = new[] { "xts_entity", "xts_anotherentity" } }; typeof(LookupAttributeMetadata).GetProperty("EntityLogicalName").SetValue(lookupAttributeMetadata, "xts_containerentity"); var lookupToEntityMetadata = new EntityMetadata { DisplayName = new Label { UserLocalizedLabel = new LocalizedLabel("Entity Label", 1033) }, LogicalName = "xts_entity", SchemaName = "EntitySchemaName" }; var holder = new LookupAttributeMetadataHolder("MyEntity", lookupAttributeMetadata, lookupToEntityMetadata); var result = holder.Generate(null); Assert.Equal("GetUserLabel", result.MethodName); Assert.Equal(ExpectedTemplate.GetRelatedMultiLookup, result.Content); }
public void CustomLookupOnCustomUnmanagedEntityNotConformingRuleValidationMessage() { var entity = new EntityMetadata() { SchemaName = "foo_MyEntity", DisplayName = new Label() { UserLocalizedLabel = new LocalizedLabel("My Entity", 1033) } }; entity.SetSealedPropertyValue("IsManaged", false); entity.SetSealedPropertyValue("IsCustomEntity", true); var scope = RuleScope.Lookup; var lookupAttr = new LookupAttributeMetadata(LookupFormat.None) { SchemaName = "foo_MyCustomLookup" }; lookupAttr.SetSealedPropertyValue("IsCustomAttribute", true); lookupAttr.SetSealedPropertyValue("IsManaged", false); var attributes = new List <AttributeMetadata> { lookupAttr }; var solutionEntity = new SolutionEntity(entity, attributes, true); var rule = new RegexRule(_REGEX_PATTERN, scope); var results = rule.Validate(solutionEntity); Assert.Equal($"Rule failed: {rule.Description} Following lookups do not match given pattern: foo_MyCustomLookup.", results.FormatValidationResult()); }
public LookupAttributeMetadataHolder(string entitySchemaName, LookupAttributeMetadata lookupMetadata, EntityMetadata lookupToEntityMetadata) { EntitySchemaName = entitySchemaName; LookupMetadata = lookupMetadata; LookupToEntityMetadata = lookupToEntityMetadata; }
public void CustomLookupOnCustomUnmanagedEntityConformingRule() { var entity = new EntityMetadata() { SchemaName = "foo_MyEntity", }; entity.SetSealedPropertyValue("IsManaged", false); entity.SetSealedPropertyValue("IsCustomEntity", true); var scope = RuleScope.Lookup; var lookupAttr = new LookupAttributeMetadata(LookupFormat.None) { SchemaName = "foo_MyCustomLookupId" }; lookupAttr.SetSealedPropertyValue("IsCustomAttribute", true); lookupAttr.SetSealedPropertyValue("IsManaged", false); var attributes = new List <AttributeMetadata> { lookupAttr }; var solutionEntity = new SolutionEntity(entity, attributes, true); var rule = new RegexRule(_REGEX_PATTERN, scope); var results = rule.Validate(solutionEntity); Assert.True(results.Passed); }
public EntityReferenceMappingControl(IOrganizationServiceExtented service , LookupAttributeMetadata attributeMetadata , EntityReference entityReferenceConnection1 , EntityReference entityReferenceConnection2 ) { InitializeComponent(); AttributeMetadataControlFactory.SetGroupBoxNameByAttributeMetadata(gbAttribute, attributeMetadata); this._service = service; this._entityReferenceConnection1 = entityReferenceConnection1; this._entityReferenceConnection2 = entityReferenceConnection2; this.AttributeMetadata = attributeMetadata; txtBEntityReferenceConnection1EntityName.Text = this._entityReferenceConnection1.LogicalName; txtBEntityReferenceConnection1EntityId.Text = this._entityReferenceConnection1.Id.ToString(); if (!string.IsNullOrEmpty(this._entityReferenceConnection1.Name)) { txtBEntityReferenceConnection1Name.Text = this._entityReferenceConnection1.Name; } else { txtBEntityReferenceConnection1Name.IsEnabled = false; txtBEntityReferenceConnection1Name.Visibility = Visibility.Collapsed; } btnRestore.IsEnabled = _entityReferenceConnection2 != null; btnRestore.Visibility = btnRestore.IsEnabled ? Visibility.Visible : Visibility.Collapsed; SetEntityReference(entityReferenceConnection2); }
public Guid AddRelationship(OneToManyRelationshipMetadata relationship, LookupAttributeMetadata lookup) { bool isReferencingEligible = EligibleForRelationship(relationship.ReferencingEntity, "CanBeReferencing"); bool isReferencedEligible = EligibleForRelationship(relationship.ReferencedEntity, "CanBeReferenced"); if (!(isReferencedEligible && isReferencingEligible)) { throw new Exception(string.Format("One-to-Many relationship between '{0}' and '{1}' is not allowed.", relationship.ReferencingEntity, relationship.ReferencedEntity)); } OrganizationRequest request = new OrganizationRequest("CreateOneToMany") { Parameters = new ParameterCollection { { "OneToManyRelationship", relationship }, { "Lookup", lookup } } }; if (CrmContext.ActiveSolution != null) { request.Parameters.Add("SolutionUniqueName", CrmContext.ActiveSolution); } OrganizationResponse response = CrmContext.OrganizationProxy.Execute(request); return((Guid)response.Results["RelationshipId"]); }
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); }
public void StoreLookUpAttributeWithLookupAttributeMetadataButEmptyTargetList() { var attributeLogicalName = "contactId"; string primaryAttribute = "contactId"; var crmField = new Capgemini.Xrm.DataMigration.Model.CrmField() { PrimaryKey = false, FieldName = primaryAttribute, FieldType = "entityreference" }; var attribute = new LookupAttributeMetadata { LogicalName = attributeLogicalName, DisplayName = new Label { UserLocalizedLabel = new LocalizedLabel { Label = attributeLogicalName } } }; NotificationServiceMock.Setup(x => x.DisplayFeedback("The supplied attribute is null. Expecting an Entity Reference!")) .Verifiable(); FluentActions.Invoking(() => systemUnderTest.StoreLookUpAttribute(attribute, crmField, NotificationServiceMock.Object)) .Should() .NotThrow(); NotificationServiceMock.Verify(x => x.DisplayFeedback("The supplied attribute is null. Expecting an Entity Reference!"), Times.Never); crmField.LookupType.Should().BeNull(); }
public void CustomLookupOnCustomUnmanagedEntityConformingRuleResultStringIsCorrect() { var entity = new EntityMetadata() { SchemaName = "foo_MyEntity", DisplayName = new Label() { UserLocalizedLabel = new LocalizedLabel("My Entity", 1033) } }; entity.SetSealedPropertyValue("IsManaged", false); entity.SetSealedPropertyValue("IsCustomEntity", true); var scope = RuleScope.Lookup; var lookupAttr = new LookupAttributeMetadata(LookupFormat.None) { SchemaName = "foo_MyCustomLookupId" }; lookupAttr.SetSealedPropertyValue("IsCustomAttribute", true); lookupAttr.SetSealedPropertyValue("IsManaged", false); var attributes = new List <AttributeMetadata> { lookupAttr }; var solutionEntity = new SolutionEntity(entity, attributes, true); var rule = new RegexRule(_REGEX_PATTERN, scope); var results = rule.Validate(solutionEntity); Assert.Equal($"Rule: {rule.Description} Succeeded for entity \"My Entity\" (foo_MyEntity).", results.FormatValidationResult()); }
private AttributeMetadata CloneAttributes(LookupAttributeMetadata att) { return(new LookupAttributeMetadata { Targets = att.Targets }); }
private static AttributeMetadata GetAttributeMetadataFromFieldNodeType(SchemaXml.Field property) { var attr = new AttributeMetadata(); switch (property.Type) { case "bool": return(new BooleanAttributeMetadata()); case "partylist": attr = new LookupAttributeMetadata(); attr.SetSealedPropertyValue("AttributeType", AttributeTypeCode.PartyList); attr.SetSealedPropertyValue("Targets", new String[] { "account", "contact" }); return(attr); case "entityreference": attr = new LookupAttributeMetadata(); return(attr); case "owner": attr = new LookupAttributeMetadata(); attr.SetSealedPropertyValue("AttributeType", AttributeTypeCode.Owner); return(attr); case "datetime": return(new DateTimeAttributeMetadata()); case "decimal": return(new DecimalAttributeMetadata()); case "float": return(new DoubleAttributeMetadata()); case "number": return(new IntegerAttributeMetadata()); case "string": return(new StringAttributeMetadata()); case "money": return(new MoneyAttributeMetadata()); case "optionsetvalue": return(new PicklistAttributeMetadata()); case "state": return(new StateAttributeMetadata()); case "status": return(new StatusAttributeMetadata()); case "guid": return(new UniqueIdentifierAttributeMetadata()); default: throw new Exception(String.Format("Unknown Field Node Type: {0}", property.Type)); // ? return new MultiSelectPicklistAttributeMetadata(); } }
public void Can_get_method_name_with_blacklist(LookupAttributeMetadata lookupMetadata, EntityMetadata lookupToEntityMetadata, IEnumerable <string> blacklist, string expectedName) { var holder = new LookupAttributeMetadataHolder("EntitySchemaName", lookupMetadata, lookupToEntityMetadata); Assert.Equal(expectedName, holder.GetMethodName(blacklist)); }
public static IEnumerable <AttributeMetadata> GetOwnerMetadata() { var ownerid = new LookupAttributeMetadata() { SchemaName = "ownerid", LogicalName = "ownerid" }; yield return(ownerid); }
public void GetNameForAttribute_AddsRefOnTheEndOfLookup() { var attMetadata = new LookupAttributeMetadata { LogicalName = "ee_testpropid", DisplayName = new Label("TestProp", 1033) }; var metadata = new EntityMetadata { LogicalName = "ee_test" } .Set(x => x.Attributes, new AttributeMetadata[] { attMetadata }); var output = sut.GetNameForAttribute(metadata, attMetadata, serviceProvider); Assert.AreEqual("TestProp", output); }
public XRMSpeedyRelationship(string entity1, string entity2, string entity1Display, string entity2Display, string relationshipType, string schemaName, string prefix) { Entity1 = entity1; Entity2 = entity2; Entity1Display = entity1Display; Entity2Display = entity2Display; RelationshipType = relationshipType; SchemaName = schemaName; if (relationshipType == "1:N Relationship") { PrimaryField = SetPrimaryField(prefix, entity1, entity1Display); } }
public void ValidateLookupColumnLookupAttributeMetadata() { string entityName = "contactattnoattributes"; mappings = new Dictionary <string, Dictionary <string, List <string> > >(); var values = new Dictionary <string, List <string> > { { entityName, new List <string>() { entityName } } }; mappings.Add(entityName, values); var attributeMetaDataItem = new LookupAttributeMetadata { LogicalName = entityName }; attributeMetaDataItem.Targets = new List <string> { entityName }.ToArray(); var attributes = new List <AttributeMetadata> { attributeMetaDataItem }; var entityMetadata = new EntityMetadata(); var attributesField = entityMetadata.GetType().GetRuntimeFields().First(a => a.Name == "_attributes"); attributesField.SetValue(entityMetadata, attributes.ToArray()); metadataServiceMock.Setup(x => x.RetrieveEntities(It.IsAny <string>(), It.IsAny <IOrganizationService>(), It.IsAny <IExceptionService>())) .Returns(entityMetadata) .Verifiable(); int rowIndex = 0; using (var systemUnderTest = new MappingListLookup(mappings, orgServiceMock.Object, metadata, selectedValue, metadataServiceMock.Object, dataMigratorExceptionHelperMock.Object)) { FluentActions.Invoking(() => systemUnderTest.ValidateLookupColumn(rowIndex, entityName, attributes.ToArray())) .Should() .NotThrow(); } metadataServiceMock.Verify(x => x.RetrieveEntities(It.IsAny <string>(), It.IsAny <IOrganizationService>(), It.IsAny <IExceptionService>()), Times.Exactly(1)); }
private IExtensibleDataObject lookUpFieldCreation(string[] row) { LookupAttributeMetadata attrMetadata = new LookupAttributeMetadata(); generalFieldCreation(row, attrMetadata); OneToManyRelationshipMetadata oneToManyRelationship = new OneToManyRelationshipMetadata(); oneToManyRelationship.ReferencingEntity = entityLocialName; string relatiosshipName = row[ExcelColumsDefinition.LOOKUPRELATIONSHIPNAME] != string.Empty ? row[ExcelColumsDefinition.LOOKUPRELATIONSHIPNAME] : string.Empty; string relashionshiptarget = row[ExcelColumsDefinition.LOOKUPTARGET] != string.Empty ? row[ExcelColumsDefinition.LOOKUPTARGET] : string.Empty; oneToManyRelationship.ReferencedEntity = relashionshiptarget; oneToManyRelationship.SchemaName = Utils.addOrgPrefix(relatiosshipName, organizationPrefix, currentOperationCreate); CreateOneToManyRequest createRelationship = new CreateOneToManyRequest(); createRelationship.Lookup = attrMetadata; createRelationship.OneToManyRelationship = oneToManyRelationship; return(createRelationship); }
public static EntityMetadata GetEntityMetadata() { var metadata = new EntityMetadata { LogicalName = "account" }; metadata.SetSealedPropertyValue(nameof(metadata.PrimaryIdAttribute), "accountid"); metadata.SetSealedPropertyValue(nameof(metadata.PrimaryNameAttribute), "name"); var accountid = new UniqueIdentifierAttributeMetadata("accountid") { LogicalName = "accountid" }; accountid.SetSealedPropertyValue(nameof(accountid.IsPrimaryId), true); accountid.SetSealedPropertyValue(nameof(accountid.IsValidForCreate), true); var name = new StringAttributeMetadata("name") { LogicalName = "name" }; name.SetSealedPropertyValue(nameof(name.IsPrimaryName), true); name.SetSealedPropertyValue(nameof(name.IsValidForCreate), true); var primarycontactid = new LookupAttributeMetadata() { LogicalName = "primarycontactid", SchemaName = "primarycontactid" }; primarycontactid.SetSealedPropertyValue(nameof(primarycontactid.IsValidForCreate), true); metadata.SetAttributeCollection( new AttributeMetadata[] { accountid, name, primarycontactid } .Concat(GlobalMetadata.GetGlobalMetadata()) .Concat(GlobalMetadata.GetOwnerMetadata()) .Concat(GlobalMetadata.GetProcessMetadata()) .ToArray()); return(metadata); }
private OrganizationRequest CloneLookupAttribute(EntityMetadata sourceEntity, EntityMetadata targetEntity, AttributeMetadata attribute) { var lookupAttribute = attribute as LookupAttributeMetadata; if (lookupAttribute == null) { return(null); } var relationShip = sourceEntity.ManyToOneRelationships.SingleOrDefault( rel => rel.ReferencingAttribute.Equals(lookupAttribute.LogicalName, StringComparison.InvariantCultureIgnoreCase)); if (relationShip == null) { return(null); } relationShip.ReferencingEntity = targetEntity.LogicalName; relationShip.ReferencingAttribute = string.Empty; relationShip.ReferencedEntityNavigationPropertyName = relationShip.ReferencedEntityNavigationPropertyName.ReplaceEntityName(sourceEntity.LogicalName, targetEntity.LogicalName); relationShip.SchemaName = relationShip.SchemaName.ReplaceEntityName(sourceEntity.LogicalName, targetEntity.LogicalName); var lookup = new LookupAttributeMetadata { Description = lookupAttribute.Description, DisplayName = lookupAttribute.DisplayName, LogicalName = lookupAttribute.LogicalName, SchemaName = lookupAttribute.SchemaName, RequiredLevel = lookupAttribute.RequiredLevel }; var request = new CreateOneToManyRequest { Lookup = lookup, OneToManyRelationship = relationShip }; return(request); }
private void AddOneToMany() { OneToManyRelationshipMetadata relationship = new OneToManyRelationshipMetadata { ReferencedEntity = ToEntity, ReferencingEntity = Entity, SchemaName = Name }; if (_context != null) { _context.SetParametersOnRelationship(relationship); } LookupAttributeMetadata lookup = new LookupAttributeMetadata { SchemaName = AttributeName, DisplayName = new Label(AttributeDisplayName, CrmContext.Language), Description = new Label(AttributeDescription ?? string.Empty, CrmContext.Language) }; AttributeRequiredLevel requiredLevel = AttributeRequiredLevel.ApplicationRequired; if (AttributeRequired == CrmRequiredLevel.Required) { requiredLevel = AttributeRequiredLevel.ApplicationRequired; } if (AttributeRequired == CrmRequiredLevel.Recommended) { requiredLevel = AttributeRequiredLevel.Recommended; } if (AttributeRequired == CrmRequiredLevel.Optional) { requiredLevel = AttributeRequiredLevel.None; } lookup.RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel); Guid result = _repository.AddRelationship(relationship, lookup); if (PassThru) { WriteObject(_repository.GetRelationship(result)); } }
private bool IsCompatibleType(AttributeMetadata a, AttributeMetadata attr) { // For optionset attributes, check they are the same optionset type if (a is EnumAttributeMetadata optionsetX && attr is EnumAttributeMetadata optionsetY) { return(optionsetX.OptionSet.IsGlobal == true && optionsetY.OptionSet.IsGlobal == true && optionsetX.OptionSet.Name == optionsetY.OptionSet.Name); } // For lookup/customer/owner/uniqueid attributes, check they can refer to the same entity types var lookupX = a as LookupAttributeMetadata; var lookupY = attr as LookupAttributeMetadata; if (a.IsPrimaryId == true) { lookupX = new LookupAttributeMetadata { Targets = new[] { a.EntityLogicalName } } } ; if (attr.IsPrimaryId == true) { lookupY = new LookupAttributeMetadata { Targets = new[] { attr.EntityLogicalName } } } ; if (lookupX != null && lookupY != null) { return(lookupX.Targets.Intersect(lookupY.Targets).Any()); } // For everything else, just check they're the same overall type if (a.AttributeType == attr.AttributeType) { return(true); } return(false); }
public void ExcludedLookupsAreCheckedOnCustomUnmanagedEntity() { var entity = new EntityMetadata() { SchemaName = "foo_myEntity", }; entity.SetSealedPropertyValue("IsManaged", false); entity.SetSealedPropertyValue("IsCustomEntity", true); var scope = RuleScope.Lookup; var lookupAttr = new LookupAttributeMetadata() { SchemaName = "foo_LookupFieldId2" }; lookupAttr.SetSealedPropertyValue("IsCustomAttribute", true); lookupAttr.SetSealedPropertyValue("IsManaged", false); var primaryKeyAttr = new LookupAttributeMetadata() { SchemaName = "foo_MyEntityId" }; primaryKeyAttr.SetSealedPropertyValue("IsCustomAttribute", true); primaryKeyAttr.SetSealedPropertyValue("IsManaged", false); var attributes = new List <AttributeMetadata> { lookupAttr, primaryKeyAttr }; var solutionEntity = new SolutionEntity(entity, attributes, true); var excludedSchemaNames = new string[] { "foo_myEntity.foo_LookupFieldId2" }; var rule = new RegexRule(_REGEX_PATTERN, scope, excludedSchemaNames); var results = rule.Validate(solutionEntity); Assert.True(results.Passed); }
private void updateSchemaName(string TargetField, string AddedField, EntityMetadata metaData) { if (Target.Contains(TargetField)) { if (Target.GetAttributeValue <string>(TargetField).Contains(".")) { tracingService.Trace("LinkEntity Field"); string[] values = Target.GetAttributeValue <string>(TargetField).Split('.'); AttributeMetadata attributeData = metaData.Attributes.Where(a => a.LogicalName == values[0]).Single(); LookupAttributeMetadata lookupField = attributeData as LookupAttributeMetadata; EntityMetadata parentMetadata = FindLookupEntity(values[1], lookupField.Targets); tracingService.Trace("Adding " + AddedField + " to Target for: " + Target.GetAttributeValue <string>(TargetField)); Target[AddedField] = parentMetadata.Attributes.Single(a => a.LogicalName == values[1]).SchemaName; UpdateEntitySchemaName(parentMetadata.SchemaName); } else { UpdateEntitySchemaName(metaData.SchemaName); tracingService.Trace("Target Field"); if (!String.IsNullOrWhiteSpace(Target.GetAttributeValue <string>(TargetField))) { tracingService.Trace("Adding " + AddedField + " to Target for: " + Target.GetAttributeValue <string>(TargetField)); Target[AddedField] = metaData.Attributes.Single(a => a.LogicalName == Target.GetAttributeValue <string>(TargetField)).SchemaName; } else { tracingService.Trace("Clearing " + AddedField); Target[AddedField] = ""; } } } }
private object CopyValueInternal(AttributeMetadata oldAttribute, LookupAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping) { CopyValueInternal((object)oldAttribute, newAttribute, value, migrationMapping); return(null); }
private object CopyValueInternal(AttributeMetadata oldAttribute, LookupAttributeMetadata newAttribute, object value) { CopyValueInternal((object)oldAttribute, newAttribute, value); return null; }
public LookupAttributeMetadataInfo(LookupAttributeMetadata amd) : base(amd) { this.amd = amd; }
private static AttributeMetadata CreateAttributeMetadata(Type propertyType) { if (typeof(string) == propertyType) { return(new StringAttributeMetadata()); } else if (typeof(EntityReference).IsAssignableFrom(propertyType)) { return(new LookupAttributeMetadata()); } #if FAKE_XRM_EASY || FAKE_XRM_EASY_2013 || FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 else if (typeof(Microsoft.Xrm.Client.CrmEntityReference).IsAssignableFrom(propertyType)) { return(new LookupAttributeMetadata()); } #endif else if (typeof(OptionSetValue).IsAssignableFrom(propertyType)) { return(new PicklistAttributeMetadata()); } else if (typeof(Money).IsAssignableFrom(propertyType)) { return(new MoneyAttributeMetadata()); } else if (propertyType.IsGenericType) { Type genericType = propertyType.GetGenericArguments().FirstOrDefault(); if (propertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (typeof(int) == genericType) { return(new IntegerAttributeMetadata()); } else if (typeof(double) == genericType) { return(new DoubleAttributeMetadata()); } else if (typeof(bool) == genericType) { return(new BooleanAttributeMetadata()); } else if (typeof(decimal) == genericType) { return(new DecimalAttributeMetadata()); } else if (typeof(DateTime) == genericType) { return(new DateTimeAttributeMetadata()); } else if (typeof(Guid) == genericType) { return(new LookupAttributeMetadata()); } else if (typeof(long) == genericType) { return(new BigIntAttributeMetadata()); } else if (typeof(Enum).IsAssignableFrom(genericType)) { return(new StateAttributeMetadata()); } else { throw new Exception($"Type {propertyType.Name}{genericType.Name} has not been mapped to an AttributeMetadata."); } } else if (propertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) { var partyList = new LookupAttributeMetadata(); partyList.SetSealedPropertyValue("AttributeType", AttributeTypeCode.PartyList); return(partyList); } else { throw new Exception($"Type {propertyType.Name}{genericType.Name} has not been mapped to an AttributeMetadata."); } } else if (typeof(BooleanManagedProperty) == propertyType) { var booleanManaged = new BooleanAttributeMetadata(); booleanManaged.SetSealedPropertyValue("AttributeType", AttributeTypeCode.ManagedProperty); return(booleanManaged); } #if !FAKE_XRM_EASY && !FAKE_XRM_EASY_2013 else if (typeof(Guid) == propertyType) { return(new UniqueIdentifierAttributeMetadata()); } #endif #if !FAKE_XRM_EASY else if (typeof(byte[]) == propertyType) { return(new ImageAttributeMetadata()); } #endif #if FAKE_XRM_EASY_9 else if (typeof(OptionSetValueCollection).IsAssignableFrom(propertyType)) { return(new MultiSelectPicklistAttributeMetadata()); } #endif else { throw new Exception($"Type {propertyType.Name} has not been mapped to an AttributeMetadata."); } }
private RetrieveAttributeResponse ExecuteInternal(RetrieveAttributeRequest request) { var response = new RetrieveAttributeResponse(); var entityType = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes().FirstOrDefault(t => t.GetCustomAttribute <EntityLogicalNameAttribute>(true)?.LogicalName == request.EntityLogicalName); var propertyTypes = entityType?.GetProperties() .Where(p => p.GetCustomAttribute <AttributeLogicalNameAttribute>()?.LogicalName == request.LogicalName ).Select(p => p.PropertyType.IsGenericType ? p.PropertyType.GenericTypeArguments.First() : p.PropertyType).ToList(); var propertyType = propertyTypes?.Count == 1 ? propertyTypes[0] : propertyTypes?.FirstOrDefault(p => p != typeof(OptionSetValue) && p != typeof(EntityReference)); // Handle OptionSets/EntityReferences that may have multiple properties if (propertyType == null) { throw new Exception($"Unable to find a property for Entity {request.EntityLogicalName} and property {request.LogicalName} in {CrmServiceUtility.GetEarlyBoundProxyAssembly().FullName}"); } AttributeMetadata metadata; if (propertyType.IsEnum || propertyTypes.Any(p => p == typeof(OptionSetValue))) { metadata = CreateOptionSetAttributeMetadata(request, propertyType); } else if (propertyType == typeof(string)) { metadata = new StringAttributeMetadata(request.LogicalName); } else if (propertyTypes.Any(p => p == typeof(EntityReference))) { metadata = new LookupAttributeMetadata { LogicalName = request.LogicalName }; } #if !XRM_2013 else if (propertyType == typeof(Guid)) { metadata = new UniqueIdentifierAttributeMetadata { LogicalName = request.LogicalName }; } #endif else if (propertyType == typeof(bool)) { metadata = new BooleanAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(Money)) { metadata = new MoneyAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(int)) { metadata = new IntegerAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(long)) { metadata = new BigIntAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(DateTime)) { metadata = new DateTimeAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(double)) { metadata = new DoubleAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(decimal)) { metadata = new DecimalAttributeMetadata { LogicalName = request.LogicalName }; } else { throw new NotImplementedException($"Attribute Type of {propertyType.FullName} is not implemented."); } response.Results["AttributeMetadata"] = metadata; return(response); }
/// <summary> /// Create the LookupField in CDS /// </summary> /// <param name="entity"> /// Uses: Entity.CollectionName /// </param> /// <param name="field"> /// Uses: LookupField.SchemaName, .LookupToEntity, .LookupToField /// </param> public void CreateLookupField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); var targetentity = JSONUtil.GetText(field, "target-entity"); var targetfield = JSONUtil.GetText(field, "target-field"); var relationshipname = JSONUtil.GetText(field, "relname"); var em = this._cdsConnection.GetEntityMetadata(entitySchemaName); CreateOneToManyRequest req = new CreateOneToManyRequest(); // define the general lookup metadata var la = new LookupAttributeMetadata(); la.Description = new Label("", 1033); la.DisplayName = new Label(displayName, 1033); la.LogicalName = fieldSchemaName; la.SchemaName = fieldSchemaName; la.RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended); req.Lookup = la; // define the 1:N relationship var rel = new OneToManyRelationshipMetadata(); // 1:N associated menu config var amc = new AssociatedMenuConfiguration(); amc.Behavior = AssociatedMenuBehavior.UseCollectionName; amc.Group = AssociatedMenuGroup.Details; amc.Label = em.DisplayCollectionName; amc.Order = 10000; rel.AssociatedMenuConfiguration = amc; // 1:N cascade behavior config var cc = new CascadeConfiguration(); cc.Assign = CascadeType.NoCascade; cc.Delete = CascadeType.RemoveLink; cc.Merge = CascadeType.NoCascade; cc.Reparent = CascadeType.NoCascade; cc.Share = CascadeType.NoCascade; cc.Unshare = CascadeType.NoCascade; rel.CascadeConfiguration = cc; // 1:N entity reference rel.ReferencedEntity = targetentity; rel.ReferencedAttribute = targetfield; rel.ReferencingEntity = entitySchemaName; if (relationshipname == null) { relationshipname = this.GetNextRelationshipName(em, field); } rel.SchemaName = relationshipname; req.OneToManyRelationship = rel; this._cdsConnection.Execute(req); }
private AttributeMetadata CloneAttributes(LookupAttributeMetadata att) { return new LookupAttributeMetadata { Targets = att.Targets }; }
public void Can_get_method_name(LookupAttributeMetadata lookupMetadata, EntityMetadata lookupToEntityMetadata, string expectedName) { var holder = new LookupAttributeMetadataHolder("EntitySchemaName", lookupMetadata, lookupToEntityMetadata); Assert.Equal(expectedName, holder.GetMethodName(null)); }
private AttributeMetadata CreateAttributeWithDifferentNameInternal(IOrganizationService service, LookupAttributeMetadata existingAtt, string newSchemaName, AttributeMetadata newAttributeType) { if (newAttributeType != null) { throw new NotImplementedException("Updating that attribute type for Lookup Attributes to a different type is not implemented!"); } var clone = (LookupAttributeMetadata)CloneAttributes(existingAtt, newSchemaName, null); foreach (var relationship in Metadata.ManyToOneRelationships.Where(r => r.ReferencingAttribute == existingAtt.LogicalName && r.ReferencingEntity == existingAtt.EntityLogicalName)) { UpdateRelationshipSchemaName(relationship, newSchemaName); relationship.ReferencingAttribute = null; relationship.ReferencedAttribute = null; Trace("Creating Relationship " + relationship.SchemaName); service.Execute(new CreateOneToManyRequest { OneToManyRelationship = relationship, Lookup = clone }); } foreach (var relationship in Metadata.OneToManyRelationships.Where(r => r.ReferencedAttribute == existingAtt.LogicalName && r.ReferencedEntity == existingAtt.EntityLogicalName)) { UpdateRelationshipSchemaName(relationship, newSchemaName); relationship.ReferencingAttribute = null; relationship.ReferencedAttribute = null; Trace("Creating Relationship " + relationship.SchemaName); service.Execute(new CreateOneToManyRequest { OneToManyRelationship = relationship, Lookup = clone }); } return clone; }
public void CreateOrUpdateLookupAttribute(string schemaName, string displayName, string description, bool isRequired, bool audit, bool searchable, string recordType, string referencedEntityType, bool displayInRelated) { lock (LockObject) { LookupAttributeMetadata metadata; if (FieldExists(schemaName, recordType)) metadata = (LookupAttributeMetadata) GetFieldMetadata(schemaName, recordType); else metadata = new LookupAttributeMetadata(); SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable); if (FieldExists(schemaName, recordType)) { CreateOrUpdateAttribute(schemaName, recordType, metadata); var relationships = GetEntityOneToManyRelationships(referencedEntityType); var relationship = relationships.First(r => r.ReferencingAttribute.ToLower() == schemaName); var newBehvaiour = displayInRelated ? AssociatedMenuBehavior.UseCollectionName : AssociatedMenuBehavior.DoNotDisplay; if (newBehvaiour != relationship.AssociatedMenuConfiguration.Behavior) { relationship.AssociatedMenuConfiguration.Behavior = displayInRelated ? AssociatedMenuBehavior.UseCollectionName : AssociatedMenuBehavior.DoNotDisplay; var request = new UpdateRelationshipRequest() { Relationship = relationship }; Execute(request); RefreshEntityMetadata(recordType); RefreshEntityMetadata(referencedEntityType); } } else { var request = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { SchemaName = string.Format("{0}_{1}_{2}", recordType, referencedEntityType, schemaName), AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = displayInRelated ? AssociatedMenuBehavior.UseCollectionName : AssociatedMenuBehavior.DoNotDisplay }, ReferencingEntity = recordType, ReferencedEntity = referencedEntityType }, Lookup = metadata }; Execute(request); RefreshFieldMetadata(schemaName, recordType); CreateOrUpdateAttribute(schemaName, recordType, metadata); RefreshEntityMetadata(recordType); RefreshEntityMetadata(referencedEntityType); } } }
private LookupAttributeMetadata BuildCreateLookupAttribute() { var lookupAtt = new LookupAttributeMetadata(); return(lookupAtt); }