private static void CreateGlobalOptionSet( string logicalName, string displayName, IList <OptionMetadata> optionMetadata) { CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = new OptionSetMetadata(new OptionMetadataCollection(optionMetadata)) { Name = logicalName, DisplayName = new Label(displayName, _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist } }; try { var optionsResp = (CreateOptionSetResponse)_organizationService.Execute(createOptionSetRequest); ExConsole.WriteLineColor( $"Created global option set {displayName} ({logicalName}) with id {optionsResp.OptionSetId}", ConsoleColor.Green); } catch (FaultException <OrganizationServiceFault> ex) { ExConsole.WriteLineColor( $"Could not create global option set {logicalName}: {ex.Message}", ConsoleColor.Red); } }
/// <summary> /// Global OptionSet 생성 /// </summary> /// <param name="dto"></param> public void CreateGlobalOptionSet(DtoOptionSet dto) { try { OptionSetMetadata setupOptionSetMetadata = GetSetupOptionSetMetadata(dto); // Wrap the OptionSetMetadata in the appropriate request. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { SolutionUniqueName = !string.IsNullOrEmpty(_solutionName) ? _solutionName : null, OptionSet = setupOptionSetMetadata }; // Pass the execute statement to the CRM service. OrganizationResponse responseFromUpdateOptionSet = _orgService.Execute(createOptionSetRequest); //foreach (var r in response.Results) //{ // Console.WriteLine(r.Value.ToString()); //} OrganizationResponse responseFromOptions = InsertOrUpdateForOptionSetOptions(dto); } catch (Exception) { throw; } }
/// <summary> /// Shows how to create an 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(); //<snippetCreateOptionSet1> // Define the option set to create. OptionSetMetadata setupOptionSetMetadata = new OptionSetMetadata() { // The name will be used to uniquely identify the option set. // Normally you should generate this identifier using the publisher's // prefix and double-check that the name is not in use. Name = _optionSetName, DisplayName = new Label("Example Option Set", _languageCode), Description = new Label("An Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, // Define the list of options that populate the option set // The order here determines the order shown in the option set. Options = { // Options accepts any number of OptionMetadata instances, which // are simply pairs of Labels and integer values. new OptionMetadata(new Label("Option 1", _languageCode), null), new OptionMetadata(new Label("Option 2", _languageCode), null) } }; // Wrap the OptionSetMetadata in the appropriate request. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = setupOptionSetMetadata }; // Pass the execute statement to the CRM service. _serviceProxy.Execute(createOptionSetRequest); Console.WriteLine("Option Set created"); //</snippetCreateOptionSet1> 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> /// Procedure: CreateGlobalOptionSet /// Handles: /// Created By: Will Wilson /// Created Date: 01/01/2016 /// Changes By: /// Changes Date: /// Changes Made: /// </summary> public void CreateGlobalOptionSet(IOrganizationService service, string solutionName, string schema, string label, int lang, string[] optionLabels) { OptionMetadataCollection options = new OptionMetadataCollection(); foreach (string o in optionLabels) { options.Add(new OptionMetadata(new Label(o, lang), null)); } CreateOptionSetRequest req = new CreateOptionSetRequest() { SolutionUniqueName = solutionName, OptionSet = new OptionSetMetadata(options) { Name = schema, DisplayName = new Label(label, lang), IsGlobal = true, OptionSetType = OptionSetType.Picklist, } }; CreateOptionSetResponse res = (CreateOptionSetResponse)service.Execute(req); Console.WriteLine("Global OptionSet created: {0}", schema); }
internal override OrganizationRequest Map(object[] dataRowValues) { var request = new CreateOptionSetRequest { OptionSet = new OptionSetMetadata { IsGlobal = true, OptionSetType = OptionSetType.Picklist } }; foreach (var column in Columns) { var value = dataRowValues[column.Position - 1]; var field = (ConfigurationFile.OptionSetFields)column.TargetField; if (value != null) { switch (field) { case ConfigurationFile.OptionSetFields.SolutionUniqueName: request.SolutionUniqueName = value as string; break; case ConfigurationFile.OptionSetFields.SchemaName: request.OptionSet.Name = value as string; break; case ConfigurationFile.OptionSetFields.DisplayName: request.OptionSet.DisplayName = new Label(value as string, LcId); break; case ConfigurationFile.OptionSetFields.Description: request.OptionSet.Description = new Label(value as string, LcId); break; case ConfigurationFile.OptionSetFields.Options: var options = ParseOptions(value as string); ((OptionSetMetadata)request.OptionSet).Options.AddRange(options); break; } } else if (!EnumUtils.IsOptional(field)) { throw new ArgumentException($"Mandatory data field {EnumUtils.Label(field)} does not contain a value."); } } return(request); }
public static void ProcessGlobalOptionSetAttributeList(BackgroundWorker worker, List <Attribute> attributeList, IOrganizationService service) { worker.ReportProgress(0, "Reviewing/Processing Global Option Sets"); var globalOptionSetList = new List <Attribute>(); foreach (var attribute in attributeList) { if (attribute.OptionSetType == "New Global Option Set") { globalOptionSetList.Add(attribute); } } if (globalOptionSetList.Count != 0) { foreach (var attribute in globalOptionSetList) { string optionSetSchemaName = (string.IsNullOrWhiteSpace(attribute.GlobalOSSchemaName)) ? attribute.FieldSchemaName : attribute.GlobalOSSchemaName; string optionSetDisplayName = (string.IsNullOrWhiteSpace(attribute.GlobalOSDisplayName)) ? attribute.FieldLabel : attribute.GlobalOSDisplayName; string regexSantizedName = "[^a-zA-Z0-9_]"; OptionMetadataCollection globalOSCollection = AttrBase.CreateOptionMetaDataCollection(attribute); var createOptionSetMeta = new OptionSetMetadata(globalOSCollection) { Name = Regex.Replace(optionSetSchemaName, regexSantizedName, string.Empty), DisplayName = new Label(optionSetDisplayName, CultureInfo.CurrentCulture.LCID), IsGlobal = true, OptionSetType = Microsoft.Xrm.Sdk.Metadata.OptionSetType.Picklist }; var createOptionsetReq = new CreateOptionSetRequest { OptionSet = createOptionSetMeta, SolutionUniqueName = attribute.SolutionUniqueName }; try { service.Execute(createOptionsetReq); } catch (Exception ex) { Console.WriteLine(ex.Message); } } FieldCreatorPluginControl.ImportGlobalOptionSets = globalOptionSetList; } }
public void AddNewOptionSet() { using (var svc = new CrmServiceClient(connection)) { CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = new OptionSetMetadata() { Name = "test_option_set", DisplayName = new Label("Test Option Set", 1033), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option 1", 1033), 1), new OptionMetadata(new Label("Option 2", 1033), 2) }, Description = new Label("This is test option set.", 1033) }, SolutionUniqueName = "samplesolution" }; svc.Execute(createOptionSetRequest); } }
/// <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); }
public void CreateOrUpdateSharedOptionSet(string schemaName, string displayName, IEnumerable<KeyValuePair<int, string>> options) { if (SharedOptionSetExists(schemaName)) { var optionSetMetadata = GetSharedOptionSet(schemaName); optionSetMetadata.DisplayName = new Label(displayName, 1033); var updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = optionSetMetadata }; Execute(updateOptionSetRequest); if (options.Any()) { var existingOptions = OptionSetToKeyValues(optionSetMetadata.Options); var optionSet = options.ToArray(); foreach (var option in existingOptions) { if (!optionSet.Any(o => o.Key == option.Key)) { var request = new DeleteOptionValueRequest { OptionSetName = schemaName, Value = option.Key }; Execute(request); } else if (optionSet.Any(o => o.Key == option.Key && o.Value != option.Value)) { var newValue = optionSet.Single(o => o.Key == option.Key); var request = new UpdateOptionValueRequest { OptionSetName = schemaName, Value = option.Key, Label = new Label(newValue.Value, 1033) }; Execute(request); } } foreach (var option in optionSet) { if (!existingOptions.Any(o => o.Key == option.Key)) { var request = new InsertOptionValueRequest { OptionSetName = schemaName, Value = option.Key, Label = new Label(option.Value, 1033) }; Execute(request); } } } } else { var optionSetMetadata = new OptionSetMetadata(); optionSetMetadata.Name = schemaName; optionSetMetadata.DisplayName = new Label(displayName, 1033); optionSetMetadata.IsGlobal = true; optionSetMetadata.Options.AddRange( options.Select(o => new OptionMetadata(new Label(o.Value, 1033), o.Key)).ToList()); var request = new CreateOptionSetRequest {OptionSet = optionSetMetadata}; Execute(request); } RefreshSharedOptionValues(schemaName); }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a managed solution for the Install or upgrade a solution sample Guid _tempPublisherId = new Guid(); System.String _tempCustomizationPrefix = "ds"; Guid _tempSolutionsSampleSolutionId = new Guid(); Random rn = new Random(); System.String _TempGlobalOptionSetName = "_TempSampleGlobalOptionSetName" + rn.Next(); Boolean _publisherCreated = false; Boolean _solutionCreated = false; //Define a new publisher Publisher _crmSdkPublisher = new Publisher { UniqueName = Constants.PublisherUniqueName, FriendlyName = Constants.PublisherFriendlyName, SupportingWebsiteUrl = Constants.PublisherSupportingWebsiteUrl, CustomizationPrefix = Constants.PublisherCustomizationPrefix, EMailAddress = Constants.PublisherEmailAddress, Description = Constants.PublisherDescription }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _tempPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _tempCustomizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _tempPublisherId = _serviceProxy.Create(_crmSdkPublisher); _tempCustomizationPrefix = _crmSdkPublisher.CustomizationPrefix; _publisherCreated = true; } //Upload only configuration page UploadConfigurationPageForSolution(); //SetWebResourceConfigurationForSolution(); //Define a solution Solution solution = new Solution { UniqueName = Constants.SolutionUniqueName, FriendlyName = Constants.SolutionFriendlyName, PublisherId = new EntityReference(Publisher.EntityLogicalName, _tempPublisherId), Description = Constants.SolutionDescription, Version = Constants.SolutionVersion, ConfigurationPageId = new EntityReference(WebResource.EntityLogicalName, _webResourceIdForSolution[0]) }; //Check whether it already exists QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(querySampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _tempSolutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _tempSolutionsSampleSolutionId = _serviceProxy.Create(solution); _solutionCreated = true; } // Add a solution Component OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _tempCustomizationPrefix + _TempGlobalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option A", _languageCode), null), new OptionMetadata(new Label("Option B", _languageCode), null) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(createOptionSetRequest); //delete configuration entity if (IsEntityExist(_customEntityName) > 0) { DeleteEntityRequest customEntityNameFormField = new DeleteEntityRequest() { LogicalName = _customEntityName, }; _serviceProxy.Execute(customEntityNameFormField); } // Create the dots_autonumber entity. AutoSMS.DotsAutoNumberEntity(); // CreateTab(); //delete dots_configuration entity if (IsEntityExist(_customConfigurationEntityName) > 0) { DeleteEntityRequest customEntityNameFormField = new DeleteEntityRequest() { LogicalName = _customConfigurationEntityName, }; _serviceProxy.Execute(customEntityNameFormField); } //for create dots_configuration entity AutoSMS.DotsAutoNumberConfigurationEntity(); // assign dots_autonumber form entity to solution RetrieveEntityRequest retrievepowertEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customEntityName }; RetrieveEntityResponse retrievepowerEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrievepowertEntityRequest); AddSolutionComponentRequest addReq = new AddSolutionComponentRequest() { ComponentType = 1, ComponentId = (Guid)retrievepowerEntityResponse.EntityMetadata.MetadataId, SolutionUniqueName = solution.UniqueName, AddRequiredComponents = true }; _serviceProxy.Execute(addReq); //assign dots_configuration entity to solution RetrieveEntityRequest retrieveconfigurationtEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customConfigurationEntityName }; RetrieveEntityResponse retrieveconfigEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveconfigurationtEntityRequest); AddSolutionComponentRequest addConfigReq = new AddSolutionComponentRequest() { ComponentType = 1, ComponentId = (Guid)retrieveconfigEntityResponse.EntityMetadata.MetadataId, SolutionUniqueName = solution.UniqueName, AddRequiredComponents = true }; _serviceProxy.Execute(addConfigReq); //assign web resource to slution CreateWebResource(solution.UniqueName); //assign configuration page above created to solution AssiginConfigurationPageToSolution(_webResourceIdForSolution[0], solution.UniqueName); ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; System.IO.Directory.CreateDirectory(_outputDir); File.WriteAllBytes(_managedSolutionLocation, exportXml); // Delete the solution and the components so it can be installed. DeleteOptionSetRequest delOptSetReq = new DeleteOptionSetRequest { Name = (_tempCustomizationPrefix + _TempGlobalOptionSetName).ToLower() }; _serviceProxy.Execute(delOptSetReq); DeleteEntityRequest delEntReq = new DeleteEntityRequest { LogicalName = (_customEntityName) }; _serviceProxy.Execute(delEntReq); DeleteEntityRequest delEntReqConfig = new DeleteEntityRequest { LogicalName = (_customConfigurationEntityName) }; _serviceProxy.Execute(delEntReqConfig); if (_solutionCreated) { _serviceProxy.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId); //delete webresorce foreach (var _id in _webResourceIds) { _serviceProxy.Delete(WebResource.EntityLogicalName, _id); } //for configuration page above created delete _serviceProxy.Delete(WebResource.EntityLogicalName, _webResourceIdForSolution[0]); } if (_publisherCreated) { _serviceProxy.Delete(Publisher.EntityLogicalName, _tempPublisherId); } Console.WriteLine("Managed Solution created and copied to {0}", _managedSolutionLocation); }
/// <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(); #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); #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 // 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); 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 // 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); 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 // 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); 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 // 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(); #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist // 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); 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 // 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); 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 // 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); } } #endregion How to retrieve all global option sets 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 Picklist Field /// </summary> /// <param name="SchemaName">Schema name of Attribute.</param> /// <param name="DisplayName">Display name of Attribute.</param> /// <param name="pickListArray">String Array for options set.</param> /// <param name="addedAttributes">Pass by reference, your Entity List.</param> /// <param name="multi">Pass "multi" for multiple picklist</param> static void createFieldPicklist(string SchemaName, string DisplayName, string[] pickListArray, ref List <AttributeMetadata> addedAttributes, string multi = "single") { // Option attribute meta mapper IList <OptionMetadata> options = new List <OptionMetadata>(); foreach (string singleTupleOptionMetadata in pickListArray) { options.Add(new OptionMetadata(new Label(singleTupleOptionMetadata, 1033), null)); } OptionSetMetadata optionset = new OptionSetMetadata(new OptionMetadataCollection(options)); optionset.IsGlobal = true; optionset.OptionSetType = OptionSetType.Picklist; optionset.DisplayName = new Label(DisplayName + " Global Picklist *", 1033); optionset.Description = new Label("MSVProperties - " + DisplayName + " picklist option set", 1033); optionset.Name = "new_msvproperties_" + SchemaName + "_option_global"; try { CrmServiceClient service = SampleHelpers.Connect("Connect"); CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = optionset }; CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)service.Execute(createOptionSetRequest); } catch (Exception ex) { //Supress Error. } if ("multi" == multi) { var CreatedMultiSelectPicklistAttributeMetadata = new MultiSelectPicklistAttributeMetadata("new_" + SchemaName) { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + " *", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM " + DisplayName + " multi check List", 1033), IsValidForForm = true, IsValidForGrid = true, OptionSet = new OptionSetMetadata { IsGlobal = true, Name = optionset.Name } }; // Add and return early. addedAttributes.Add(CreatedMultiSelectPicklistAttributeMetadata); } else { var CreatedPicklistAttributeMetadata = new PicklistAttributeMetadata("new_" + SchemaName) { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + " *", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM " + DisplayName + " single checklist", 1033), IsValidForForm = true, IsValidForGrid = true, OptionSet = new OptionSetMetadata { IsGlobal = true, Name = optionset.Name } }; addedAttributes.Add(CreatedPicklistAttributeMetadata); } }
public static void CreateQuestionMapping(OrganizationServiceProxy service, string name, string type, string values, string desc) { var nameLength = name.Length > 40 ? 40 : name.Length; var uniqueName = name.Substring(0, nameLength); uniqueName = uniqueName.Replace("(", "").Replace(")", "").Replace("(", "").Replace("/", "") .Replace("-", "").Replace(";", "").Replace("?", "").Replace("&", "").Replace(",", "").Replace(":", "").Replace(" ", "").ToLower(); var displaynameLength = name.Length > 50 ? 50 : name.Length; var DisplayName = name.Substring(0, displaynameLength); if (type == "Option Set") { var _values = values.Split(','); // Define the option set to create. OptionSetMetadata setupOptionSetMetadata = new OptionSetMetadata() { // The name will be used to uniquely identify the option set. // Normally you should generate this identifier using the publisher's // prefix and double-check that the name is not in use. Name = publisherPrefix + uniqueName, DisplayName = new Label(DisplayName, _languageCode), Description = new Label(desc, _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, // Define the list of options that populate the option set // The order here determines the order shown in the option set. Options = { // Options accepts any number of OptionMetadata instances, which // are simply pairs of Labels and integer values. new OptionMetadata(new Label(_values[0], _languageCode), null), new OptionMetadata(new Label(_values[1], _languageCode), null), } }; // Wrap the OptionSetMetadata in the appropriate request. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = setupOptionSetMetadata }; // Pass the execute statement to the CRM service. //service.Execute(createOptionSetRequest); Console.WriteLine(DisplayName + " Option Set created"); service.Execute(createOptionSetRequest); } else if (type.StartsWith("Mutli")) { var _values = values.Split(','); var outDoorActivitiesAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = publisherPrefix + uniqueName, LogicalName = publisherPrefix + uniqueName, DisplayName = new Label(DisplayName, _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label(desc, _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label(_values[0], _languageCode), 1), new OptionMetadata(new Label(_values[1], _languageCode), 2) } } }; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = outDoorActivitiesAttribute }; service.Execute(createAttributeRequest); Console.WriteLine(DisplayName + " Option Set created"); } else if (type == "Boolean") { var att = CreateBooleanAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Date & Time") { var att = CreateDateTimeAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Multi Text") { var att = CreateMemoAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc, 4000); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Text") { var att = CreateStringAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc, 500); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Whole Integer") { var att = CreateIntegerAttributeMetadata(uniqueName, DisplayName, AttributeRequiredLevel.None, desc, -1000000, 1000000); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // Define the request object and pass to the service. var 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)service.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. var 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 } } }; service.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). var updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; service.Execute(updateOptionSetRequest); //Publish the OptionSet var pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.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)service.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.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)service.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) }; service.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.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 service.Execute(orderOptionRequest); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.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)service.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); } } #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <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 creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a managed solution for the Install or upgrade a solution sample Guid _tempPublisherId = new Guid(); System.String _tempCustomizationPrefix = "new"; Guid _tempSolutionsSampleSolutionId = new Guid(); System.String _TempGlobalOptionSetName = "_TempSampleGlobalOptionSetName"; Boolean _publisherCreated = false; Boolean _solutionCreated = false; //Define a new publisher Publisher _crmSdkPublisher = new Publisher { UniqueName = "sdksamples", FriendlyName = "Microsoft CRM SDK Samples", SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx", CustomizationPrefix = "sample", EMailAddress = "*****@*****.**", Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK" }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _tempPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _tempCustomizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _tempPublisherId = _serviceProxy.Create(_crmSdkPublisher); _tempCustomizationPrefix = _crmSdkPublisher.CustomizationPrefix; _publisherCreated = true; } //Create a Solution //Define a solution Solution solution = new Solution { UniqueName = "samplesolutionforImport", FriendlyName = "Sample Solution for Import", PublisherId = new EntityReference(Publisher.EntityLogicalName, _tempPublisherId), Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.", Version = "1.0" }; //Check whether it already exists QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(querySampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _tempSolutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _tempSolutionsSampleSolutionId = _serviceProxy.Create(solution); _solutionCreated = true; } // Add a solution Component OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _tempCustomizationPrefix + _TempGlobalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option A", _languageCode), null), new OptionMetadata(new Label("Option B", _languageCode), null ) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(createOptionSetRequest); //Export an a solution ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = true; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; System.IO.Directory.CreateDirectory(outputDir); File.WriteAllBytes(ManagedSolutionLocation, exportXml); // Delete the solution and the components so it can be installed. DeleteOptionSetRequest delOptSetReq = new DeleteOptionSetRequest { Name = (_tempCustomizationPrefix + _TempGlobalOptionSetName).ToLower() }; _serviceProxy.Execute(delOptSetReq); if (_solutionCreated) { _serviceProxy.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId); } if (_publisherCreated) { _serviceProxy.Delete(Publisher.EntityLogicalName, _tempPublisherId); } Console.WriteLine("Managed Solution created and copied to {0}", ManagedSolutionLocation); }
private void CreateGlobalOptionSetAttribute(AttributeTemplate attributeTemplate) { var optionMetadataCollection = GetOptionMetadataCollection(attributeTemplate); var createOptionSetRequest = new CreateOptionSetRequest { OptionSet = new OptionSetMetadata(optionMetadataCollection) { Name = attributeTemplate.GlobalOptionSetListLogicalName, DisplayName = GetLabelWithLocalized(attributeTemplate.DisplayNameShort), Description = GetLabelWithLocalized(attributeTemplate.Description), IsGlobal = true, OptionSetType = OptionSetType.Picklist } }; if (!string.IsNullOrWhiteSpace(attributeTemplate.OtherDisplayName)) { var otherDisplayLabel = new LocalizedLabel(attributeTemplate.OtherDisplayName, DefaultConfiguration.OtherLanguageCode); createOptionSetRequest.OptionSet.DisplayName.LocalizedLabels.Add(otherDisplayLabel); } if (!string.IsNullOrWhiteSpace(attributeTemplate.OtherDescription)) { var otherDescriptionLabel = new LocalizedLabel(attributeTemplate.OtherDescription, DefaultConfiguration.OtherLanguageCode); createOptionSetRequest.OptionSet.Description.LocalizedLabels.Add(otherDescriptionLabel); } ExecuteOperation(GetSharedOrganizationService(), createOptionSetRequest, string.Format("An error occured while creating the attribute: {0}", attributeTemplate.LogicalName)); createdGlobalOptionSetList.Add(attributeTemplate.GlobalOptionSetListLogicalName); }
/// <summary> /// Shows how to create an 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(); //<snippetCreateOptionSet1> // Define the option set to create. OptionSetMetadata setupOptionSetMetadata = new OptionSetMetadata() { // The name will be used to uniquely identify the option set. // Normally you should generate this identifier using the publisher's // prefix and double-check that the name is not in use. Name = _optionSetName, DisplayName = new Label("Example Option Set", _languageCode), Description = new Label("An Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, // Define the list of options that populate the option set // The order here determines the order shown in the option set. Options = { // Options accepts any number of OptionMetadata instances, which // are simply pairs of Labels and integer values. new OptionMetadata(new Label("Option 1", _languageCode), null ), new OptionMetadata(new Label("Option 2", _languageCode), null ) } }; // Wrap the OptionSetMetadata in the appropriate request. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = setupOptionSetMetadata }; // Pass the execute statement to the CRM service. _serviceProxy.Execute(createOptionSetRequest); Console.WriteLine("Option Set created"); //</snippetCreateOptionSet1> 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 creates any entity records that this sample requires. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // Create a managed solution for the Install or upgrade a solution sample Guid _tempPublisherId = new Guid(); System.String _tempCustomizationPrefix = "new"; Guid _tempSolutionsSampleSolutionId = new Guid(); System.String _TempGlobalOptionSetName = "_TempSampleGlobalOptionSetName"; Boolean _publisherCreated = false; Boolean _solutionCreated = false; //Define a new publisher Publisher _powerappsSdkPublisher = new Publisher { UniqueName = "sdksamples", FriendlyName = "PowerApps SDK Samples", SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx", CustomizationPrefix = "sample", EMailAddress = "*****@*****.**", Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK" }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _powerappsSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = service.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _tempPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _tempCustomizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _tempPublisherId = service.Create(_powerappsSdkPublisher); _tempCustomizationPrefix = _powerappsSdkPublisher.CustomizationPrefix; _publisherCreated = true; } //Create a Solution //Define a solution Solution solution = new Solution { UniqueName = "samplesolutionforImport", FriendlyName = "Sample Solution for Import", PublisherId = new EntityReference(Publisher.EntityLogicalName, _tempPublisherId), Description = "This solution was created by the WorkWithSolutions sample code in the PowerApps SDK samples.", Version = "1.0" }; //Check whether it already exists QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); EntityCollection querySampleSolutionResults = service.RetrieveMultiple(querySampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _tempSolutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _tempSolutionsSampleSolutionId = service.Create(solution); _solutionCreated = true; } // Add a solution Component OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _tempCustomizationPrefix + _TempGlobalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option A", _languageCode), null), new OptionMetadata(new Label("Option B", _languageCode), null) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata, SolutionUniqueName = solution.UniqueName }; service.Execute(createOptionSetRequest); //Export an a solution ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = true; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)service.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; System.IO.Directory.CreateDirectory(outputDir); File.WriteAllBytes(ManagedSolutionLocation, exportXml); // Delete the solution and the components so it can be installed. DeleteOptionSetRequest delOptSetReq = new DeleteOptionSetRequest { Name = (_tempCustomizationPrefix + _TempGlobalOptionSetName).ToLower() }; service.Execute(delOptSetReq); if (_solutionCreated) { service.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId); } if (_publisherCreated) { service.Delete(Publisher.EntityLogicalName, _tempPublisherId); } Console.WriteLine("Managed Solution created and copied to {0}", ManagedSolutionLocation); }