/// <summary> /// Create and configure the organization service proxy. /// Create few types of attributes. /// Insert status in the existing status list. /// Retrieve attribute. /// Update attribute. /// Update existing state value. /// Optionally delete/revert any attributes /// that were created/changed 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(); //<snippetWorkWithAttributes1> #region How to create attributes //<snippetWorkWithAttributes2> // Create storage for new attributes being created addedAttributes = new List<AttributeMetadata>(); // Create a boolean attribute BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_boolean", DisplayName = new Label("Sample Boolean", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; // Add to list addedAttributes.Add(boolAttribute); // Create a date time attribute DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_datetime", DisplayName = new Label("Sample DateTime", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("DateTime Attribute", _languageCode), // Set extended properties Format = DateTimeFormat.DateOnly, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(dtAttribute); // Create a decimal attribute DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_decimal", DisplayName = new Label("Sample Decimal", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Decimal Attribute", _languageCode), // Set extended properties MaxValue = 100, MinValue = 0, Precision = 1 }; // Add to list addedAttributes.Add(decimalAttribute); // Create a integer attribute IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_integer", DisplayName = new Label("Sample Integer", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Integer Attribute", _languageCode), // Set extended properties Format = IntegerFormat.None, MaxValue = 100, MinValue = 0 }; // Add to list addedAttributes.Add(integerAttribute); // Create a memo attribute MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_memo", DisplayName = new Label("Sample Memo", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Memo Attribute", _languageCode), // Set extended properties Format = StringFormat.TextArea, ImeMode = ImeMode.Disabled, MaxLength = 500 }; // Add to list addedAttributes.Add(memoAttribute); // Create a money attribute MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_money", DisplayName = new Label("Money Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Money Attribue", _languageCode), // Set extended properties MaxValue = 1000.00, MinValue = 0.00, Precision = 1, PrecisionSource = 1, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(moneyAttribute); // Create a picklist attribute PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_picklist", DisplayName = new Label("Sample Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Picklist Attribute", _languageCode), // Set extended properties // Build local picklist options OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata( new Label("Created", _languageCode), null), new OptionMetadata( new Label("Updated", _languageCode), null), new OptionMetadata( new Label("Deleted", _languageCode), null) } } }; // Add to list addedAttributes.Add(pickListAttribute); // Create a string attribute StringAttributeMetadata stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_string", DisplayName = new Label("Sample String", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("String Attribute", _languageCode), // Set extended properties MaxLength = 100 }; // Add to list addedAttributes.Add(stringAttribute); // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship. // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type. // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK. foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. _serviceProxy.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } //</snippetWorkWithAttributes2> #endregion How to create attributes #region How to insert status //<snippetWorkWithAttributes3> // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. InsertStatusValueRequest insertStatusValueRequest = new InsertStatusValueRequest { AttributeLogicalName = "statuscode", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("Dormant", _languageCode), StateCode = 0 }; // Execute the request and store newly inserted value // for cleanup, used later part of this sample. _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); //</snippetWorkWithAttributes3> #endregion How to insert status #region How to retrieve attribute //<snippetWorkWithAttributes4> // Create the request RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); //</snippetWorkWithAttributes4> #endregion How to retrieve attribute #region How to update attribute //<snippetWorkWithAttributes5> // Modify the retrieved attribute AttributeMetadata retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest UpdateAttributeRequest updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); //</snippetWorkWithAttributes5> #endregion How to update attribute #region How to update state value //<snippetWorkWithAttributes6> // Modify the state value label from Active to Open. // Create the request. UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. _serviceProxy.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); //</snippetWorkWithAttributes6> #endregion How to update state value #region How to insert a new option item in a local option set //<snippetWorkWithAttributes7> // Create a request. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); //</snippetWorkWithAttributes7> #endregion How to insert a new option item in a local option set #region How to change the order of options of a local option set //<snippetWorkWithAttributes8> // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute( retrieveAttributeRequest); // Access the retrieved attribute. PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); Console.WriteLine("Option Set option order changed"); //</snippetWorkWithAttributes8> #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. _serviceProxy.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); //</snippetWorkWithAttributes1> 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; } }
/// <summary> /// Create 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(); //<snippetCreateCustomActivityEntity1> // The custom prefix would typically be passed in as an argument or // determined by the publisher of the custom solution. //<snippetCreateCustomActivityEntity2> String prefix = "new_"; String customEntityName = prefix + "instantmessage"; // Create the custom activity entity. CreateEntityRequest request = new CreateEntityRequest { HasNotes = true, HasActivities = false, PrimaryAttribute = new StringAttributeMetadata { SchemaName = "Subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) }, Entity = new EntityMetadata { IsActivity = true, SchemaName = customEntityName, DisplayName = new Label("Instant Message", 1033), DisplayCollectionName = new Label("Instant Messages", 1033), OwnershipType = OwnershipTypes.UserOwned, IsAvailableOffline = true, } }; _serviceProxy.Execute(request); //Entity must be published //</snippetCreateCustomActivityEntity2> // Add few attributes to the custom activity entity. CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontfamily", DisplayName = new Label("Font Family", 1033), MaxLength = 100 } }; CreateAttributeResponse fontFamilyAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontFamilyAttributeRequest); CreateAttributeRequest fontColorAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontcolor", DisplayName = new Label("Font Color", 1033), MaxLength = 50 } }; CreateAttributeResponse fontColorAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontColorAttributeRequest); CreateAttributeRequest fontSizeAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new IntegerAttributeMetadata { SchemaName = prefix + "fontSize", DisplayName = new Label("Font Size", 1033) } }; CreateAttributeResponse fontSizeAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute( fontSizeAttributeRequest); //</snippetCreateCustomActivityEntity1> Console.WriteLine("The custom activity has been created."); DeleteCustomEntity(prefix, 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; } }
/// <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 void CreateOptionSetField(JToken field) { CreateAttributeRequest req = new CreateAttributeRequest(); req.EntityName = field["entity"].ToString(); var am = new PicklistAttributeMetadata(); am.SchemaName = field["schemaname"].ToString(); am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); am.DisplayName = new Label(field["displayname"].ToString(), 1033); am.Description = new Label("", 1033); OptionSetMetadata os = new OptionSetMetadata(); os.IsGlobal = false; foreach (var option in field["options"]) { Label label = new Label(option["displayname"].ToString(), 1033); int? value = JSONUtil.GetInt32(option, "value"); os.Options.Add(new OptionMetadata(label, value)); } am.OptionSet = os; req.Attribute = am; this._cdsConnection.Execute(req); }
private void CreateNewDummySavingAttribute(pavelkh_advancedmultiselectitemsetconfiguration itemSetConfig) { const int LangCode = 1033; try { var schemaName = itemSetConfig.pavelkh_NewDummySavingField.Trim(); var request = new CreateAttributeRequest { EntityName = itemSetConfig.pavelkh_EntityName, Attribute = new StringAttributeMetadata { SchemaName = schemaName, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = StringFormat.Text, MaxLength = itemSetConfig.pavelkh_NewDummySavingAttributeLength, DisplayName = new Label(itemSetConfig.pavelkh_NewDummySavingFieldDisplayName, LangCode), Description = new Label("Dummy Saving Attribute for AdvancedMultiSelect.", LangCode), IsValidForAdvancedFind = new BooleanManagedProperty(false), IsAuditEnabled = new BooleanManagedProperty(false), } }; var pluginContext = this.PluginContext; pluginContext.Trace($"Creating a new Dummy Saving Attribute ({schemaName})"); var service = pluginContext.Service; service.Execute(request); MetadataUtils.PublishEntity(service, itemSetConfig.pavelkh_EntityName); } catch (Exception exc) { throw new InvalidPluginExecutionException( $"Error while creating a new field. Please check, perhaps a field with such name already exists.\n{exc.Message}"); } }
private void CreateDateTimeField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); CreateAttributeRequest req = new CreateAttributeRequest(); req.EntityName = entitySchemaName; var dta = new DateTimeAttributeMetadata(); dta.SchemaName = fieldSchemaName; dta.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); var datetimeoption = JSONUtil.GetText(field, "datetimeoption"); if (datetimeoption == null) { datetimeoption = "dateonly"; } if (datetimeoption == "dateonly") { dta.Format = DateTimeFormat.DateOnly; } else if (datetimeoption == "datetime") { dta.Format = DateTimeFormat.DateAndTime; } dta.DisplayName = new Label(displayName, 1033); dta.Description = new Label("", 1033); req.Attribute = dta; this._cdsConnection.Execute(req); }
private void CreateBooleanField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); CreateAttributeRequest req = new CreateAttributeRequest(); req.EntityName = entitySchemaName; var am = new BooleanAttributeMetadata(); am.SchemaName = fieldSchemaName; am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); am.DisplayName = new Label(displayName, 1033); am.Description = new Label("", 1033); am.OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("Yes", 1033), 1), new OptionMetadata(new Label("No", 1033), 0)); req.Attribute = am; this._cdsConnection.Execute(req); }
/// <summary> /// 创建Floating Point Number字段 /// </summary> public OrganizationResponse CreateFloatingPointNumberField( string entityName, string schemName, string displayName, string decription, double?minValue, double?maxValue, AttributeRequiredLevel requiredLevel) { var request = new CreateAttributeRequest { EntityName = entityName, Attribute = new DoubleAttributeMetadata() { SchemaName = schemName, RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), DisplayName = new Label(displayName, 1033), Description = new Label(decription, 1033), MinValue = minValue, MaxValue = maxValue } }; return(Service.Execute(request)); }
/// <summary> /// 创建OptionSet字段 /// </summary> public OrganizationResponse CreateOptionSetField( string entityName, string schemName, string displayName, string decription, IDictionary <string, int> options, bool isGlobal, AttributeRequiredLevel requiredLevel) { OptionMetadataCollection collection = GetOptionMetadataCollection(options); var request = new CreateAttributeRequest { EntityName = entityName, Attribute = new PicklistAttributeMetadata() { SchemaName = schemName, RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), DisplayName = new Label(displayName, 1033), Description = new Label(decription, 1033), OptionSet = new OptionSetMetadata(collection) { IsGlobal = isGlobal } } }; return(Service.Execute(request)); }
/// <summary> /// 创建Two Options字段 /// </summary> public OrganizationResponse CreateTwoOptionsField( string entityName, string schemName, string displayName, string decription, IDictionary <string, int> options, AttributeRequiredLevel requiredLevel) { if (options.Count != 2) { throw new ArgumentException("The options argument should have two options"); } OptionMetadataCollection collection = GetOptionMetadataCollection(options); var request = new CreateAttributeRequest { EntityName = entityName, Attribute = new BooleanAttributeMetadata() { SchemaName = schemName, RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), DisplayName = new Label(displayName, 1033), Description = new Label(decription, 1033), OptionSet = new BooleanOptionSetMetadata( collection[0], // true option collection[1] // false option ) } }; return(Service.Execute(request)); }
private void addCreateRequest(string[] row, List <CrmOperation> crmOp) { IEnumerable <IExtensibleDataObject> attrMetadataList = attributeReader(row); foreach (var attrMetadata in attrMetadataList) { if (attrMetadata != null) { if (attrMetadata is AttributeMetadata) { CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = filteredMetadata[0].EntityLogicalName, Attribute = attrMetadata as AttributeMetadata, SolutionUniqueName = GlobalApplicationData.Instance.currentSolution.SolutionName }; crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.create, CrmOperation.CrmOperationTarget.attribute, createAttributeRequest, "Create field " + ((AttributeMetadata)attrMetadata).SchemaName + " in " + filteredMetadata[0].EntityLogicalName)); } else if (attrMetadata is CreateOneToManyRequest) { string outputstring = string.Format("Create relation {0} -> {1}", ((CreateOneToManyRequest)attrMetadata).OneToManyRelationship.ReferencingEntity, ((CreateOneToManyRequest)attrMetadata).OneToManyRelationship.ReferencedEntity); crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.create, CrmOperation.CrmOperationTarget.attribute, attrMetadata as CreateOneToManyRequest, outputstring)); } else if (attrMetadata is InsertOptionValueRequest) { string outputstring = string.Format("Insert Option to {0} Text: {1}", ((InsertOptionValueRequest)attrMetadata).OptionSetName, Utils.getLocalizedLabel(((InsertOptionValueRequest)attrMetadata).Label.LocalizedLabels, languageCode)); crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.create, CrmOperation.CrmOperationTarget.attribute, attrMetadata as InsertOptionValueRequest, outputstring)); } } } }
protected override void ProcessRecord() { base.ProcessRecord(); CreateAttributeRequest request; try { request = new CreateAttributeRequest { CatalogId = CatalogId, DataAssetKey = DataAssetKey, EntityKey = EntityKey, CreateAttributeDetails = CreateAttributeDetails, OpcRequestId = OpcRequestId, OpcRetryToken = OpcRetryToken }; response = client.CreateAttribute(request).GetAwaiter().GetResult(); WriteOutput(response, response.Attribute); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
//code to autopopulate Mortgage Number field in Mortgage request entity, only needed to be run once for this take affect public void autoPopulateMortgageNumber() { CrmServiceClient client = new CrmServiceClient("Url=https://revaturefinalproj.crm.dynamics.com; [email protected]; Password=Revature2018!; authtype=Office365"); IOrganizationService service = (IOrganizationService) client.OrganizationWebProxyClient != null ? (IOrganizationService)client.OrganizationWebProxyClient : (IOrganizationService)client.OrganizationServiceProxy; CreateAttributeRequest widgetSerialNumberAttributeRequest = new CreateAttributeRequest { EntityName = "revfinal_mortgage", Attribute = new StringAttributeMetadata { //Define the format of the attribute AutoNumberFormat = "{DATETIMEUTC:yyyyMMddhhmm}", LogicalName = "revfinal_mortgagenumber", SchemaName = "revfinal_mortgagenumber", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, // The MaxLength defined for the string attribute must be greater than the length of the AutoNumberFormat value, that is, it should be able to fit in the generated value. DisplayName = new Label("Mortgage Number", 1033), Description = new Label("Mortgage Number of the Mortgage Application.", 1033) } }; service.Execute(widgetSerialNumberAttributeRequest); }
static void CriarAtributo(OrganizationServiceProxy serviceProxy) { CreateAttributeRequest create = new CreateAttributeRequest { EntityName = "new_bankaccount", 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), } }; try { serviceProxy.Execute(create); Console.WriteLine("Atributo criado com sucesso!!"); } catch (Exception ex) { Console.WriteLine("Erro ao criar Atributo:" + ex.Message.ToString()); } }
protected void Run_Work_AutoNumber(IOrganizationService service) { string prefix = "WRK"; Helper help = new Helper(); CreateAttributeRequest autonum = help.AutoNumber(prefix, workEntityName); service.Execute(autonum); }
public void Run() { //[ONPREM] string connectionString = @"AuthType=IFD;Url=https://dyncrmsql:444/CRM;Username=contoso\\Administrator;Password=***!"; // Custom entity required: // Entity name: new_test // Default field: name // Custom fields: // content (multi-line text) string connectionString = @"AuthType=Office365;Url=https://fiscalnet.crm.dynamics.com;[email protected];Password=Itadow29"; CrmServiceClient proxy = new CrmServiceClient(connectionString); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Creating AutoNumber attribute CreateAttributeRequest testAttributeRequest = new CreateAttributeRequest { EntityName = "new_test", Attribute = new StringAttributeMetadata { //Define the format of the attribute. Main documentation is here: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/create-auto-number-attributes AutoNumberFormat = "TST2-{SEQNUM:5}", LogicalName = "new_serialnumber2", SchemaName = "new_SerialNumber2", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, // The MaxLength defined for the string attribute must be greater than the length of the AutoNumberFormat value, that is, it should be able to fit in the generated value. DisplayName = new Label("Serial Number 2", 1033), Description = new Label("Serial Number of the test 2.", 1033) } }; proxy.Execute(testAttributeRequest); Console.Out.WriteLine("AutoNumber Attribute has been created..."); //Creating a new record Random r = new Random(); Entity e = new Entity("new_test"); e["new_name"] = "New record " + String.Format("{0:00000}", r.Next(1000, 10000)); e["new_content"] = "All we need is less..."; Guid newRecordId = proxy.Create(e); // When creating the record, the new attribute is auto-populated following the specified pattern Console.Out.WriteLine(String.Format("New entity {0} record has been created...", newRecordId.ToString())); // Retrieving the just created record using the Guid returned by the create method Entity e2 = proxy.Retrieve("new_test", newRecordId, new ColumnSet(true)); Console.Out.WriteLine("Retrieving new record..."); Console.Out.WriteLine(String.Format("Name = {0}", e2["new_name"].ToString())); Console.Out.WriteLine(String.Format("content = {0}", e2["new_content"].ToString())); Console.Out.WriteLine(String.Format("AutoNumber = {0}", e2["new_serialnumber2"].ToString())); Console.Out.WriteLine("Press any key to end..."); Console.ReadKey(); }
public static void DotsTwitterPublisher() { // Create the custom entity. CreateEntityRequest createRequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _custom_PublisherEntityName, DisplayName = new Label("DS Twitter Publisher", 1033), DisplayCollectionName = new Label("Twitter Publisher", 1033), Description = new Label("An entity to store information about Publisher a entity.", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, //CanCreateForms = new BooleanManagedProperty(true), }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "dots_alias", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.SystemRequired), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Alias", 1033), Description = new Label("The primary attribute for the dots_twitterpublisher entity.", 1033), } }; _serviceProxy.Execute(createRequest); // Add some attributes to the entity CreateAttributeRequest createMediaAttributeRequest = new CreateAttributeRequest { EntityName = _custom_PublisherEntityName, Attribute = new PicklistAttributeMetadata { SchemaName = "dots_media", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.SystemRequired), OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Twitter", 1033), 1), } }, DisplayName = new Label("Media", 1033), Description = new Label("The Media type like twitter.", 1033), } }; _serviceProxy.Execute(createMediaAttributeRequest); }
public SingleResponse Create(string repoName, CreateAttributeRequest request) { Uri endpoint = ApiUris.GetFullUri( mBaseUri, ApiEndpoints.CreateAttribute, repoName); string actionDescription = string.Format( "create attribute name {0} on repo {1}", request.Name, repoName); return(Internal.MakeApiRequest <CreateAttributeRequest, SingleResponse>( endpoint, HttpMethod.Post, request, actionDescription, mApiKey)); }
public override void CreateAttribute(IOrganizationService service) { var attribute = GetAttributeMetadata(); var request = new CreateAttributeRequest { EntityName = Entity, Attribute = attribute }; service.Execute(request); }
static void Main(string[] args) { try { CrmServiceClient crmServiceClientObj = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CrmOnlineStringFromAppConfig"].ConnectionString); if (!crmServiceClientObj.IsReady) { Console.WriteLine("No Connection was Made."); } Console.WriteLine("Connected"); Console.WriteLine("Creating Auto number Attribute for Entity {0}", entityName); var attributeMetaData = new StringAttributeMetadata() { //{DATETIMEUTC:yyyyMMddhhmmss} can also be used AutoNumberFormat = "SYS {RANDSTRING:4} - ORG {SEQNUM:4}", //this should be unique SchemaName = "new_AutoNumAtt", //set it as per required RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), //Lable Name DisplayName = new Microsoft.Xrm.Sdk.Label("Entity Code", 1033), // On hover description Description = new Microsoft.Xrm.Sdk.Label("The value will be AUTO GENERATED", 1033), IsAuditEnabled = new Microsoft.Xrm.Sdk.BooleanManagedProperty(false), // we need it to be searched direclty from global search. IsGlobalFilterEnabled = new Microsoft.Xrm.Sdk.BooleanManagedProperty(true), MaxLength = 100 // }; CreateAttributeRequest req = new CreateAttributeRequest() { EntityName = entityName, Attribute = attributeMetaData }; crmServiceClientObj.Execute(req); Console.WriteLine("Created Auto number Attribute for Entity {0}", entityName); Console.ReadLine(); } catch (Exception e) { Console.WriteLine("Error here. " + e.Message); Console.ReadLine(); } }
private void CreatePickLIst(string pEntity) { foreach (var _rows in _dataset.Tables[0].Rows) { this._row = ((DataRow)_rows); this._options = this._row[7].ToString().Replace("\n", "|"); GetOptions(); switch (this._row[5]) { case "None": _requiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); break; case "ApplicationRequired": _requiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired); break; } try { PicklistAttributeMetadata dxPicklistAttributeMetadata = new PicklistAttributeMetadata { SchemaName = this._row[1].ToString(), DisplayName = new Microsoft.Xrm.Sdk.Label(this._row[2].ToString(), 1033), Description = new Microsoft.Xrm.Sdk.Label(this._row[4].ToString(), 1033), RequiredLevel = this._requiredLevel, OptionSet = this._optionMetadata }; AttributeMetadata attributeMetadata = dxPicklistAttributeMetadata; CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = pEntity, Attribute = attributeMetadata, }; _crmsvc.OrganizationServiceProxy.Execute(createBankNameAttributeRequest); ColorConsole.WriteLine($"Create done { this._row[1].ToString() }".Red().OnGreen()); } catch (Exception ex) { ColorConsole.WriteLine($"Create has an error {ex.Message}".Yellow().OnDarkRed()); logger.Error(ex.Message); } } }
private void CreateTextField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); var req = new CreateAttributeRequest(); req.EntityName = entitySchemaName; var format = JSONUtil.GetText(field, "format"); if (format == null) { format = "single"; } int?maxlength = JSONUtil.GetInt32(field, "maxlength"); if (format == "single") { var am = new StringAttributeMetadata(); am.SchemaName = field["schemaname"].ToString(); am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); maxlength = maxlength == null ? 100 : maxlength; am.MaxLength = maxlength; am.FormatName = StringFormatName.Text; am.DisplayName = new Label(displayName, 1033); am.Description = new Label("", 1033); req.Attribute = am; } else if (format == "multi") { var am = new MemoAttributeMetadata(); am.SchemaName = fieldSchemaName; am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); maxlength = maxlength == null ? 2000 : maxlength; am.MaxLength = maxlength; am.DisplayName = new Label(displayName, 1033); am.Description = new Label("", 1033); req.Attribute = am; } this._cdsConnection.Execute(req); }
public static void DotsAutoNumberConfigurationEntity() { // Create the custom entity. CreateEntityRequest createRequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customConfigurationEntityName, DisplayName = new Label("DS AutoSMS Configuration", 1033), DisplayCollectionName = new Label("Auto SMS Configuration", 1033), Description = new Label("An entity to store information about autosms configuration for particular entity.", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, //CanCreateForms = new BooleanManagedProperty(true), }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "dots_type", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Type", 1033), Description = new Label("The primary attribute for the dots_autonumber configuration entity.", 1033), } }; _serviceProxy.Execute(createRequest); // Add some attributes to the dots_autonumber entity CreateAttributeRequest createPlaceHolderAttributeRequest = new CreateAttributeRequest { EntityName = _customConfigurationEntityName, Attribute = new StringAttributeMetadata { SchemaName = "dots_value", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 500, FormatName = StringFormatName.Text, DisplayName = new Label("Value", 1033), Description = new Label("The Value for Security", 1033), } }; _serviceProxy.Execute(createPlaceHolderAttributeRequest); }
public void CreateAttribute(string logicalname, string displayname, string type, string requirement) { var requiredlevel = AttributeRequiredLevel.None; Enum.TryParse(requirement, out requiredlevel); var attribute = GetAttributeMetadata(type, logicalname, displayname, requiredlevel); var request = new CreateAttributeRequest { EntityName = entity, Attribute = attribute }; service.Execute(request); }
internal static bool CreateAttribute( RestApi restApi, string repoName, string attributeName, string attributeComment) { CreateAttributeRequest request = new CreateAttributeRequest() { Name = attributeName, Comment = attributeComment }; SingleResponse response = restApi.Attributes.Create(repoName, request); return(GetBoolValue(response.Value, false)); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create custom fields in account entity // Create secure custom field #1 CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "secret_home", DisplayName = new Label("SecretHome", 1033), SchemaName = "Secret_Home", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = Account.EntityLogicalName }; CreateAttributeResponse attributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _secretHomeId = attributeResponse.AttributeId; Console.WriteLine("Secret_Home custom field created."); // Create secure custom field #2 attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "secret_phone", DisplayName = new Label("SecretPhone", 1033), SchemaName = "Secret_Phone", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = Account.EntityLogicalName }; attributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _secretPhoneId = attributeResponse.AttributeId; Console.WriteLine("Secret_Phone custom field created."); #endregion Create custom fields in account entity Console.WriteLine(); }
/// <summary> /// 创建示例字段 /// </summary> /// <param name="entityName">Entity的LogicalName</param> /// <param name="schemName">Field的SchemName</param> /// <param name="displayName">Field的DisplayName</param> /// <param name="decription">Field的描述</param> /// <param name="requiredLevel">Field的</param> public OrganizationResponse CreateSampleField(string entityName, string schemName, string displayName, string decription, AttributeRequiredLevel requiredLevel) { var request = new CreateAttributeRequest { EntityName = entityName, Attribute = new StringAttributeMetadata { SchemaName = schemName, RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), MaxLength = 100, Format = StringFormat.Text, DisplayName = new Label(displayName, 1033), Description = new Label(decription, 1033) } }; return(Service.Execute(request)); }
private static string CreateAttribute(string entityName, List <AttributeMetadata> addedAttributes, string solutionName, IOrganizationService service) { string createAttribute = string.Empty; foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = entityName, Attribute = anAttribute, SolutionUniqueName = solutionName }; // Execute the request. service.Execute(createAttributeRequest); } createAttribute = String.Format("Created the attributes for {0}.", entityName); return(createAttribute); }
private bool CreateAttributes(IOrganizationService service, XRMSpeedyEntity entity, int languageCode) { try { foreach (XRMSpeedyField field in entity.Fields.Where(f => f.Import == true)) { CreateAttributeRequest request = new CreateAttributeRequest { EntityName = entity.EntityMetadata.SchemaName, Attribute = field.AttributeMetadata }; CreateAttributeResponse response = (CreateAttributeResponse)service.Execute(request); } return(true); } catch (FaultException <OrganizationServiceFault> ) { throw; } }
public CreateAttributeRequest AutoNumber(string prefix, string entityName) { CreateAttributeRequest widgetSerialNumberAttributeRequest = new CreateAttributeRequest { EntityName = entityName, Attribute = new StringAttributeMetadata { //Define the format of the attribute AutoNumberFormat = prefix + "-{SEQNUM:3}-{RANDSTRING:6}-{DATETIMEUTC:yyyyMMddhhmmss}", LogicalName = "new_serialnumber", SchemaName = "new_SerialNumber", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, // The MaxLength defined for the string attribute must be greater than the length of the AutoNumberFormat value, that is, it should be able to fit in the generated value. DisplayName = new Label("Serial Number", 1033), Description = new Label("Serial Number of the widget.", 1033) } }; //_serviceProxy.Execute(widgetSerialNumberAttributeRequest); return(widgetSerialNumberAttributeRequest); }
private void CreateMoneyField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); CreateAttributeRequest req = new CreateAttributeRequest { EntityName = entitySchemaName, Attribute = new MoneyAttributeMetadata { SchemaName = fieldSchemaName, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label(displayName, 1033), Description = new Label("", 1033), } }; this._cdsConnection.Execute(req); }
public void UpdateEntities() { foreach (string item in this._logicalNames) { CreateAttributeRequest req = new CreateAttributeRequest { EntityName = item, Attribute = new BooleanAttributeMetadata { SchemaName = "gsc_IsGlobalRecord", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Is Global Record?", 1033), Description = new Label("This field identifies if record is global. Global records are the records created by MMPC.", 1033), OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", 1033), 1), new OptionMetadata(new Label("False", 1033), 0) ) } }; var entityResponse = _service.Execute(req); } }
private void CreateIntegerField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); CreateAttributeRequest req = new CreateAttributeRequest { EntityName = entitySchemaName, Attribute = new IntegerAttributeMetadata { SchemaName = fieldSchemaName, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), //MaxValue = field.MaxValue == null ? null : field.MaxValue, //MinValue = field.MinValue == null ? null : field.MinValue, DisplayName = new Label(displayName, 1033), Description = new Label("", 1033) } }; this._cdsConnection.Execute(req); }
/// <summary> /// Ensures that a govd_id to hold GovDelivery email IDs exists on email activities /// </summary> /// <returns></returns> public void EnsureEmailGovdeliveryField() { AttributeMetadata[] emailMetadataAttributes = this.retrieveMetadataAttributes("email"); if (!emailMetadataAttributes.Any(prop => prop.LogicalName.Equals("govd_id"))) { CreateAttributeRequest createGovDeliveryRequest = new CreateAttributeRequest { EntityName = "email", Attribute = new StringAttributeMetadata() { SchemaName = "govd_id", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("GovDelivery Message Id", 1033), Description = new Label("The GovDelivery Transactional Message ID for tracking purposes.", 1033) } }; this.getService().Execute(createGovDeliveryRequest); } }
//</snippetremoveOptionLabelsFromCache> protected void addCustomEntityWithOptionSet() { String primaryAttributeSchemaName = "sample_SampleEntityForMetadataQueryName"; CreateEntityRequest createEntityRequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntitySchemaName, LogicalName = _customEntitySchemaName.ToLower(), DisplayName = new Label("Entity for MetadataQuery Sample", _languageCode), DisplayCollectionName = new Label("Entity for MetadataQuery Sample", _languageCode), Description = new Label("An entity created for the MetadataQuery Sample", _languageCode), OwnershipType = OwnershipTypes.UserOwned, IsVisibleInMobile = new BooleanManagedProperty(true), IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = primaryAttributeSchemaName, LogicalName = primaryAttributeSchemaName.ToLower(), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, Format = StringFormat.Text, DisplayName = new Label("Entity for MetadataQuery Sample Name", _languageCode), Description = new Label("The primary attribute for the Bank Account entity.", _languageCode) } }; _service.Execute(createEntityRequest); //PublishXmlRequest publishXmlRequest = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", _customEntitySchemaName.ToLower()) }; //_service.Execute(publishXmlRequest); //Add an optionset attribute CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = _customEntitySchemaName.ToLower(), Attribute = new PicklistAttributeMetadata { SchemaName = _customAttributeSchemaName, DisplayName = new Label("Example OptionSet for MetadataQuery Sample", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("First Option",_languageCode),null), new OptionMetadata(new Label("Second Option",_languageCode),null), new OptionMetadata(new Label("Third Option",_languageCode),null), new OptionMetadata(new Label("Fourth Option",_languageCode),null) } } } }; _service.Execute(createAttributeRequest); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a FieldSecurityProfile object is created and tied to an existing team. Then a /// custom entity and several attributes are created and FieldPermission is /// assigned to the Identity attribute of the new 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 { //<snippetEnableFieldSecurityForAnEntity1> // 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(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); //<snippetEnableFieldSecurityForAnEntity2> // Create the request object and set the monikers with the // teamprofiles_association relationship. AssociateRequest teamToProfile = new AssociateRequest { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; // Execute the request. _serviceProxy.Execute(teamToProfile); //</snippetEnableFieldSecurityForAnEntity2> // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false) }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; // Execute the request. _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Create custom attributes. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; // Execute the request. CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; // Execute the request. CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create the field permission for the Identity attribute. FieldPermission identityPermission = new FieldPermission() { AttributeLogicalName = "new_identity", EntityName = "new_tweet", CanRead = new OptionSetValue(FieldPermissionType.Allowed), FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId) }; // Execute the request _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created. "); DeleteRequiredRecords(promptforDelete); } //</snippetEnableFieldSecurityForAnEntity1> } // 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 CreateAttributeRequest GetCreateAttributeRequest(string entityLogicalName, AttributeTemplate attributeTemplate) { if (attributeTemplate.AttributeType == typeof(Primary)) { return null; } var createAttributeRequest = new CreateAttributeRequest {EntityName = entityLogicalName}; if (attributeTemplate.AttributeType == typeof (string)) { createAttributeRequest.Attribute = CreateStringAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (int)) { createAttributeRequest.Attribute = CreateIntAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (decimal)) { createAttributeRequest.Attribute = CreateDecimalAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (OptionSet)) { createAttributeRequest.Attribute = CreateOptionSetAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (GlobalOptionSet)) { createAttributeRequest.Attribute = CreateGlobalOptionSetAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (bool)) { createAttributeRequest.Attribute = CreateBoolAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (Money)) { createAttributeRequest.Attribute = CreateMoneyAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (DateTime)) { createAttributeRequest.Attribute = CreateDateTimeAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof (Multiline)) { createAttributeRequest.Attribute = CreateMultilineAttributeMetadata(attributeTemplate); } else if (attributeTemplate.AttributeType == typeof(float)) { createAttributeRequest.Attribute = CreateFloatAttributeMetadata(attributeTemplate); } else { var exception = new Exception(string.Format("Given attribute type is not supported. Type: {0}", attributeTemplate.AttributeType)); errorList.Add(exception); return null; } createAttributeRequest.Attribute.SchemaName = attributeTemplate.LogicalName; createAttributeRequest.Attribute.RequiredLevel = new AttributeRequiredLevelManagedProperty(attributeTemplate.IsRequired ? AttributeRequiredLevel.SystemRequired : AttributeRequiredLevel.None); createAttributeRequest.Attribute.DisplayName = GetLabelWithLocalized(attributeTemplate.DisplayNameShort); createAttributeRequest.Attribute.Description = GetLabelWithLocalized(attributeTemplate.Description); if(!string.IsNullOrWhiteSpace(attributeTemplate.OtherDisplayName)) { var otherDisplayLabel = new LocalizedLabel(attributeTemplate.OtherDisplayName, DefaultConfiguration.OtherLanguageCode); createAttributeRequest.Attribute.DisplayName.LocalizedLabels.Add(otherDisplayLabel); } if (!string.IsNullOrWhiteSpace(attributeTemplate.OtherDescription)) { var otherDescriptionLabel = new LocalizedLabel(attributeTemplate.OtherDescription, DefaultConfiguration.OtherLanguageCode); createAttributeRequest.Attribute.Description.LocalizedLabels.Add(otherDescriptionLabel); } return createAttributeRequest; }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Link the custom attributes. /// 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(); //<snippetLinkCustomAttributesBetweenSeriesandInstances1> // Create a custom string attribute for the appointment instance StringAttributeMetadata customAppointmentInstanceAttribute = new StringAttributeMetadata { LogicalName = "new_customAppInstanceAttribute", DisplayName = new Label("CustomAppInstanceAttribute", 1033), Description = new Label("Sample Custom Appointment Instance Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppInstanceAttribute" }; CreateAttributeRequest instanceAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentInstanceAttribute, EntityName = "appointment" }; CreateAttributeResponse instanceAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(instanceAttributeRequest); _instanceAttributeID = instanceAttributeResponse.AttributeId; // Create a custom string attribute for the recurring appointment master (series) StringAttributeMetadata customAppointmentSeriesAttribute = new StringAttributeMetadata { LogicalName = "new_customAppSeriesAttribute", DisplayName = new Label("CustomAppSeriesAttribute", 1033), Description = new Label("Sample Custom Appointment Series Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppSeriesAttribute", LinkedAttributeId = _instanceAttributeID // Link the custom attribute to the appointment’s custom attribute. }; CreateAttributeRequest seriesAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentSeriesAttribute, EntityName = "recurringappointmentmaster" }; CreateAttributeResponse seriesAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(seriesAttributeRequest); _seriesAttributeID = seriesAttributeResponse.AttributeId; // Publish all the changes to the solution. PublishAllXmlRequest createRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(createRequest); Console.WriteLine("Created a custom string attribute, {0}, for the appointment.", customAppointmentInstanceAttribute.LogicalName); Console.WriteLine("Created a custom string attribute, {0}, for the recurring appointment, and linked it with {1}.", customAppointmentSeriesAttribute.LogicalName, customAppointmentInstanceAttribute.LogicalName); //</snippetLinkCustomAttributesBetweenSeriesandInstances1> 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; } }
/// <summary> /// Create a custom entity that can be used in the To field of an email activity. /// 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(); //<snippetCreateUpdateEmailableEntity1> // Create the custom entity. CreateEntityRequest createrequest = new CreateEntityRequest { // Define an entity to enable for emailing. In order to do so, // IsActivityParty must be set. Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Agent", 1033), DisplayCollectionName = new Label("Agents", 1033), Description = new Label("Insurance Agents", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, // Unless this flag is set, this entity cannot be party to an // activity. IsActivityParty = true }, // As with built-in emailable entities, the Primary Attribute will // be used in the activity party screens. Be sure to choose descriptive // attributes. PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_fullname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Agent Name", 1033), Description = new Label("Agent Name", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The emailable entity has been created."); // The entity will not be selectable as an activity party until its customizations // have been published. Otherwise, the e-mail activity dialog cannot find // a correct default view. PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); // Before any emails can be created for this entity, an Email attribute // must be defined. CreateAttributeRequest createFirstEmailAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_emailaddress", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Email, DisplayName = new Label("Email Address", 1033), Description = new Label("Email Address", 1033) } }; _serviceProxy.Execute(createFirstEmailAttributeRequest); Console.WriteLine("An email attribute has been added to the emailable entity."); // Create a second, alternate email address. Since there is already one // email attribute on the entity, this will never be used for emailing // even if the first one is not populated. CreateAttributeRequest createSecondEmailAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_secondaryaddress", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Email, DisplayName = new Label("Secondary Email Address", 1033), Description = new Label("Secondary Email Address", 1033) } }; _serviceProxy.Execute(createSecondEmailAttributeRequest); Console.WriteLine("A second email attribute has been added to the emailable entity."); //</snippetCreateUpdateEmailableEntity1> 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 void CreateOrUpdateAttribute(string schemaName, string recordType, AttributeMetadata metadata) { lock (LockObject) { if (FieldExists(schemaName, recordType)) { var request = new UpdateAttributeRequest { EntityName = recordType, Attribute = metadata, }; Execute(request); RefreshFieldMetadata(schemaName, recordType); } else { var request = new CreateAttributeRequest { EntityName = recordType, Attribute = metadata }; Execute(request); RefreshFieldMetadata(schemaName, recordType); } } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateImageAttributeDemoEntity() { //Create a Custom entity CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Image Attribute Demo", 1033), DisplayCollectionName = new Label("Image Attribute Demos", 1033), Description = new Label("An entity created by an SDK sample to demonstrate how to upload and retrieve entity images.", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "sample_Name", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Name", 1033), Description = new Label("The primary attribute for the Image Attribute Demo entity.", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The Image Attribute Demo entity has been created."); //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.ToLower(), Attribute = new ImageAttributeMetadata { SchemaName = "EntityImage", //The name is always EntityImage //Required level must be AttributeRequiredLevel.None RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Image", 1033), Description = new Label("An image to show with this demonstration.", 1033) } }; _serviceProxy.Execute(createEntityImageRequest); Console.WriteLine("The Image attribute has been created."); //<snippetEntityImages5> QueryExpression qe = new QueryExpression("systemform"); qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2); //main form qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, _customEntityName.ToLower()); qe.ColumnSet.AddColumn("formxml"); SystemForm ImageAttributeDemoMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0]; XDocument ImageAttributeDemoMainFormXml = XDocument.Parse(ImageAttributeDemoMainForm.FormXml); //Set the showImage attribute so the entity image will be displayed ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", true); //Updating the entity form definition ImageAttributeDemoMainForm.FormXml = ImageAttributeDemoMainFormXml.ToString(); _serviceProxy.Update(ImageAttributeDemoMainForm); //</snippetEntityImages5> Console.WriteLine("The Image Attribute Demo main form has been updated to show images."); PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format(@" <importexportxml> <entities> <entity>{0}</entity> </entities> </importexportxml>", _customEntityName.ToLower()) }; _serviceProxy.Execute(pxReq1); Console.WriteLine("The Image Attribute Demo entity was published"); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a publisher /// Create a new solution, "Primary" /// Create a Global Option Set in solution "Primary" /// Export the "Primary" solution, setting it to Protected /// Delete the option set and solution /// Import the "Primary" solution, creating a managed solution in CRM. /// Create a new solution, "Secondary" /// Create an attribute in "Secondary" that references the Global Option Set /// </summary> public void CreateRequiredRecords() { //Create the publisher that will "own" the two solutions //<snippetGetSolutionDependencies6> Publisher publisher = new Publisher { UniqueName = "examplepublisher", FriendlyName = "An Example Publisher", Description = "This is an example publisher", CustomizationPrefix = _prefix }; _publisherId = _serviceProxy.Create(publisher); //</snippetGetSolutionDependencies6> //Create the primary solution - note that we are not creating it //as a managed solution as that can only be done when exporting the solution. //<snippetGetSolutionDependencies2> Solution primarySolution = new Solution { Version = "1.0", FriendlyName = "Primary Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId), UniqueName = _primarySolutionName }; _primarySolutionId = _serviceProxy.Create(primarySolution); //</snippetGetSolutionDependencies2> //Now, create the Global Option Set and associate it to the solution. //<snippetGetSolutionDependencies3> OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option 1", _languageCode), 1), new OptionMetadata(new Label("Option 2", _languageCode), 2) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata }; createOptionSetRequest.SolutionUniqueName = _primarySolutionName; _serviceProxy.Execute(createOptionSetRequest); //</snippetGetSolutionDependencies3> //Export the solution as managed so that we can later import it. //<snippetGetSolutionDependencies4> ExportSolutionRequest exportRequest = new ExportSolutionRequest { Managed = true, SolutionName = _primarySolutionName }; ExportSolutionResponse exportResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportRequest); //</snippetGetSolutionDependencies4> // Delete the option set previous created, so it can be imported under the // managed solution. //<snippetGetSolutionDependencies5> DeleteOptionSetRequest deleteOptionSetRequest = new DeleteOptionSetRequest { Name = _globalOptionSetName }; _serviceProxy.Execute(deleteOptionSetRequest); //</snippetGetSolutionDependencies5> // Delete the previous primary solution, so it can be imported as managed. _serviceProxy.Delete(Solution.EntityLogicalName, _primarySolutionId); _primarySolutionId = Guid.Empty; // Re-import the solution as managed. ImportSolutionRequest importRequest = new ImportSolutionRequest { CustomizationFile = exportResponse.ExportSolutionFile }; _serviceProxy.Execute(importRequest); // Retrieve the solution from CRM in order to get the new id. QueryByAttribute primarySolutionQuery = new QueryByAttribute { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet("solutionid"), Attributes = { "uniquename" }, Values = { _primarySolutionName } }; _primarySolutionId = _serviceProxy.RetrieveMultiple(primarySolutionQuery).Entities .Cast<Solution>().FirstOrDefault().SolutionId.GetValueOrDefault(); // Create a secondary solution. Solution secondarySolution = new Solution { Version = "1.0", FriendlyName = "Secondary Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId), UniqueName = "SecondarySolution" }; _secondarySolutionId = _serviceProxy.Create(secondarySolution); // Create a Picklist attribute in the secondary solution linked to the option set in the // primary - see WorkWithOptionSets.cs for more on option sets. PicklistAttributeMetadata picklistMetadata = new PicklistAttributeMetadata { SchemaName = _picklistName, LogicalName = _picklistName, DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } }; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = picklistMetadata }; createAttributeRequest["SolutionUniqueName"] = secondarySolution.UniqueName; _serviceProxy.Execute(createAttributeRequest); }
/// <summary> /// Create a global option set. /// Set the options for that option set. /// Create a new reference to that option set on an entity. /// Update the option set's properties. /// Check the global option set for dependencies. /// Delete the option set. /// </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(); //<snippetWorkwithGlobalOptionSets1> //<snippetWorkwithGlobalOptionSets2> #region How to create global option set // Define the request object and pass to the service. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = new OptionSetMetadata { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Open", _languageCode), null), new OptionMetadata(new Label("Suspended", _languageCode), null), new OptionMetadata(new Label("Cancelled", _languageCode), null), new OptionMetadata(new Label("Closed", _languageCode), null) } } }; // Execute the request. CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest); //</snippetWorkwithGlobalOptionSets2> #endregion How to create global option set // Store the option set's id as it will be needed to find all the // dependent components. _optionSetId = optionsResp.OptionSetId; Console.WriteLine("The global option set has been created."); #region How to create a picklist linked to the global option set //<snippetWorkwithGlobalOptionSets3> // Create a Picklist linked to the option set. // Specify which entity will own the picklist, and create it. CreateAttributeRequest createRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = new PicklistAttributeMetadata { SchemaName = "sample_examplepicklist", LogicalName = "sample_examplepicklist", DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), // In order to relate the picklist to the global option set, be sure // to specify the two attributes below appropriately. // Failing to do so will lead to errors. OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } } }; _serviceProxy.Execute(createRequest); //</snippetWorkwithGlobalOptionSets3> Console.WriteLine("Referring picklist attribute created."); #endregion How to create a picklist linked to the global option set #region How to update a global option set //<snippetWorkwithGlobalOptionSets4> // Use UpdateOptionSetRequest to update the basic information of an option // set. Updating option set values requires different messages (see below). UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; _serviceProxy.Execute(updateOptionSetRequest); //Publish the OptionSet PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq1); //</snippetWorkwithGlobalOptionSets4> Console.WriteLine("Option Set display name changed."); #endregion How to update a global option set properties #region How to insert a new option item in a global option set //<snippetWorkwithGlobalOptionSets5> // Use InsertOptionValueRequest to insert a new option into a // global option set. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = _globalOptionSetName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request and store the newly inserted option value // for cleanup, used in the later part of this sample. _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq2); //</snippetWorkwithGlobalOptionSets5> Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, _insertedOptionValue); #endregion How to insert a new option item in a global option set #region How to retrieve a global option set by it's name //<snippetWorkwithGlobalOptionSets6> // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute( retrieveOptionSetRequest); Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); //</snippetWorkwithGlobalOptionSets6> #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist //<snippetWorkwithGlobalOptionSets7> // In order to change labels on option set values (or delete) option set // values, you must use UpdateOptionValueRequest // (or DeleteOptionValueRequest). UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = _globalOptionSetName, // Update the second option value. Value = optionList[1].Value.Value, Label = new Label("Updated Option 1", _languageCode) }; _serviceProxy.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq3); //</snippetWorkwithGlobalOptionSets7> Console.WriteLine("Option Set option label changed."); #endregion How to update an option item in a picklist #region How to change the order of options of a global option set //<snippetWorkwithGlobalOptionSets8> // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. OptionSetName = _globalOptionSetName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq4); //</snippetWorkwithGlobalOptionSets8> Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set #region How to retrieve all global option sets //<snippetWorkwithGlobalOptionSets9> // Use RetrieveAllOptionSetsRequest to retrieve all global option sets. // Create the request. RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)_serviceProxy.Execute( retrieveAllOptionSetsRequest); // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to // work with all retrieved option sets. if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { Console.WriteLine("All the global option sets retrieved as below:"); int count = 1; foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata) { Console.WriteLine("{0} {1}", count++, (optionSetMetadata.DisplayName.LocalizedLabels.Count >0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); } } //</snippetWorkwithGlobalOptionSets9> #endregion How to retrieve all global option sets //</snippetWorkwithGlobalOptionSets1> 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; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// authorization profile is created, and associated to a team. Then an entity /// is created and permissions for the entity are assigned to the profile. These /// permissions are then retrieved. /// </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 { //<snippetRetrieveSecuredFieldsForAUser1> // 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(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; _serviceProxy.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; _serviceProxy.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)_serviceProxy.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List<Guid> profileIds = new List<Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection<Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = _serviceProxy.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveSecuredFieldsForAUser1> } // 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; } }