/// <summary> /// Create a custom entity. /// Update the custom entity. /// Optionally delete the custom entity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the custom entity. //<snippetCreateUpdateEntityMetadata1> CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Bank Account", 1033), DisplayCollectionName = new Label("Bank Accounts", 1033), Description = new Label("An entity to store information about customer bank accounts", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_accountname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Account Name", 1033), Description = new Label("The primary attribute for the Bank Account entity.", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The bank account entity has been created."); //</snippetCreateUpdateEntityMetadata1> // Add some attributes to the Bank Account entity //<snippetCreateUpdateEntityMetadata2> CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_bankname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Bank Name", 1033), Description = new Label("The name of the bank.", 1033) } }; _serviceProxy.Execute(createBankNameAttributeRequest); //</snippetCreateUpdateEntityMetadata2> Console.WriteLine("An bank name attribute has been added to the bank account entity."); //<snippetCreateUpdateEntityMetadata3> CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new MoneyAttributeMetadata { SchemaName = "new_balance", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label("Balance", 1033), Description = new Label("Account Balance at the last known date", 1033), } }; _serviceProxy.Execute(createBalanceAttributeRequest); //</snippetCreateUpdateEntityMetadata3> Console.WriteLine("An account balance attribute has been added to the bank account entity."); //<snippetCreateUpdateEntityMetadata4> CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new DateTimeAttributeMetadata { SchemaName = "new_checkeddate", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = DateTimeFormat.DateOnly, DisplayName = new Label("Date", 1033), Description = new Label("The date the account balance was last confirmed", 1033) } }; _serviceProxy.Execute(createCheckedDateRequest); Console.WriteLine("An date attribute has been added to the bank account entity."); //</snippetCreateUpdateEntityMetadata4> //Create a lookup attribute to link the bank account with a contact record. //<snippetCreateUpdateEntityMetadata5> CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The owner of the bank account", 1033), DisplayName = new Label("Account Owner", 1033), LogicalName = "new_parent_contactid", SchemaName = "New_Parent_ContactId", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("Bank Accounts", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = Contact.EntityLogicalName, ReferencedAttribute = "contactid", ReferencingEntity = _customEntityName, SchemaName = "new_contact_new_bankaccount" } }; _serviceProxy.Execute(req); //</snippetCreateUpdateEntityMetadata5> Console.WriteLine("A lookup attribute has been added to the bank account entity to link it with the Contact entity."); //<snippetCreateUpdateEntityMetadata11> //Create an Image attribute for the custom entity // Only one Image attribute can be added to an entity that doesn't already have one. CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new ImageAttributeMetadata { SchemaName = "EntityImage", //The name is always EntityImage RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Image", 1033), Description = new Label("An image to represent the bank account.", 1033) } }; _serviceProxy.Execute(createEntityImageRequest); Console.WriteLine("An image attribute has been added to the bank account entity."); //</snippetCreateUpdateEntityMetadata11> //<snippetCreateUpdateEntityMetadata9> //<snippetCreateUpdateEntityMetadata.RetrieveEntity> RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customEntityName }; RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest); //</snippetCreateUpdateEntityMetadata.RetrieveEntity> //<snippetCreateUpdateEntityMetadata8> EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata; // Disable Mail merge BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false); // Enable Notes UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest { Entity = BankAccountEntity, HasNotes = true }; _serviceProxy.Execute(updateBankAccountRequest); //</snippetCreateUpdateEntityMetadata8> //</snippetCreateUpdateEntityMetadata9> Console.WriteLine("The bank account entity has been updated"); //Update the entity form so the new fields are visible UpdateEntityForm(_customEntityName); // Customizations must be published after an entity is updated. //<snippetCreateUpdateEntityMetadata6> PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); //</snippetCreateUpdateEntityMetadata6> Console.WriteLine("Customizations were published."); //Provides option to view the entity in the default solution ShowEntityInBrowser(promptForDelete, BankAccountEntity); //Provides option to view the entity form with the fields added ShowEntityFormInBrowser(promptForDelete, BankAccountEntity); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private CreateOneToManyRequest BuildCreateOneToManyRequest(OneToManyRelationshipMetadata relationship, LookupAttributeMetadata lookup) { var createOneToManyRequest = new CreateOneToManyRequest(); createOneToManyRequest.OneToManyRelationship = relationship; createOneToManyRequest.Lookup = lookup; return(createOneToManyRequest); }
public override void CreateAttribute(IOrganizationService service) { var request = new CreateOneToManyRequest { OneToManyRelationship = GetRelationshipMetadata(), Lookup = GetAttributeMetadata() }; service.Execute(request); }
public static void CreateRelationShip() { //show subgrid on webform of fields CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The referral (" + _customFieldEntityName + ") from the " + _customEntityName + " table", 1033), DisplayName = new Label("Web Form", 1033), //LogicalName = "dots_parent_twitterpostid", //SchemaName = "dots_Parent_twitterpostId", LogicalName = "dots_parent_webformid", SchemaName = "dots_Parent_webformId", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("WebForm Accounts", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, //ReferencedEntity = _customFieldEntityName, //ReferencedAttribute = "dots_fieldid", //ReferencingEntity = _customEntityName, //SchemaName = "dots_field_dots_webform" ReferencedEntity = _customEntityName, ReferencedAttribute = "dots_webformid", ReferencingEntity = _customFieldEntityName, SchemaName = "dots_webform_dots_field" } }; _serviceProxy.Execute(req); }
public void CreateOneToManyRelationship <TOne, TMany>(Expression <Func <TMany, EntityReference <TOne> > > lookupExpr, EntityAttributes.Metadata.AttributeRequiredLevel lookupRequiredLevel, string relationshipPrefix = "new") where TOne : CrmPlusPlusEntity, new() where TMany : CrmPlusPlusEntity, new() { Guard.This(relationshipPrefix).AgainstNullOrEmpty(); var oneEntityName = EntityNameAttribute.GetFromType <TOne>(); var manyEntityName = EntityNameAttribute.GetFromType <TMany>(); var oneDisplayName = EntityInfoAttribute.GetFromType <TOne>().DisplayName; var lookupPropertyName = PropertyNameAttribute.GetFromType(lookupExpr); var oneToManyRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = oneEntityName, ReferencingEntity = manyEntityName, SchemaName = relationshipPrefix.EndsWith("_") ? relationshipPrefix : relationshipPrefix + "_" + oneEntityName + "_" + manyEntityName, AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = oneDisplayName.ToLabel(), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = lookupPropertyName, DisplayName = (oneDisplayName + " Lookup").ToLabel(), RequiredLevel = new AttributeRequiredLevelManagedProperty(lookupRequiredLevel.ToSimilarEnum <AttributeRequiredLevel>()), Description = (oneDisplayName + " Lookup").ToLabel() } }; service.Execute(oneToManyRequest); }
private static void CreateOneToManyAttribute(OrganizationServiceProxy service, string referencedEntityName, string referencingEntityName, string referencedEntityDisplayName, string attributeSchemaName, string attributeDisplayName, string attributeDescription) { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = referencingEntityName, ReferencingEntity = referencedEntityName, SchemaName = publisherPrefix + referencedEntityName + "_" + referencingEntityName + "_" + attributeSchemaName, AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label(referencedEntityDisplayName, 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = publisherPrefix + attributeSchemaName, DisplayName = new Label(attributeDisplayName, 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label(attributeDescription, 1033) } }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)service.Execute( createOneToManyRelationshipRequest); Console.WriteLine( "The one-to-many relationship has been created between {0} and {1}.", referencedEntityName, referencingEntityName); }
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); }
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 static CreateOneToManyRequest BuildCreateLookup(IOrganizationService service, string entityLogicalName) { var finalEntityLogicalName = entityLogicalName.Contains("_") ? entityLogicalName : $"clabs_{entityLogicalName}"; CreateOneToManyRequest createTrackedEtntiyLookupRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = entityLogicalName, //populate tracked entity name ReferencingEntity = "clabs_bpfchangehistory", SchemaName = string.Format("{0}_clabs_bpfchangehistory_createdbyplugin", finalEntityLogicalName), AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("History", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = finalEntityLogicalName + "id", DisplayName = new Label(entityLogicalName, 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label(entityLogicalName, 1033) } }; return(createTrackedEtntiyLookupRequest); }
public bool CreateOneToMany(IOrganizationService service, XRMSpeedyRelationship relationship, string prefix, int languageCode) { try { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = relationship.Entity1, ReferencingEntity = relationship.Entity2, SchemaName = relationship.SchemaName, AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label(relationship.Entity1.Substring(0, 1).ToUpper() + relationship.Entity1.Substring(1), languageCode), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.Cascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = relationship.PrimaryField }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)service.Execute(createOneToManyRelationshipRequest); return(true); } catch (FaultException <OrganizationServiceFault> ) { throw; } }
/// <summary> /// 创建Lookup字段 /// </summary> public OrganizationResponse CreateLookupField( string entityName, string schemName, string displayName, string decription, string referencedEntityName, string referencedAttributeName, string relationshipSchemName, AttributeRequiredLevel requiredLevel) { CreateOneToManyRequest request = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label(decription, 1033), DisplayName = new Label(displayName, 1033), SchemaName = schemName, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = referencedEntityName, ReferencedAttribute = referencedAttributeName, ReferencingEntity = entityName, SchemaName = relationshipSchemName } }; return(Service.Execute(request)); }
/// <summary> /// Create and configure the organization service proxy. /// Create one-to-many relationship. /// Create many-to-many relationship. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetWorkWithRelationships1> bool eligibleCreateOneToManyRelationship = EligibleCreateOneToManyRelationship("account", "campaign"); if (eligibleCreateOneToManyRelationship) { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = "account", ReferencingEntity = "campaign", SchemaName = "new_account_campaign", AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = "new_parent_accountid", DisplayName = new Label("Account Lookup", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Sample Lookup", 1033) } }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)_serviceProxy.Execute( createOneToManyRelationshipRequest); _oneToManyRelationshipId = createOneToManyRelationshipResponse.RelationshipId; _oneToManyRelationshipName = createOneToManyRelationshipRequest.OneToManyRelationship.SchemaName; Console.WriteLine( "The one-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } //</snippetWorkWithRelationships1> //<snippetWorkWithRelationships2> bool accountEligibleParticipate = EligibleCreateManyToManyRelationship("account"); bool campaignEligibleParticipate = EligibleCreateManyToManyRelationship("campaign"); if (accountEligibleParticipate && campaignEligibleParticipate) { CreateManyToManyRequest createManyToManyRelationshipRequest = new CreateManyToManyRequest { IntersectEntitySchemaName = "new_accounts_campaigns", ManyToManyRelationship = new ManyToManyRelationshipMetadata { SchemaName = "new_accounts_campaigns", Entity1LogicalName = "account", Entity1AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, Entity2LogicalName = "campaign", Entity2AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Campaign", 1033), Order = 10000 } } }; CreateManyToManyResponse createManytoManyRelationshipResponse = (CreateManyToManyResponse)_serviceProxy.Execute( createManyToManyRelationshipRequest); _manyToManyRelationshipId = createManytoManyRelationshipResponse.ManyToManyRelationshipId; _manyToManyRelationshipName = createManyToManyRelationshipRequest.ManyToManyRelationship.SchemaName; Console.WriteLine( "The many-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } //</snippetWorkWithRelationships2> // Publish the customization changes. _serviceProxy.Execute(new PublishAllXmlRequest()); //<snippetWorkWithRelationships.RetrieveRelationship> //You can use either the Name or the MetadataId of the relationship. //Retrieve the One-to-many relationship using the MetadataId. RetrieveRelationshipRequest retrieveOneToManyRequest = new RetrieveRelationshipRequest { MetadataId = _oneToManyRelationshipId }; RetrieveRelationshipResponse retrieveOneToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveOneToManyRequest); Console.WriteLine("Retrieved {0} One-to-many relationship by id", retrieveOneToManyResponse.RelationshipMetadata.SchemaName); //Retrieve the Many-to-many relationship using the Name. RetrieveRelationshipRequest retrieveManyToManyRequest = new RetrieveRelationshipRequest { Name = _manyToManyRelationshipName }; RetrieveRelationshipResponse retrieveManyToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveManyToManyRequest); Console.WriteLine("Retrieved {0} Many-to-Many relationship by Name", retrieveManyToManyResponse.RelationshipMetadata.MetadataId); //</snippetWorkWithRelationships.RetrieveRelationship> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
internal override OrganizationRequest Map(object[] dataRowValues) { var request = new CreateOneToManyRequest { Lookup = new LookupAttributeMetadata { RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired) }, OneToManyRelationship = new OneToManyRelationshipMetadata { AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } } }; foreach (var column in Columns) { var value = dataRowValues[column.Position - 1]; var field = (ConfigurationFile.OneToManyFields)column.TargetField; if (value != null) { switch (field) { case ConfigurationFile.OneToManyFields.SolutionUniqueName: request.SolutionUniqueName = value as string; break; case ConfigurationFile.OneToManyFields.EntityLogicalName: request.OneToManyRelationship.ReferencingEntity = (value as string).ToLower(); break; case ConfigurationFile.OneToManyFields.RelatedEntityLogicalName: request.OneToManyRelationship.ReferencedEntity = (value as string).ToLower(); break; case ConfigurationFile.OneToManyFields.SchemaName: request.OneToManyRelationship.SchemaName = value as string; break; case ConfigurationFile.OneToManyFields.LookupAttributeDisplayName: request.Lookup.DisplayName = new Label(value as string, LcId); break; case ConfigurationFile.OneToManyFields.LookupAttributeSchemaName: request.Lookup.SchemaName = value as string; break; case ConfigurationFile.OneToManyFields.RequiredLevel: request.Lookup.RequiredLevel = new AttributeRequiredLevelManagedProperty((AttributeRequiredLevel)EnumUtils.GetSelectedOption(field, value)); break; case ConfigurationFile.OneToManyFields.LookupAttributeDescription: request.Lookup.Description = new Label(value as string, LcId); break; case ConfigurationFile.OneToManyFields.MenuBehavior: request.OneToManyRelationship.AssociatedMenuConfiguration.Behavior = (AssociatedMenuBehavior)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.MenuGroup: request.OneToManyRelationship.AssociatedMenuConfiguration.Group = (AssociatedMenuGroup)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.MenuCustomLabel: request.OneToManyRelationship.AssociatedMenuConfiguration.Label = new Label(value as string, LcId); break; case ConfigurationFile.OneToManyFields.MenuOrder: request.OneToManyRelationship.AssociatedMenuConfiguration.Order = Convert.ToInt32(value); break; case ConfigurationFile.OneToManyFields.CascadeAssign: request.OneToManyRelationship.CascadeConfiguration.Assign = (CascadeType)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.CascadeShare: request.OneToManyRelationship.CascadeConfiguration.Share = (CascadeType)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.CascadeUnshare: request.OneToManyRelationship.CascadeConfiguration.Unshare = (CascadeType)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.CascadeReparent: request.OneToManyRelationship.CascadeConfiguration.Reparent = (CascadeType)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.CascadeDelete: request.OneToManyRelationship.CascadeConfiguration.Delete = (CascadeType)EnumUtils.GetSelectedOption(field, value); break; case ConfigurationFile.OneToManyFields.CascadeMerge: request.OneToManyRelationship.CascadeConfiguration.Merge = (CascadeType)EnumUtils.GetSelectedOption(field, value); break; } } else if (!EnumUtils.IsOptional(field)) { throw new ArgumentException($"Mandatory data field {EnumUtils.Label(field)} does not contain a value."); } } return(request); }
/// <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); }
public ActionResult ViewUploadFile(HttpPostedFileBase file, Models.UploadFileModel uploadFileModel) { Boolean verboseLogs = false; StringBuilder message = new StringBuilder(); StringBuilder messageError = new StringBuilder(); StringBuilder table = new StringBuilder(); Int32 entityCount = 0; Int32 attributeCount = 0; string fieldSchemaName = string.Empty; List<string> entityNameCreatedList = new List<string>(); List<string> fieldSchemaNameCreatedList = new List<string>(); Boolean error = false; if (ModelState.IsValid) { try { if (Login.IsValid(Login.OrgURL.ToString(), Login.Email.ToString(), sc.Decrypt(Login.Password.ToString()))) { //assign the crm service if (file != null && file.ContentLength > 0 && System.IO.Path.GetExtension(file) == ".xlsx") { try { //Set <httpRuntime maxRequestLength="x" /> in your web.config, where x is the number of //KB allowed for upload. Default is 4KB var fileName = System.IO.Path.GetFileName(file.FileName); using (MemoryStream ms = new MemoryStream()) { file.InputStream.CopyTo(ms); byte[] myFile = ms.GetBuffer(); Entity myNote = new Entity(Annotation.EntityLogicalName); string subject = "Metadata File: " + fileName.ToString(); myNote["subject"] = subject; Guid myNoteGuid = service.Create(myNote); if (myNoteGuid != Guid.Empty) { using (ExcelPackage package = new ExcelPackage(ms)) { foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets) { DataTable tbl = createDataTablefromExcel(worksheet, true); var missing = from c in findMyRequiredFields() where !tbl.Columns.Contains(c) select c; missing.ToList(); if (missing.Count() > 0) { error = true; message.AppendLine(worksheet.Name + " is not valid for import and will be skipped. It is missing the following required columns: " + String.Join(Environment.NewLine, missing)); } else { error = false; message.AppendLine(String.Format("Data successfully retrieved from excel-worksheet: {0}. Colum-count:{1} Row-count:{2}", worksheet.Name, tbl.Columns.Count, tbl.Rows.Count)); var eN = tbl.AsEnumerable().Select(r => r.Field<string>(findMyRequiredFields().First<string>())); string entityName = eN.First<string>(); if (verboseLogs) message.AppendLine("entityname: " + entityName.ToString()); #region GetAttributes int currentRow; List<AttributeMetadata> addedAttributes; List<CRMLookup> crmLookupList; addedAttributes = new List<AttributeMetadata>(); crmLookupList = new List<CRMLookup>(); foreach (DataRow row in tbl.Rows) { string fieldDisplayName = row[findMyRequiredFields()[1]].ToString(); fieldSchemaName = uploadFileModel.preFix + row[findMyRequiredFields()[2]].ToString(); if (verboseLogs) message.AppendLine("fieldSchemaName: " + fieldSchemaName); string fieldReq = row[findMyRequiredFields()[3]].ToString(); AttributeRequiredLevel reqLvl; if (fieldReq == "Business Required") reqLvl = AttributeRequiredLevel.ApplicationRequired; else reqLvl = AttributeRequiredLevel.None; string fieldDataType = row[findMyRequiredFields()[4]].ToString(); string fieldRecordType = row[findMyRequiredFields()[5]].ToString(); string fieldFormat = row[findMyRequiredFields()[6]].ToString(); if (fieldFormat == "Text") strFm = StringFormat.Text; else if (fieldFormat == "URL") strFm = StringFormat.Url; else if (fieldFormat == "Date Only") dtFm = DateTimeFormat.DateOnly; string fieldPrecisionLength = row[findMyRequiredFields()[7]].ToString(); string fieldOther = row[findMyRequiredFields()[8]].ToString(); if (fieldDataType == "Decimal Number" && fieldOther.Contains("auto")) { minLength = Convert.ToDecimal(fieldOtherMin.Substring(0, fieldOtherMin.IndexOf(' ') - 1).Replace(",", "")); if (verboseLogs) message.AppendLine("minLength: " + minLength.ToString()); maxLength = Convert.ToDecimal(fieldOtherMax.Substring(fieldOtherMax.IndexOf(' ') + 1, fieldOtherMax.IndexOf(", auto") - (fieldOtherMax.IndexOf(' ') + 1)).Replace(",", "")); if (verboseLogs) message.AppendLine("maxLength: " + maxLength.ToString()); } else { if (fieldDataType == "Single Line of Text") addedAttributes.Add(createAttributeObj(fieldSchemaName, fieldDisplayName, "", reqLvl, Convert.ToInt32(fieldPrecisionLength), strFm)); else if (fieldDataType == "Multiple Lines of Text") addedAttributes.Add(createAttributeObj(fieldSchemaName, fieldDisplayName, "", reqLvl, Convert.ToInt32(fieldPrecisionLength.Replace(",","")))); else if (fieldDataType == "Date and Time") addedAttributes.Add(createAttributeObj(fieldSchemaName, fieldDisplayName, "", reqLvl, dtFm)); else if (fieldDataType == "Two Options") addedAttributes.Add(createAttributeObj(fieldSchemaName, fieldDisplayName, "", reqLvl, defaultValue)); else if (fieldDataType == "Decimal Number") addedAttributes.Add(createAttributeObj(fieldSchemaName, fieldDisplayName, "", reqLvl, minLength, maxLength, Convert.ToInt16(fieldPrecisionLength))); else if (fieldDataType == "Lookup") crmLookupList.Add(new CRMLookup { schemaName = fieldSchemaName, displayName = fieldDisplayName, description = "", fieldRecordType = fieldRecordType, lvl = reqLvl, parentEntityDisplayName = entityName, fieldOther = fieldOther }); else if (fieldDataType == "Option Set") { var labels = Regex.Split(fieldOther, "\r\n|\r|\n"); OptionSetMetadata setupOptionSetMetadata = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist }; int optionsValue = 1; foreach (var lbl in labels) { setupOptionSetMetadata.Options.Add(new OptionMetadata(new Label(lbl, 1033), optionsValue)); optionsValue++; } addedAttributes.Add(createAttributeObj(fieldSchemaName, fieldDisplayName, "", reqLvl, setupOptionSetMetadata)); } } currentRow++; } #endregion #region CreateEntityandPrimaryAttribute if (verboseLogs) message.AppendLine(String.Format("Create entity: {0} with PrimaryAttribute: {1}", entityName, primaryName)); CreateEntityRequest createrequest = new CreateEntityRequest { Entity = new EntityMetadata { SchemaName = uploadFileModel.preFix + entityName, DisplayName = new Label(entityName, 1033), DisplayCollectionName = new Label(entityName, 1033) OwnershipType = OwnershipTypes.UserOwned, }, PrimaryAttribute = new StringAttributeMetadata { SchemaName = primaryName, RequiredLevel = new AttributeRequiredLevelManagedProperty(primaryLvl), MaxLength = primaryLength, Format = primaryFormat, DisplayName = new Label(primaryDisplayName, 1033) }, }; service.Execute(createrequest); entityCount++; attributeCount++; if (verboseLogs) message.AppendLine("The " + entityName + " custom entity has been created."); entityNameCreatedList.Add(entityName); #endregion #region CreateAttributes if (addedAttributes.Count > 0) { foreach (AttributeMetadata anAttribute in addedAttributes) { if (verboseLogs) message.AppendLine(String.Format("attribute {0}.", anAttribute.SchemaName)); fieldSchemaName = anAttribute.SchemaName; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = uploadFileModel.preFix + entityName.ToLower(), Attribute = anAttribute }; service.Execute(createAttributeRequest); attributeCount++; fieldSchemaNameCreatedList.Add(anAttribute.SchemaName); } } if (crmLookupList.Count > 0) { foreach (CRMLookup anAttribute in crmLookupList) { if (verboseLogs) message.AppendLine(String.Format("LookupAttribute {0}.", anAttribute.schemaName)); fieldSchemaName = anAttribute.schemaName; CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { DisplayName = new Label(anAttribute.displayName, 1033), LogicalName = anAttribute.schemaName, SchemaName = anAttribute.schemaName, RequiredLevel = new AttributeRequiredLevelManagedProperty(anAttribute.lvl) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { ReferencedEntity = anAttribute.fieldRecordType.ToLower(), ReferencedAttribute = anAttribute.fieldRecordType.ToLower() + "id", ReferencingEntity = uploadFileModel.preFix + anAttribute.parentEntityDisplayName.ToLower(), SchemaName = anAttribute.fieldOther } }; service.Execute(req); attributeCount++; fieldSchemaNameCreatedList.Add(anAttribute.schemaName); if (verboseLogs) message.AppendLine(String.Format("Created the LookupAttribute {0}.", anAttribute.schemaName)); } } #endregion Entity myNoteU = new Entity(Annotation.EntityLogicalName); myNoteU.Id = myNoteGuid; if (error) myNoteU["subject"] = "FAILED " + subject; else myNoteU["subject"] = "SUCCEEDED " + subject; myNoteU["notetext"] = message.ToString() + String.Format("Entities created: {0}, Attributes created: {1}, Global OptionSets created: {2}", entityCount, attributeCount, globalAttributeCount); service.Update(myNoteU); } } } }
/// <summary> /// Create and configure the organization service proxy. /// Create one-to-many relationship. /// Create many-to-many relationship. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetWorkWithRelationships1> bool eligibleCreateOneToManyRelationship = EligibleCreateOneToManyRelationship("account", "campaign"); if (eligibleCreateOneToManyRelationship) { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = "account", ReferencingEntity = "campaign", SchemaName = "new_account_campaign", AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = "new_parent_accountid", DisplayName = new Label("Account Lookup", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Sample Lookup", 1033) } }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)_serviceProxy.Execute( createOneToManyRelationshipRequest); _oneToManyRelationshipId = createOneToManyRelationshipResponse.RelationshipId; _oneToManyRelationshipName = createOneToManyRelationshipRequest.OneToManyRelationship.SchemaName; Console.WriteLine( "The one-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } //</snippetWorkWithRelationships1> //<snippetWorkWithRelationships2> bool accountEligibleParticipate = EligibleCreateManyToManyRelationship("account"); bool campaignEligibleParticipate = EligibleCreateManyToManyRelationship("campaign"); if (accountEligibleParticipate && campaignEligibleParticipate) { CreateManyToManyRequest createManyToManyRelationshipRequest = new CreateManyToManyRequest { IntersectEntitySchemaName = "new_accounts_campaigns", ManyToManyRelationship = new ManyToManyRelationshipMetadata { SchemaName = "new_accounts_campaigns", Entity1LogicalName = "account", Entity1AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, Entity2LogicalName = "campaign", Entity2AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Campaign", 1033), Order = 10000 } } }; CreateManyToManyResponse createManytoManyRelationshipResponse = (CreateManyToManyResponse)_serviceProxy.Execute( createManyToManyRelationshipRequest); _manyToManyRelationshipId = createManytoManyRelationshipResponse.ManyToManyRelationshipId; _manyToManyRelationshipName = createManyToManyRelationshipRequest.ManyToManyRelationship.SchemaName; Console.WriteLine( "The many-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } //</snippetWorkWithRelationships2> // Publish the customization changes. _serviceProxy.Execute(new PublishAllXmlRequest()); //<snippetWorkWithRelationships.RetrieveRelationship> //You can use either the Name or the MetadataId of the relationship. //Retrieve the One-to-many relationship using the MetadataId. RetrieveRelationshipRequest retrieveOneToManyRequest = new RetrieveRelationshipRequest { MetadataId = _oneToManyRelationshipId }; RetrieveRelationshipResponse retrieveOneToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveOneToManyRequest); Console.WriteLine("Retrieved {0} One-to-many relationship by id", retrieveOneToManyResponse.RelationshipMetadata.SchemaName); //Retrieve the Many-to-many relationship using the Name. RetrieveRelationshipRequest retrieveManyToManyRequest = new RetrieveRelationshipRequest { Name = _manyToManyRelationshipName}; RetrieveRelationshipResponse retrieveManyToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveManyToManyRequest); Console.WriteLine("Retrieved {0} Many-to-Many relationship by Name", retrieveManyToManyResponse.RelationshipMetadata.MetadataId); //</snippetWorkWithRelationships.RetrieveRelationship> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public void Run() { objCRMHelper = new CRMHelper(); _serviceProxy = objCRMHelper.setSrvice(); try { //<snippetWorkWithRelationships1> bool eligibleCreateOneToManyRelationship = EligibleCreateOneToManyRelationship("rah_country", "rah_territory"); Console.WriteLine("fileName" + fileName); if (eligibleCreateOneToManyRelationship) { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = "rah_country", ReferencingEntity = "rah_territory", SchemaName = "rah_country_rah_territory", AssociatedMenuConfiguration = new AssociatedMenuConfiguration { // Behavior = AssociatedMenuBehavior.UseLabel, Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("MASTER Country", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.Restrict, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = "rah_parent_rah_countryid", DisplayName = new Label("Country Lookup", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MASTer Sample rah_country Lookup", 1033) } }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)_serviceProxy.Execute( createOneToManyRelationshipRequest); _oneToManyRelationshipId = createOneToManyRelationshipResponse.RelationshipId; _oneToManyRelationshipName = createOneToManyRelationshipRequest.OneToManyRelationship.SchemaName; Console.WriteLine( "The One-to-Many relationship has been created between {0} and {1}.", "rah_country", "rah_territory"); } } catch (FaultException <OrganizationServiceFault> ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp); Console.WriteLine("Code: {0}", ex.Detail.ErrorCode); Console.WriteLine("Message: {0}", ex.Detail.Message); Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } catch (System.TimeoutException ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Message: {0}", ex.Message); Console.WriteLine("Stack Trace: {0}", ex.StackTrace); Console.WriteLine("Inner Fault: {0}", null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message); } catch (System.Exception ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); FaultException <OrganizationServiceFault> fe = ex.InnerException as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>; if (fe != null) { Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp); Console.WriteLine("Code: {0}", fe.Detail.ErrorCode); Console.WriteLine("Message: {0}", fe.Detail.Message); Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } } } }
/// <summary> /// Create a custom entity /// </summary> /// <returns></returns> public static void CreateCustomEntity() { Console.WriteLine("###### Creating Custom Entity"); CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity. This entity will show up in Sales/Service/Marketing -> Extensions (last group) Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Custom Entity", 1033), DisplayCollectionName = new Label("Custom Entities", 1033), Description = new Label("A custom entity created for testing purpose", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_name", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Name", 1033), Description = new Label("The primary attribute for the Custom Entity.", 1033) } }; service.Execute(createrequest); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); service.Execute(publishRequest); //Add String type attribute CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_teststring", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Test String", 1033) } }; service.Execute(createBankNameAttributeRequest); //Add money type attribute CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new MoneyAttributeMetadata { SchemaName = "new_testmoney", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label("Test Money", 1033) } }; service.Execute(createBalanceAttributeRequest); //Add date only attribute CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new DateTimeAttributeMetadata { SchemaName = "new_testdate", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = DateTimeFormat.DateOnly, DisplayName = new Label("Test Date", 1033), } }; service.Execute(createCheckedDateRequest); //Add lookup attribute CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The referral (lead) from the Custom Entity record", 1033), DisplayName = new Label("Test Lookup To Lead", 1033), LogicalName = "new_customentity_leadid", SchemaName = "new_customentity_leadid", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("Custom Entities", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = "lead", ReferencedAttribute = "leadid", ReferencingEntity = _customEntityName, SchemaName = "new_customentity_leadid" } }; service.Execute(req); // Customizations must be published after an entity is updated. publishRequest = new PublishAllXmlRequest(); service.Execute(publishRequest); Console.WriteLine("Created Custom Entity"); }
/// <summary> /// Create a custom entity. /// Update the custom entity. /// Optionally delete the custom entity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the custom entity. //<snippetCreateUpdateEntityMetadata1> CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Bank Account", 1033), DisplayCollectionName = new Label("Bank Accounts", 1033), Description = new Label("An entity to store information about customer bank accounts", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_accountname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Account Name", 1033), Description = new Label("The primary attribute for the Bank Account entity.", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The bank account entity has been created."); //</snippetCreateUpdateEntityMetadata1> // Add some attributes to the Bank Account entity //<snippetCreateUpdateEntityMetadata2> CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_bankname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Bank Name", 1033), Description = new Label("The name of the bank.", 1033) } }; _serviceProxy.Execute(createBankNameAttributeRequest); //</snippetCreateUpdateEntityMetadata2> Console.WriteLine("An bank name attribute has been added to the bank account entity."); //<snippetCreateUpdateEntityMetadata3> CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new MoneyAttributeMetadata { SchemaName = "new_balance", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label("Balance", 1033), Description = new Label("Account Balance at the last known date", 1033), } }; _serviceProxy.Execute(createBalanceAttributeRequest); //</snippetCreateUpdateEntityMetadata3> Console.WriteLine("An account balance attribute has been added to the bank account entity."); //<snippetCreateUpdateEntityMetadata4> CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new DateTimeAttributeMetadata { SchemaName = "new_checkeddate", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = DateTimeFormat.DateOnly, DisplayName = new Label("Date", 1033), Description = new Label("The date the account balance was last confirmed", 1033) } }; _serviceProxy.Execute(createCheckedDateRequest); Console.WriteLine("An date attribute has been added to the bank account entity."); //</snippetCreateUpdateEntityMetadata4> //Create a lookup attribute to link the bank account with a contact record. //<snippetCreateUpdateEntityMetadata5> CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The owner of the bank account", 1033), DisplayName = new Label("Account Owner", 1033), LogicalName = "new_parent_contactid", SchemaName = "New_Parent_ContactId", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("Bank Accounts", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = Contact.EntityLogicalName, ReferencedAttribute = "contactid", ReferencingEntity = _customEntityName, SchemaName = "new_contact_new_bankaccount" } }; _serviceProxy.Execute(req); //</snippetCreateUpdateEntityMetadata5> Console.WriteLine("A lookup attribute has been added to the bank account entity to link it with the Contact entity."); //<snippetCreateUpdateEntityMetadata11> //Create an Image attribute for the custom entity // Only one Image attribute can be added to an entity that doesn't already have one. CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new ImageAttributeMetadata { SchemaName = "EntityImage", //The name is always EntityImage RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Image", 1033), Description = new Label("An image to represent the bank account.", 1033) } }; _serviceProxy.Execute(createEntityImageRequest); Console.WriteLine("An image attribute has been added to the bank account entity."); //</snippetCreateUpdateEntityMetadata11> //<snippetCreateUpdateEntityMetadata9> //<snippetCreateUpdateEntityMetadata.RetrieveEntity> RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customEntityName }; RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest); //</snippetCreateUpdateEntityMetadata.RetrieveEntity> //<snippetCreateUpdateEntityMetadata8> EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata; // Disable Mail merge BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false); // Enable Notes UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest { Entity = BankAccountEntity, HasNotes = true }; _serviceProxy.Execute(updateBankAccountRequest); //</snippetCreateUpdateEntityMetadata8> //</snippetCreateUpdateEntityMetadata9> Console.WriteLine("The bank account entity has been updated"); //Update the entity form so the new fields are visible UpdateEntityForm(_customEntityName); // Customizations must be published after an entity is updated. //<snippetCreateUpdateEntityMetadata6> PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); //</snippetCreateUpdateEntityMetadata6> Console.WriteLine("Customizations were published."); //Provides option to view the entity in the default solution ShowEntityInBrowser(promptForDelete, BankAccountEntity); //Provides option to view the entity form with the fields added ShowEntityFormInBrowser(promptForDelete, BankAccountEntity); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
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 void CreateLookupAttribute(string entityLogicalName, AttributeTemplate attributeTemplate) { var schemaName = attributeTemplate.LogicalName + "_" + attributeTemplate.LookupEntityLogicalName + "_" + entityLogicalName; if(schemaName.Length > 100) { schemaName = schemaName.Substring(default(int), 100); } var createOneToManyRequest = new CreateOneToManyRequest { Lookup = new LookupAttributeMetadata { Description = GetLabelWithLocalized(attributeTemplate.Description), DisplayName = GetLabelWithLocalized(attributeTemplate.DisplayNameShort), LogicalName = attributeTemplate.LogicalName, SchemaName = attributeTemplate.LogicalName, RequiredLevel = new AttributeRequiredLevelManagedProperty(attributeTemplate.IsRequired ? AttributeRequiredLevel.SystemRequired : AttributeRequiredLevel.None) }, OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = attributeTemplate.LookupEntityLogicalName, ReferencingEntity = entityLogicalName, SchemaName = schemaName } }; if (!string.IsNullOrWhiteSpace(attributeTemplate.OtherDisplayName)) { var otherDisplayLabel = new LocalizedLabel(attributeTemplate.OtherDisplayName, DefaultConfiguration.OtherLanguageCode); createOneToManyRequest.Lookup.DisplayName.LocalizedLabels.Add(otherDisplayLabel); } if (!string.IsNullOrWhiteSpace(attributeTemplate.OtherDescription)) { var otherDescriptionLabel = new LocalizedLabel(attributeTemplate.OtherDescription, DefaultConfiguration.OtherLanguageCode); createOneToManyRequest.Lookup.Description.LocalizedLabels.Add(otherDescriptionLabel); } CreateRequest createWebRequest = null; if (attributeTemplate.DisplayName.Length > DefaultConfiguration.AttributeDisplayNameMaxLength) { createWebRequest = GetCreateWebResourceRequest(entityLogicalName, attributeTemplate); } ExecuteOperation(GetSharedOrganizationService(), createOneToManyRequest, string.Format("An error occured while creating the attribute: {0}", attributeTemplate.LogicalName)); if (createWebRequest != null) { ExecuteOperation(GetSharedOrganizationService(), createWebRequest, string.Format("An error occured while creating the web resource for attribute: {0}", attributeTemplate.LogicalName)); } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate bool eligibleCreateOneToManyRelationship = EligibleCreateOneToManyRelationship(service, "account", "contact"); if (eligibleCreateOneToManyRelationship) { var createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = "account", ReferencingEntity = "contact", SchemaName = "new_account_contact", AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = "new_parent_accountid", DisplayName = new Label("Account Lookup", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Sample Lookup", 1033) } }; var createOneToManyRelationshipResponse = (CreateOneToManyResponse)service.Execute( createOneToManyRelationshipRequest); _oneToManyRelationshipId = createOneToManyRelationshipResponse.RelationshipId; _oneToManyRelationshipName = createOneToManyRelationshipRequest.OneToManyRelationship.SchemaName; Console.WriteLine( "The one-to-many relationship has been created between {0} and {1}.", "account", "contact"); } bool accountEligibleParticipate = EligibleCreateManyToManyRelationship(service, "account"); bool campaignEligibleParticipate = EligibleCreateManyToManyRelationship(service, "contact"); if (accountEligibleParticipate && campaignEligibleParticipate) { var createManyToManyRelationshipRequest = new CreateManyToManyRequest { IntersectEntitySchemaName = "new_accounts_contacts", ManyToManyRelationship = new ManyToManyRelationshipMetadata { SchemaName = "new_accounts_contacts", Entity1LogicalName = "account", Entity1AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, Entity2LogicalName = "contact", Entity2AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Contact", 1033), Order = 10000 } } }; var createManytoManyRelationshipResponse = (CreateManyToManyResponse)service.Execute( createManyToManyRelationshipRequest); _manyToManyRelationshipId = createManytoManyRelationshipResponse.ManyToManyRelationshipId; _manyToManyRelationshipName = createManyToManyRelationshipRequest.ManyToManyRelationship.SchemaName; Console.WriteLine( "The many-to-many relationship has been created between {0} and {1}.", "account", "contact"); } // Publish the customization changes. service.Execute(new PublishAllXmlRequest()); //You can use either the Name or the MetadataId of the relationship. //Retrieve the One-to-many relationship using the MetadataId. var retrieveOneToManyRequest = new RetrieveRelationshipRequest { MetadataId = _oneToManyRelationshipId }; var retrieveOneToManyResponse = (RetrieveRelationshipResponse)service.Execute(retrieveOneToManyRequest); Console.WriteLine("Retrieved {0} One-to-many relationship by id", retrieveOneToManyResponse.RelationshipMetadata.SchemaName); //Retrieve the Many-to-many relationship using the Name. var retrieveManyToManyRequest = new RetrieveRelationshipRequest { Name = _manyToManyRelationshipName }; var retrieveManyToManyResponse = (RetrieveRelationshipResponse)service.Execute(retrieveManyToManyRequest); Console.WriteLine("Retrieved {0} Many-to-Many relationship by Name", retrieveManyToManyResponse.RelationshipMetadata.MetadataId); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public static void ProcessAttributeList(BackgroundWorker worker, List <Attribute> attributeList, IOrganizationService service) { var importLogs = new List <string>(); var importEntities = new List <string>(); int successfulImports = 0; int failedImports = 0; foreach (var attr in attributeList) { int progressComplete = FieldCreatorHelpers.ReturnProgressComplete(attributeList.IndexOf(attr), attributeList.Count()); worker.ReportProgress(progressComplete, attr.FieldSchemaName); string fullyQualFieldTypeName = AttrTypes[attr.FieldType]; Type attributeType = Type.GetType(fullyQualFieldTypeName); dynamic attribute = Activator.CreateInstance(attributeType, attr); var attributeInstance = (IAttribute)attribute; AttributeMetadata attributeMetadata = attributeInstance.ReturnAttributeMetadata(attr); if (attr.FieldType == "Lookup") { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = attr.ReferencedEntity, ReferencingEntity = attribute.AttrEntitySchemaName, SchemaName = attr.OnetoNRelationshipSchemaName, AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label(attribute.AttrEntitySchemaName, CultureInfo.CurrentCulture.LCID), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = (LookupAttributeMetadata)attributeMetadata, SolutionUniqueName = attr.SolutionUniqueName }; try { service.Execute(createOneToManyRelationshipRequest); importLogs.Add($"Success | {attr.FieldSchemaName}"); importEntities.Add(attr.EntitySchemaName); successfulImports++; } catch (Exception exception) { importLogs.Add($"Fail | {attr.FieldSchemaName} - {exception.Message}"); failedImports++; } } else { CreateAttributeRequest createAttrRequest = new CreateAttributeRequest { SolutionUniqueName = attribute.AttrSolution, EntityName = attribute.AttrEntitySchemaName, Attribute = attributeMetadata }; try { service.Execute(createAttrRequest); importLogs.Add($"Success | {attr.FieldSchemaName}"); importEntities.Add(attr.EntitySchemaName); successfulImports++; } catch (Exception exception) { importLogs.Add($"Fail | {attr.FieldSchemaName} - {exception.Message}"); failedImports++; } } } FieldCreatorPluginControl.ImportEntities = importEntities; FieldCreatorPluginControl.ImportLogs = importLogs; }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate //Create a custom entity var createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Bank Account", 1033), DisplayCollectionName = new Label("Bank Accounts", 1033), Description = new Label("An entity to store information about customer bank accounts", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_accountname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Account Name", 1033), Description = new Label("The primary attribute for the Bank Account entity.", 1033) } }; service.Execute(createrequest); Console.WriteLine("The bank account entity has been created."); //Add a String attribute to the custom entity CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_bankname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Bank Name", 1033), Description = new Label("The name of the bank.", 1033) } }; service.Execute(createBankNameAttributeRequest); //Add a Money attribute to the custom entity CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new MoneyAttributeMetadata { SchemaName = "new_balance", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label("Balance", 1033), Description = new Label("Account Balance at the last known date", 1033), } }; service.Execute(createBalanceAttributeRequest); //Add a DateTime attribute to the custom entity CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new DateTimeAttributeMetadata { SchemaName = "new_checkeddate", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = DateTimeFormat.DateOnly, DisplayName = new Label("Date", 1033), Description = new Label("The date the account balance was last confirmed", 1033) } }; service.Execute(createCheckedDateRequest); Console.WriteLine("An date attribute has been added to the bank account entity."); //Adding lookup attribute to the custom entity CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The referral (lead) from the bank account owner", 1033), DisplayName = new Label("Referral", 1033), LogicalName = "new_parent_leadid", SchemaName = "New_Parent_leadId", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("Bank Accounts", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = "lead", ReferencedAttribute = "leadid", ReferencingEntity = _customEntityName, SchemaName = "new_lead_new_bankaccount" } }; service.Execute(req); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }