Esempio n. 1
0
        protected override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            switch (this.ParameterSetName)
            {
            case NewOptionSetParameterSet:
                OptionSetMetadata internalOptionset = BuildOptionSet();
                Guid id1 = _repository.AddOptionSet(internalOptionset);
                if (PassThru)
                {
                    WriteObject(_repository.GetOptionSet(id1));
                }
                break;

            case NewOptionSetByInputObjectParameterSet:
                Guid id2 = _repository.AddOptionSet(InputObject);
                if (PassThru)
                {
                    WriteObject(_repository.GetOptionSet(id2));
                }
                break;

            default:
                break;
            }
        }
Esempio n. 2
0
 public SolutionComponentDependencyReport(IOrganizationService orgSvc)
 {
     _orgSvc           = orgSvc;
     _componentTypeDao = new ComponentInfoProvider(orgSvc);
     //The ComponentType global Option Set contains options for each possible component.
     _componentTypeOptionSet = GlobalOptionSetDao.GetMetadata(_orgSvc, "componenttype");
 }
Esempio n. 3
0
        public string GetOptionsetText(string optionsetName, int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;

            RetrieveOptionSetRequest retrieveOptionSetRequest =
                new RetrieveOptionSetRequest
            {
                Name = optionsetName
            };

            // Execute the request.
            RetrieveOptionSetResponse retrieveOptionSetResponse = null;

            retrieveOptionSetResponse = (RetrieveOptionSetResponse)_service.Execute(retrieveOptionSetRequest);

            // Access the retrieved OptionSetMetadata.
            OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

            // Get the current options list for the retrieved attribute.
            OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
            foreach (OptionMetadata optionMetadata in optionList)
            {
                if (optionMetadata.Value == optionsetValue)
                {
                    optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                    break;
                }
            }

            return(optionsetSelectedText);
        }
Esempio n. 4
0
        public OptionMetadata[] GetOptionSet(string entityName, string fieldName)
        {
            OptionMetadata[]         optionMetadatas;
            IOrganizationService     orgService       = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityName,
                LogicalName           = fieldName,
                RetrieveAsIfPublished = false
            };

            RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgService.Execute(attributeRequest);

            if (attributeResponse.AttributeMetadata.AttributeType == Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Boolean)
            {
                BooleanAttributeMetadata boolenAttributeMetadata = (BooleanAttributeMetadata)attributeResponse.AttributeMetadata;
                BooleanOptionSetMetadata boolenOptionSetMetadata = boolenAttributeMetadata.OptionSet;

                OptionMetadata[] options = new OptionMetadata[2];
                options[0]      = boolenOptionSetMetadata.TrueOption;
                options[1]      = boolenOptionSetMetadata.FalseOption;
                optionMetadatas = options;
            }
            else
            {
                EnumAttributeMetadata picklistAttributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;
                OptionSetMetadata     optionSetMetadata         = picklistAttributeMetadata.OptionSet;
                OptionMetadata[]      optionList = optionSetMetadata.Options.ToArray();
                optionMetadatas = optionList;
            }


            return(optionMetadatas);
        }
 private void FollowHyperlinkEventHandler(Hyperlink target)
 {
     //Handle the OptionSet click
     if (target != null)
     { //to check if the link is an option set
         Guid           guid      = new Guid(target.ScreenTip);
         ExcelSheetInfo currentSh = appData.eSheetsInfomation.getCurrentSheet();
         if (currentSh != null && currentSh is AttributeExcelSheetsInfo)
         {
             EntityMetadata etMetadata = ((AttributeExcelSheetsInfo)currentSh).entityMedata;
             IEnumerable <AttributeMetadata> etMetadataFilter = etMetadata.Attributes.Where(x => x is EnumAttributeMetadata && ((EnumAttributeMetadata)x).OptionSet != null && ((EnumAttributeMetadata)x).OptionSet.MetadataId == guid);
             if (etMetadataFilter.Count() > 0)
             {
                 AttributeMetadata currenAttribute = etMetadataFilter.First();
                 OptionSetMetadata optMetadata     = ((EnumAttributeMetadata)currenAttribute).OptionSet;
                 optioSetEventHandlerDelegate(optMetadata, currenAttribute);
                 //GlobalOperations.CreatenNewOptionSetSheet(optMetadata.MetadataId, currenAttribute);
                 //appData.eSheetsInfomation.addSheetAndSetAsCurrent(new OptionSetExcelSheetsInfo(ExcelSheetInfo.ExcelSheetType.optionSet, currentSheet, optMetadata, currenAttribute, optionKey), optionKey);
             }
         }
         if (currentSh != null && currentSh is EntityExcelSheetsInfo && guid != Guid.Empty)
         {
             IEnumerable <EntityMetadata> currentEntityWithoutAttributes = appData.allEntities.Where(x => x.MetadataId == guid);
             if (currentEntityWithoutAttributes.Count() != 1)
             {
                 return;
             }
             GlobalOperations.Instance.CreatenNewAttributesSheet(guid);
         }
     }
 }
Esempio n. 6
0
        public void GetNameForOptionSet_NonGlobal()
        {
            var optionSet = new OptionSetMetadata {
                Name = "OptionsetName"
            };
            var attMetadata = new PicklistAttributeMetadata {
                LogicalName = "ee_testid", DisplayName = new Label("Test_OptionsetName", 1033),
                OptionSet   = optionSet
            };
            var em = new EntityMetadata
            {
                LogicalName           = "ee_test",
                DisplayName           = new Label("Test", 1033),
                DisplayCollectionName = new Label("Tests", 1033)
            };

            em.Set(x => x.Attributes, new[] {
                attMetadata
            });
            organizationMetadata.Entities.Returns(new[] { em });

            organizationMetadata.OptionSets.Returns(new OptionSetMetadata [0]);

            var result = sut.GetNameForOptionSet(em, optionSet, serviceProvider);

            Assert.AreEqual(result, "Test_OptionsetName");
        }
Esempio n. 7
0
        /// <summary>
        /// 옵션집합 가져오기
        /// </summary>
        /// <param name="optionSetName"></param>
        /// <returns></returns>
        public DtoOptionSet RetrieveGlobalOptionSet(string optionSetName)
        {
            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
                {
                    Name = optionSetName
                };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_orgService.Execute(retrieveOptionSetRequest);

                //Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name);

                // Access the retrieved OptionSetMetadata.
                OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                DtoOptionSet retVal = new DtoOptionSet
                {
                    SchemaName  = optionSetName,
                    DisplayName = retrievedOptionSetMetadata.DisplayName.UserLocalizedLabel.Label,
                    Description = retrievedOptionSetMetadata.Description.UserLocalizedLabel.Label
                };

                return(retVal);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 옵션집합의 Options 가져오기
        /// </summary>
        /// <param name="optionSetName"></param>
        /// <returns></returns>
        private OptionMetadata[] RetrieveGlobalOptionSetOptions(string optionSetName)
        {
            try
            {
                // Use the RetrieveOptionSetRequest message to retrieve
                // a global option set by it's name.
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
                {
                    Name = optionSetName
                };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_orgService.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[] options = retrievedOptionSetMetadata.Options.ToArray();

                return(options);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 9
0
        /// <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;
            }
        }
Esempio n. 10
0
        public string GetOptionsetText(Entity entity, IOrganizationService service, string optionsetName, int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;

            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                    Name = optionsetName
                };
                RetrieveOptionSetResponse retrieveOptionSetResponse  = (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);
                OptionSetMetadata         retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;
                OptionMetadata[]          optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(optionsetSelectedText);
        }
Esempio n. 11
0
        // get a global option set value
        public static String getGlobalOptionSetName(String optionsetName, int optionsetValue, IOrganizationService service)
        {
            string ret = string.Empty;

            RetrieveOptionSetRequest req = new RetrieveOptionSetRequest {
                Name = optionsetName
            };

            // Execute the request.
            RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)service.Execute(req);

            // Access the retrieved OptionSetMetadata.
            OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)resp.OptionSetMetadata;

            // Get the current options list for the retrieved attribute.
            OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
            foreach (OptionMetadata optionMetadata in optionList)
            {
                if (optionMetadata.Value == optionsetValue)
                {
                    ret = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                    break;
                }
            }

            return(ret);
        }
Esempio n. 12
0
        // get a local option set value
        public static String getOptionName(Entity entity, string attributeName, IOrganizationService service)
        {
            int optionsetValue = getIntValue(entity, attributeName);

            string optionsetText = string.Empty;
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();

            retrieveAttributeRequest.EntityLogicalName     = entity.LogicalName;
            retrieveAttributeRequest.LogicalName           = attributeName;
            retrieveAttributeRequest.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse retrieveAttributeResponse =
                (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            PicklistAttributeMetadata picklistAttributeMetadata =
                (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

            OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

            foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
            {
                if (optionMetadata.Value == optionsetValue)
                {
                    optionsetText = optionMetadata.Label.UserLocalizedLabel.Label;
                    return(optionsetText);
                }
            }
            return(optionsetText);
        }
Esempio n. 13
0
        public bool GenerateOptionSet(
            OptionSetMetadata optionSetMetadata
            , AttributeMetadata attributeMetadata
            , ICodeGenerationServiceProvider iCodeGenerationServiceProvider
            )
        {
            if (IgnoreOptionSet(optionSetMetadata, attributeMetadata, iCodeGenerationServiceProvider))
            {
                return(false);
            }

            if (optionSetMetadata.OptionSetType == OptionSetType.State ||
                optionSetMetadata.OptionSetType == OptionSetType.Status
                )
            {
                return(_config.GenerateStatus);
            }

            if (optionSetMetadata.IsGlobal.GetValueOrDefault())
            {
                return(_config.GenerateGlobalOptionSet);
            }
            else
            {
                return(_config.GenerateLocalOptionSet);
            }
        }
        private CodeTypeReference BuildCodeTypeReferenceForOptionSet(
            string attributeName
            , EntityMetadata entityMetadata
            , AttributeMetadata attributeMetadata
            , OptionSetMetadata attributeOptionSet
            , ICodeGenerationServiceProvider iCodeGenerationServiceProvider
            )
        {
            if (iCodeGenerationServiceProvider.CodeWriterFilterService.GenerateOptionSet(attributeOptionSet, attributeMetadata, iCodeGenerationServiceProvider))
            {
                string nameForOptionSet = iCodeGenerationServiceProvider.NamingService.GetNameForOptionSet(entityMetadata, attributeOptionSet, iCodeGenerationServiceProvider);

                CodeGenerationType typeForOptionSet = iCodeGenerationServiceProvider.CodeGenerationService.GetTypeForOptionSet(entityMetadata, attributeOptionSet, iCodeGenerationServiceProvider);

                switch (typeForOptionSet)
                {
                case CodeGenerationType.Class:
                    return(this.TypeRef(nameForOptionSet));

                case CodeGenerationType.Enum:
                case CodeGenerationType.Struct:
                    return(TypeMappingService.TypeRef(typeof(Nullable <>), this.TypeRef(nameForOptionSet)));
                }
            }
            return(TypeMappingService.TypeRef(typeof(object)));
        }
 /// <summary>
 /// Processes the global option sets
 /// </summary>
 /// <param name="dictionary">The <see cref="String"/> array that contains the global option set values.</param>
 /// <param name="key">The option set name to be created or updated.</param>
 private void ProcessGlobalPicklists(string[] dictionary, string key)
 {
     if (dictionary.Length > 0)
     {
         try
         {
             RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                 Name = key
             };
             RetrieveOptionSetResponse retrieveOptionSetResponse  = (RetrieveOptionSetResponse)this.CrmAdapter.OrganizationService.Execute(retrieveOptionSetRequest);
             OptionSetMetadata         retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;
             OptionMetadata[]          optionList = retrievedOptionSetMetadata.Options.ToArray();
             foreach (string label in dictionary)
             {
                 var option = optionList.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label == label);
                 if (option == null)
                 {
                     InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest {
                         OptionSetName = key, Label = new Label(label, retrievedOptionSetMetadata.DisplayName.UserLocalizedLabel.LanguageCode)
                     };
                     this.CrmAdapter.OrganizationService.Execute(insertOptionValueRequest);
                 }
             }
         }
         catch (FaultException ex)
         {
             throw new AdapterException(ex.Message, ex)
                   {
                       ExceptionId = ErrorCodes.CrmPlatformException
                   };
         }
     }
 }
Esempio n. 16
0
        public string getOptionSetText(string entityName, string attributeName, int optionsetValue)
        {
            string optionsetText = string.Empty;
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();

            retrieveAttributeRequest.EntityLogicalName     = entityName;
            retrieveAttributeRequest.LogicalName           = attributeName;
            retrieveAttributeRequest.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse retrieveAttributeResponse =
                (RetrieveAttributeResponse)context.Execute(retrieveAttributeRequest);
            PicklistAttributeMetadata picklistAttributeMetadata =
                (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

            OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

            foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
            {
                if (optionMetadata.Value == optionsetValue)
                {
                    optionsetText = optionMetadata.Label.UserLocalizedLabel.Label;
                    return(optionsetText);
                }
            }
            return(optionsetText);
        }
Esempio n. 17
0
        public void GenerateGlobalOptionSetNoMatch()
        {
            var optionSetMetadata = new OptionSetMetadata
            {
                IsGlobal      = true,
                OptionSetType = OptionSetType.Picklist,
                Name          = "ee_TestOpt"
            };
            var id                = Guid.NewGuid();
            var attId             = Guid.NewGuid();
            var attributeMetadata = new PicklistAttributeMetadata
            {
                MetadataId = attId,
                OptionSet  = optionSetMetadata
            }.Set(x => x.EntityLogicalName, "ee_test");

            organizationMetadata.Entities.Returns(new[] {
                new EntityMetadata {
                    LogicalName = "ee_test", MetadataId = id,
                }
                .Set(x => x.Attributes, new[] { attributeMetadata })
            });

            SolutionHelper.organisationService.RetrieveMultiple(Arg.Any <QueryExpression>())
            .Returns(new EntityCollection(new List <Entity> {
                new Entity("solutioncomponent")
                {
                    Attributes = { { "objectid", id }, { "componenttype", 1 } }
                }
            }));

            var result = sut.GenerateOptionSet(optionSetMetadata, serviceProvider);

            Assert.IsFalse(result);
        }
Esempio n. 18
0
        /// <summary>
        /// helper method to retrieve option set text
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="attributeName"></param>
        /// <param name="optionsetValue"></param>
        /// <param name="orgService"></param>
        /// <returns></returns>
        public static string GetOptionSetText(string entityName, string attributeName, int optionsetValue, IOrganizationService orgService)
        {
            try
            {
                string optionsetText = string.Empty;
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest()
                {
                    EntityLogicalName     = entityName,
                    LogicalName           = attributeName,
                    RetrieveAsIfPublished = true
                };


                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)orgService.Execute(retrieveAttributeRequest);
                PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

                OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;


                foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetText = optionMetadata.Label.UserLocalizedLabel.Label;
                        return(optionsetText);
                    }
                }
                return(optionsetText);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("Error: Unable to load value for " + attributeName, ex);
            }
        }
        public List <OptionsetField> GetGlobalOptionSet(string optionSetName)
        {
            List <OptionsetField> optionSets = new List <OptionsetField>();
            ServerConnection      cnx        = new ServerConnection();

            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                    Name = optionSetName
                };

                RetrieveOptionSetResponse retrieveOptionSetResponse =
                    (RetrieveOptionSetResponse)cnx.Context.Execute(retrieveOptionSetRequest);

                OptionSetMetadata opcionesMedaData = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                opcionesMedaData.Options.ToList().ForEach
                    (l =>
                    optionSets.Add(new OptionsetField()
                {
                    Label = l.Label.UserLocalizedLabel.Label,
                    Value = Convert.ToInt32(l.Value)
                })
                    );
            }
            catch (Exception ex)
            {
                cnx = null;
                throw new CrmDataException(ex);
            }

            return(optionSets);
        }
Esempio n. 20
0
        public static OptionSetValue getOptionSetValue(IOrganizationService service, string entityName, string attributeName, string optionsetText)
        {
            OptionSetValue           optionSetValue           = new OptionSetValue();
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();

            retrieveAttributeRequest.EntityLogicalName     = entityName;
            retrieveAttributeRequest.LogicalName           = attributeName;
            retrieveAttributeRequest.RetrieveAsIfPublished = true;

            try
            {
                RetrieveAttributeResponse retrieveAttributeResponse =
                    (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                PicklistAttributeMetadata picklistAttributeMetadata =
                    (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

                OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

                foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
                {
                    if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
                    {
                        optionSetValue.Value = optionMetadata.Value.Value;
                        return(optionSetValue);
                    }
                }
                return(optionSetValue);
            }
            catch (Exception)
            { return(optionSetValue); }
        }
Esempio n. 21
0
        private List <OptionalValue> GetOptionSet(string entityName, string fieldName, IOrganizationService service)
        {
            RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest();

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

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

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

            return((from o in options.Options
                    select new OptionalValue
            {
                Value = o.Value,
                Text = o.Label.UserLocalizedLabel.Label
            }).ToList());
        }
Esempio n. 22
0
        /// <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;
            }
        }
Esempio n. 23
0
        private OptionSetMetadata BuildOptionSet()
        {
            OptionSetMetadata optionset = new OptionSetMetadata()
            {
                Name          = Name,
                DisplayName   = new Label(DisplayName, CrmContext.Language),
                Description   = new Label(Description ?? string.Empty, CrmContext.Language),
                OptionSetType = OptionSetType.Picklist
            };

            if (Customizable.HasValue)
            {
                optionset.IsCustomizable = new BooleanManagedProperty(Customizable.Value);
            }

            foreach (var item in Values)
            {
                OptionMetadata option = new OptionMetadata(new Label(item.DisplayName, CrmContext.Language), item.Value)
                {
                    Description = new Label(item.Description ?? string.Empty, CrmContext.Language)
                };
                optionset.Options.Add(option);
            }
            return(optionset);
        }
        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);
        }
Esempio n. 25
0
        public PicklistAttributeMetadata CreateOptionSet(string schema, string label, int lang, AttributeRequiredLevel requiredLevel, string[] optionLabels)
        {
            OptionMetadataCollection options = new OptionMetadataCollection();

            foreach (string o in optionLabels)
            {
                options.Add(new OptionMetadata(new Label(o, lang), null));
            }
            OptionSetMetadata optMetadata = new OptionSetMetadata(options)
            {
                IsGlobal      = false,
                OptionSetType = OptionSetType.Picklist,
            };

            PicklistAttributeMetadata pickListAttribute =
                new PicklistAttributeMetadata
            {
                // Set base properties
                SchemaName    = schema,
                DisplayName   = new Label(label, lang),
                RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                //Description = new Label("Picklist Attribute", lang),
                // Set extended properties
                // Build local picklist options
                OptionSet = optMetadata
            };

            return(pickListAttribute);
        }
Esempio n. 26
0
        private List <KeyValuePair <string, string> > RetrieveAttributeMetadata(string entityName, string attributeName)
        {
            RetrieveAttributeRequest request = new RetrieveAttributeRequest()
            {
                EntityLogicalName     = entityName,
                LogicalName           = attributeName,
                RetrieveAsIfPublished = true
            };

            RetrieveAttributeResponse response          = (RetrieveAttributeResponse)service.Execute(request);
            PicklistAttributeMetadata picklistMetadata  = (PicklistAttributeMetadata)response.AttributeMetadata;
            OptionSetMetadata         optionsetMetadata = (OptionSetMetadata)picklistMetadata.OptionSet;

            List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >();

            foreach (OptionMetadata option in optionsetMetadata.Options)
            {
                int?   optionKey   = option.Value;
                string optionValue = option.Label.UserLocalizedLabel.Label;
                if (optionKey.HasValue)
                {
                    int optionKeyValue = optionKey.Value;
                    list.Add(new KeyValuePair <string, string>(optionKeyValue.ToString(), optionValue));
                }
            }

            return(list);
        }
Esempio n. 27
0
 public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
 {
     if (EnumFilter.GenerateOptionSet(optionSetMetadata, services))
     {
         OptionSetMetadata.Add(optionSetMetadata.MetadataId.GetValueOrDefault(), optionSetMetadata);
     }
     return(DefaultService.GenerateOptionSet(optionSetMetadata, services));
 }
        public async Task <string[]> GetSecurityQuestions()
        {
            IEnumerable <OptionSetMetadataBase> optionSetDefinitions = essContext.GlobalOptionSetDefinitions.GetAllPages();
            OptionSetMetadata securityQuestionsOptionSet             = (OptionSetMetadata)optionSetDefinitions.Where(t => t.Name.Equals("era_registrantsecretquestions")).FirstOrDefault();

            string[] options = securityQuestionsOptionSet.Options.Select(o => o.Label.UserLocalizedLabel.Label).ToArray();
            return(await Task.FromResult(options));
        }
Esempio n. 29
0
        private void GenerateGetterForMultiSelectOptionSetProperty(CodeNamespace codeNamespace, AttributeMetadata attributeMetadata, CodeMemberProperty codeMemberProperty, EntityMetadata entityMetadata)
        {
            if (codeNamespace == null)
            {
                throw new ArgumentNullException(nameof(codeNamespace));
            }
            if (attributeMetadata == null)
            {
                throw new ArgumentNullException(nameof(attributeMetadata));
            }
            if (codeMemberProperty == null)
            {
                throw new ArgumentNullException(nameof(codeMemberProperty));
            }
            if (entityMetadata == null)
            {
                throw new ArgumentNullException(nameof(entityMetadata));
            }
            if (attributeMetadata.GetType() != typeof(MultiSelectPicklistAttributeMetadata))
            {
                throw new InvalidCastException(AttributeIsNotExpectedMessage);
            }

            OptionSetMetadata osm = ((MultiSelectPicklistAttributeMetadata)attributeMetadata).OptionSet;
            string            osn = ServiceHelper.GetOptionSetName(entityMetadata, osm); if (string.IsNullOrWhiteSpace(osn))
            {
                return;
            }
            string typeName = string.IsNullOrWhiteSpace(codeNamespace.Name) ? osn : string.Format(CultureInfo.InvariantCulture, "{0}.{1}", codeNamespace.Name, osn);

            codeMemberProperty.GetStatements.Clear();
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\tif ({0} == null)", ServiceHelper.GetPrivateAttributeName(osn))));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\t\tvar optionSetValueCollection = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValueCollection>(\"{0}\");", attributeMetadata.LogicalName)));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\tif (optionSetValueCollection == null)"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t\treturn null;"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\telse"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\t\t\t{1} = new System.Collections.Generic.HashSet<{0}>();", typeName, ServiceHelper.GetPrivateAttributeName(osn))));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t\tforeach(var optionSet in optionSetValueCollection)"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\t\t\t\t{1}.Add(({0})(System.Enum.ToObject(typeof({0}), optionSet.Value)));", typeName, ServiceHelper.GetPrivateAttributeName(osn))));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\telse"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\tvar optionSetValueCollection = new Microsoft.Xrm.Sdk.OptionSetValueCollection();"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\t\tforeach(var item in {0})", ServiceHelper.GetPrivateAttributeName(osn))));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t\toptionSetValueCollection.Add(new Microsoft.Xrm.Sdk.OptionSetValue((int)item));"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\t\tthis.SetAttributeValue(\"{0}\", optionSetValueCollection);", attributeMetadata.LogicalName)));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\treturn {0};", ServiceHelper.GetPrivateAttributeName(osn))));
        }
Esempio n. 30
0
        public static IDictionary <int, string> GetComponentTypes()
        {
            MetadataRepository repository       = new MetadataRepository();
            OptionSetMetadata  componentTypeSet = repository.GetOptionSet("componenttype") as OptionSetMetadata;

            LabelConverter lc = new LabelConverter();

            return(componentTypeSet.Options.ToDictionary(k => k.Value.GetValueOrDefault(), e => ((string)lc.ConvertTo(e.Label, typeof(string), null, true)).Replace(" ", "")));
        }
 public static AttributeMetadata CreateOptionSet(OptionSetMetadata optionSet, int? defaultFormValue = null, string formulaDefinition = null)
 {
     return new PicklistAttributeMetadata
     {
         FormulaDefinition = formulaDefinition,
         DefaultFormValue = defaultFormValue,
         OptionSet = optionSet
     };
 }
        public static AttributeMetadata CreateOptionSet(OptionSetMetadata optionSet, int? defaultFormValue = null, string formulaDefinition = null)
        {
            if (optionSet.IsGlobal.GetValueOrDefault())
            {   
                // Can't send Global Option Set Options
                optionSet.Options.Clear();
            }

            return new PicklistAttributeMetadata
            {
                FormulaDefinition = formulaDefinition,
                DefaultFormValue = defaultFormValue,
                OptionSet = optionSet
            };
        }
        private void AddEnumTypeValues(OptionSetMetadata options, Type enumType, string error)
        {
            if (enumType == null)
            {
                throw new Exception(error);
            }

            foreach (var value in Enum.GetValues(enumType))
            {
                options.Options.Add(
                    new OptionMetadata
                    {
                        Value = (int) value,
                        Label = new Label
                        {
                            UserLocalizedLabel = new LocalizedLabel(value.ToString(), Info.LanguageCode),
                        },
                    });
            }
        }
Esempio n. 34
0
        public void GetPicklistOptionCountTest_Test()
        {
            //ARRANGE - set up everything our test needs

            //first - set up a mock service to act like the CRM organization service
            var serviceMock = new Mock<IOrganizationService>();
            IOrganizationService service = serviceMock.Object;

            PicklistAttributeMetadata retrievedPicklistAttributeMetadata = new PicklistAttributeMetadata();
            OptionMetadata femaleOption = new OptionMetadata(new Label("Female", 1033), 43);
            femaleOption.Label.UserLocalizedLabel = new LocalizedLabel("Female", 1033);
            femaleOption.Label.UserLocalizedLabel.Label = "Female";
            OptionMetadata maleOption = new OptionMetadata(new Label("Male", 1033), 400);
            maleOption.Label.UserLocalizedLabel = new LocalizedLabel("Male", 400);
            maleOption.Label.UserLocalizedLabel.Label = "Male";
            OptionSetMetadata genderOptionSet = new OptionSetMetadata
            {
                Name = "gendercode",
                DisplayName = new Label("Gender", 1033),
                IsGlobal = true,
                OptionSetType = OptionSetType.Picklist,
                Options = { femaleOption, maleOption }
            };

            retrievedPicklistAttributeMetadata.OptionSet = genderOptionSet;
            RetrieveAttributeResponseWrapper picklistWrapper = new RetrieveAttributeResponseWrapper(new RetrieveAttributeResponse());
            picklistWrapper.AttributeMetadata = retrievedPicklistAttributeMetadata;

            serviceMock.Setup(t => t.Execute(It.Is<RetrieveAttributeRequest>(r => r.LogicalName == "gendercode"))).Returns(picklistWrapper);

            //ACT
            int returnedCount = Sample03.GetPicklistOptionCount("ANYENTITYMATCHES", "gendercode", service);

            //ASSERT
            Assert.AreEqual(2, returnedCount);
        }
Esempio n. 35
0
 public OptionSetMetadataInfo(OptionSetMetadata amd)
 {
     this.amd = amd;
 }
        private RetrieveOptionSetResponse ExecuteInternal(RetrieveOptionSetRequest request)
        {
            var response = new RetrieveOptionSetResponse();
            var optionSet = new OptionSetMetadata(new OptionMetadataCollection());

            response.Results["OptionSetMetadata"] = optionSet;

            var types = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes();
            var enumType = types.FirstOrDefault(t => IsEnumType(t, request.Name)) ??
                           types.FirstOrDefault(t => IsEnumType(t, request.Name + "Enum"));

            AddEnumTypeValues(optionSet, enumType, "Unable to find global optionset enum " + request.Name);

            return response;
        }
Esempio n. 37
0
        /// <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);

        }
Esempio n. 38
0
        /// <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);
        }
Esempio n. 39
0
        /// <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;
            }
        }
Esempio n. 40
0
        public void CreateOrUpdatePicklistAttribute(string schemaName, string displayName, string description,
            bool isRequired, bool audit, bool searchable,
            string recordType, IEnumerable<KeyValuePair<int, string>> options)
        {
            lock (LockObject)
            {
                var optionSet = new OptionSetMetadata
                {
                    OptionSetType = OptionSetType.Picklist,
                    IsGlobal = false
                };
                optionSet.Options.AddRange(options.Select(o => new OptionMetadata(new Label(o.Value, 1033), o.Key)));

                PicklistAttributeMetadata metadata;
                var exists = FieldExists(schemaName, recordType);
                if (exists)
                    metadata = (PicklistAttributeMetadata) GetFieldMetadata(schemaName, recordType);
                else
                    metadata = new PicklistAttributeMetadata();

                SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable);

                metadata.OptionSet = optionSet;

                CreateOrUpdateAttribute(schemaName, recordType, metadata);
            }
        }
Esempio n. 41
0
        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);
        }