Exemplo n.º 1
0
        /// <summary>
        /// 创建Two Options字段
        /// </summary>
        public OrganizationResponse CreateTwoOptionsField(
            string entityName,
            string schemName,
            string displayName,
            string decription,
            IDictionary <string, int> options,
            AttributeRequiredLevel requiredLevel)
        {
            if (options.Count != 2)
            {
                throw new ArgumentException("The options argument should have two options");
            }
            OptionMetadataCollection collection = GetOptionMetadataCollection(options);
            var request = new CreateAttributeRequest
            {
                EntityName = entityName,
                Attribute  = new BooleanAttributeMetadata()
                {
                    SchemaName    = schemName,
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                    DisplayName   = new Label(displayName, 1033),
                    Description   = new Label(decription, 1033),
                    OptionSet     = new BooleanOptionSetMetadata(
                        collection[0],  // true option
                        collection[1]   // false option
                        )
                }
            };

            return(Service.Execute(request));
        }
Exemplo n.º 2
0
        public static OptionsModel Parse(this OptionMetadataCollection th, int?languageCode = null)
        {
            var options = new List <OptionModel>();

            var nullOption = new OptionModel();

            nullOption.DisplayName = "Null";
            nullOption.Hexadecimal = "#000000";
            nullOption.Value       = null;
            nullOption.Count       = 0;
            options.Add(nullOption);

            foreach (var option_ in th)
            {
                var option = new OptionModel();
                option.DisplayName = option_.Label.GetLabel(languageCode);
                option.Hexadecimal = option_.Color;
                option.Value       = option_.Value.Value;
                option.Count       = 0;
                options.Add(option);
            }
            return(new OptionsModel()
            {
                Options = options.ToArray()
            });
        }
Exemplo n.º 3
0
        /// <summary>
        /// 创建OptionSet字段
        /// </summary>
        public OrganizationResponse CreateOptionSetField(
            string entityName,
            string schemName,
            string displayName,
            string decription,
            IDictionary <string, int> options,
            bool isGlobal,
            AttributeRequiredLevel requiredLevel)
        {
            OptionMetadataCollection collection = GetOptionMetadataCollection(options);

            var request = new CreateAttributeRequest
            {
                EntityName = entityName,
                Attribute  = new PicklistAttributeMetadata()
                {
                    SchemaName    = schemName,
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                    DisplayName   = new Label(displayName, 1033),
                    Description   = new Label(decription, 1033),
                    OptionSet     = new OptionSetMetadata(collection)
                    {
                        IsGlobal = isGlobal
                    }
                }
            };

            return(Service.Execute(request));
        }
        public void LoadSolutions()
        {
            sManager = new SolutionManager(Service);

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Loading solutions...",
                Work    = (bw, e) =>
                {
                    e.Result = sManager.RetrieveSolutions();

                    _omc = ((OptionSetMetadata)((RetrieveOptionSetResponse)Service.Execute(
                                                    new RetrieveOptionSetRequest
                    {
                        Name = "componenttype"
                    })).OptionSetMetadata).Options;
                    //_omc
                },
                PostWorkCallBack = e =>
                {
                    if (e.Error == null)
                    {
                        sourceSolutionPicker.LoadSolutions((IEnumerable <Entity>)e.Result);
                        targetSolutionPicker.LoadSolutions((IEnumerable <Entity>)e.Result);
                    }
                    else
                    {
                        MessageBox.Show(ParentForm, "An error occured: " + e.Error.Message, "Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                },
            });
        }
Exemplo n.º 5
0
        /// <summary>
        /// Procedure: InsertGlobalOptionSet
        /// Handles: Inserts Values to existing optionset
        /// Created By: Steve Weinberger
        /// Created Date: 06/07/2016
        /// Changes By:
        /// Changes Date:
        /// Changes Made:
        /// </summary>
        public void InsertGlobalOptionSet(IOrganizationService service, string solutionName, string schema, string label, int lang, string[] optionLabels)
        {
            string globalOptionSetName = schema;
            int    _insertedOptionValue;

            OptionMetadataCollection options = new OptionMetadataCollection();

            foreach (string o in optionLabels)
            {
                InsertOptionValueRequest req = new InsertOptionValueRequest()
                {
                    SolutionUniqueName = solutionName,
                    OptionSetName      = globalOptionSetName,
                    Label = new Label(o, lang)
                };
                //InsertOptionValueResponse res = (InsertOptionValueResponse)service.Execute(req);

                _insertedOptionValue = ((InsertOptionValueResponse)service.Execute(req)).NewOptionValue;


                Console.WriteLine("Created {0} with the value of {1}.",
                                  req.Label.LocalizedLabels[0].Label,
                                  _insertedOptionValue);
            }

            //Publish the OptionSet
            PublishXmlRequest pxReq2 = new PublishXmlRequest {
                ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", globalOptionSetName)
            };

            service.Execute(pxReq2);
            Console.WriteLine("Global OptionSet inserted: {0}", schema);
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        /// <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);
        }
        private static Microsoft.Xrm.Sdk.Metadata.OptionMetadataCollection GetOptionMetadata(string option)
        {
            OptionMetadataCollection optionMetadataCollection = new OptionMetadataCollection();

            if (option != "")
            {
                if (option.Contains("|"))
                {
                    string[] optionArray = option.Split('|');
                    if (optionArray != null && optionArray.Length > 0)
                    {
                        for (int arrayCounter = 0; arrayCounter < optionArray.Length; arrayCounter++)
                        {
                            optionMetadataCollection.Add(new OptionMetadata(
                                                             new Microsoft.Xrm.Sdk.Label(optionArray[arrayCounter], _languageCode), null));
                        }
                    }
                }
                else
                {
                    optionMetadataCollection.Add(new OptionMetadata(
                                                     new Microsoft.Xrm.Sdk.Label(option, _languageCode), null));
                }
            }
            return(optionMetadataCollection);
        }
        private Dictionary <int, string> GetOptionsNames(EntityReference sourceEntityReference, string attributeName, Common context)
        {
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = sourceEntityReference.LogicalName,
                LogicalName           = attributeName,
                RetrieveAsIfPublished = false
            };

            RetrieveAttributeResponse response = context.service.Execute(attributeRequest) as RetrieveAttributeResponse;

            MultiSelectPicklistAttributeMetadata attributeMetadata = response.AttributeMetadata as MultiSelectPicklistAttributeMetadata;

            if (attributeMetadata == null)
            {
                throw new InvalidPluginExecutionException($"Attribute {attributeName} is not an expected multi-select optionset / choices type");
            }

            OptionMetadataCollection options      = attributeMetadata.OptionSet.Options;
            Dictionary <int, string> optionsTable = new Dictionary <int, string>(options.Count);

            foreach (OptionMetadata optionMetadata in options)
            {
                optionsTable.Add(optionMetadata.Value.Value, optionMetadata.Label.UserLocalizedLabel.Label);
            }

            return(optionsTable);
        }
        protected override void Execute(CodeActivityContext context)
        {
            if (context == null)
            {
                throw new InvalidPluginExecutionException("Context not found!");
            }
            ;

            var workflowContext = context.GetExtension <IWorkflowContext>();
            var serviceFactory  = context.GetExtension <IOrganizationServiceFactory>();
            var orgService      = serviceFactory.CreateOrganizationService(workflowContext.UserId);

            Guid recordId = Guid.Empty;

            if (Guid.TryParse(EntityId.Get <string>(context), out recordId))
            {
                DynamicsDAO             dynamicsDAO = new DynamicsDAO(orgService);
                List <AuditDetailModel> audits      = dynamicsDAO.RetrieveAuditHistory(EntityLogicalName.Get <string>(context), AttributeLogicalName.Get <string>(context), recordId);
                if (audits.Count > 0)
                {
                    if (audits.Where(w => w.Type == "optionsetvalue").ToList().Count > 0) //This is necessary because the audit log, capture all changes in attributes including 'clear'
                    {
                        OptionMetadataCollection optionMetadatas = dynamicsDAO.GetOptionsSetTextOnValue(EntityLogicalName.Get <string>(context), AttributeLogicalName.Get <string>(context));
                        audits.ReplaceOptionSetValuesByLabels(optionMetadatas);
                    }
                    else if (audits.Where(w => w.Type == "boolean").ToList().Count > 0)
                    {
                        BooleanOptionSetMetadata booleanOptionSetMetadata = dynamicsDAO.GetBooleanTextOnValue(EntityLogicalName.Get <string>(context), AttributeLogicalName.Get <string>(context));
                        audits.ReplaceBooleanValuesByLabels(booleanOptionSetMetadata);
                    }
                }
                ChangesCount.Set(context, audits.Count);
                History.Set(context, audits.ToJSON());
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Gets the integer value for a picklist option by name and language code.
        /// </summary>
        /// <param name="entityName">Logical name of the entity.</param>
        /// <param name="attributeName">Logical name of the attribute.</param>
        /// <param name="picklistValue">Name of the picklist option.</param>
        /// <param name="languageCode">Language code of the picklist option.</param>
        /// <returns>Integer value for the picklist option.</returns>
        public int GetIntValueFromPicklistString(String entityName, String attributeName, String picklistValue, int languageCode)
        {
            var attributeMetadata = RetrieveAttribute(entityName, attributeName);
            var type    = attributeMetadata.GetType();
            var options = new OptionMetadataCollection();

            if (type == typeof(PicklistAttributeMetadata))
            {
                options = ((PicklistAttributeMetadata)attributeMetadata).OptionSet.Options;
            }
            else if (type == typeof(StateAttributeMetadata))
            {
                options = ((StateAttributeMetadata)attributeMetadata).OptionSet.Options;
            }
            else if (type == typeof(StatusAttributeMetadata))
            {
                options = ((StatusAttributeMetadata)attributeMetadata).OptionSet.Options;
            }


            foreach (var option in options)
            {
                if (option.Value.HasValue)
                {
                    var label = option.Label.LocalizedLabels.FirstOrDefault(
                        x => x.LanguageCode == languageCode && picklistValue.Equals(x.Label, StringComparison.CurrentCultureIgnoreCase));
                    if (label != null)
                    {
                        return(option.Value.Value);
                    }
                }
            }

            return(-1);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the integer value for a picklist option by name.
        /// </summary>
        /// <param name="entityName">Logical name of the entity.</param>
        /// <param name="attributeName">Logical name of the attribute.</param>
        /// <param name="picklistValue">Name of the picklist option.</param>
        /// <returns>Integer value for the picklist option.</returns>
        public int GetIntValueFromPicklistString(String entityName, String attributeName, String picklistValue)
        {
            var attributeMetadata = RetrieveAttribute(entityName, attributeName);
            var type    = attributeMetadata.GetType();
            var options = new OptionMetadataCollection();

            if (type == typeof(PicklistAttributeMetadata))
            {
                options = ((PicklistAttributeMetadata)attributeMetadata).OptionSet.Options;
            }
            else if (type == typeof(StateAttributeMetadata))
            {
                options = ((StateAttributeMetadata)attributeMetadata).OptionSet.Options;
            }
            else if (type == typeof(StatusAttributeMetadata))
            {
                options = ((StatusAttributeMetadata)attributeMetadata).OptionSet.Options;
            }

            foreach (var option in options)
            {
                if (option.Value.HasValue && option.Label.UserLocalizedLabel.Label.ToLower() == picklistValue.ToLower())
                {
                    return(option.Value.Value);
                }
            }

            return(-1);
        }
Exemplo n.º 13
0
        public void GetOptionSetNameFromValueOk()
        {
            var optionSetName = "name";
            var value         = 12;
            var name          = "value";

            OrganizationService.Setup(s => s.Execute(It.IsAny <OrganizationRequest>())).Callback <OrganizationRequest>(request =>
            {
                Assert.IsInstanceOfType(request, typeof(RetrieveOptionSetRequest));
                var r = (RetrieveOptionSetRequest)request;

                Assert.AreEqual(r.Name, optionSetName);
            }).Returns(() =>
            {
                var options = new OptionMetadataCollection();
                options.Add(new OptionMetadata(new Label(new LocalizedLabel("autre", 1033), null), 18));
                options.Add(new OptionMetadata(new Label(new LocalizedLabel(name, 1033), null), value));

                var response = new RetrieveOptionSetResponse();
                response.Results["OptionSetMetadata"] = new OptionSetMetadata(options);
                return(response);
            });

            var result = Service.GetOptionSetNameFromValue(optionSetName, value);

            Assert.AreEqual(result, name);
        }
Exemplo n.º 14
0
        private void CreateRecords(Settings settings)
        {
            foreach (var optionSet in settings.OptionSets)
            {
                OptionMetadataCollection omc = null;

                if (optionSet is PicklistAttributeMetadata)
                {
                    omc = ((PicklistAttributeMetadata)optionSet).OptionSet.Options;
                }
                else if (optionSet is StateAttributeMetadata)
                {
                    omc = ((StateAttributeMetadata)optionSet).OptionSet.Options;
                }
                else
                {
                    omc = ((StatusAttributeMetadata)optionSet).OptionSet.Options;
                }

                foreach (OptionMetadata option in omc)
                {
                    foreach (LocalizedLabel label in option.Label.LocalizedLabels)
                    {
                        bool exists = true;
                        var  record = GetRecord(settings.AllMetadata.First(e => e.LogicalName == optionSet.EntityLogicalName).SchemaName, optionSet.SchemaName, option.Value.Value, label.LanguageCode);
                        if (record == null)
                        {
                            record = new Entity("gap_powerbioptionsetref");
                            exists = false;
                        }
                        else
                        {
                            // The label did not change, no need to update
                            if (record.GetAttributeValue <string>("gap_label") == label.Label)
                            {
                                continue;
                            }
                        }

                        record["gap_entityname"]          = settings.AllMetadata.First(e => e.LogicalName == optionSet.EntityLogicalName).DisplayName.UserLocalizedLabel.Label;
                        record["gap_entityschemaname"]    = settings.AllMetadata.First(e => e.LogicalName == optionSet.EntityLogicalName).SchemaName;
                        record["gap_optionsetschemaname"] = optionSet.SchemaName;
                        record["gap_value"]    = option.Value;
                        record["gap_language"] = label.LanguageCode;
                        record["gap_label"]    = label.Label;

                        if (exists)
                        {
                            Service.Update(record);
                        }
                        else
                        {
                            Service.Create(record);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets the basket name of product.
        /// </summary>
        /// <param name="detail">The detail.</param>
        /// <param name="optionSetLabels">The option set labels.</param>
        /// <returns></returns>
        private static string GetBasketNameOfProduct(SalesOrderDetail detail, OptionMetadataCollection levelOptionSetLabels)
        {
            string basketName = detail.lss_courseid == null ? String.Empty : detail.lss_courseid.Name;

            basketName += " - " + ReplaceOptionSet(levelOptionSetLabels, detail.lss_Level) + " - ";
            basketName += detail.lss_Centre == null ? String.Empty : detail.lss_Centre.Name;

            return(basketName);
        }
        /// <summary>
        /// Builds the basket.
        /// </summary>
        /// <param name="connector">The connector.</param>
        /// <param name="order">The order.</param>
        /// <returns>
        /// A string containing the contents of the order
        /// </returns>
        private static string BuildBasket(CrmConnector connector, OrderProvider orderProvider, SalesOrder order)
        {
            StringBuilder basket = new StringBuilder();

            // A basket item comprises of Product Name, Quantity, Unit Cost, Tax, Cost inc. Tax, and Total Cost (Cost*Quantity).  These are all seperated with colons (i.e. %3A).
            string basketItem = String.Empty;
            string seperator  = "%3A";

            // Get a list of the names for the level Option Set.
            MetaDataProvider         metaDataProvider     = new MetaDataProvider(connector);
            OptionMetadataCollection levelOptionSetLabels = metaDataProvider.RetrieveOptionSetMetaDataCollection(SalesOrderDetail.EntityLogicalName, "lss_level");

            int basketCount = 0;
            List <SalesOrderDetail> productExtras;
            List <SalesOrderDetail> orderDetails = orderProvider.GetOrderDetail(order.Id, ProductType.Course);

            foreach (SalesOrderDetail detail in orderDetails)
            {
                string basketItemName = GetBasketNameOfProduct(detail, levelOptionSetLabels);

                // Add name of basket item with a hard-coded Quantity of 1
                basketItem = seperator + basketItemName + seperator + "1" + seperator;

                // For each product check if it has any related products
                productExtras = orderProvider.GetProductExtras(detail.Id);
                decimal extraUnitCost = 0;
                decimal extraTax      = 0;
                decimal extraTotal    = 0;
                foreach (SalesOrderDetail extra in productExtras)
                {
                    extraUnitCost += extra.BaseAmount == null ? 0 : extra.BaseAmount.Value;
                    extraTax      += extra.Tax == null ? 0 : extra.Tax.Value;
                    extraTotal    += extra.ExtendedAmount == null ? 0 : extra.ExtendedAmount.Value;
                }

                // Add unit cost
                basketItem += (detail.BaseAmount.Value + extraUnitCost).ToString("#.##") + seperator;

                // Add Tax
                basketItem += detail.Tax == null ? "0" : (detail.Tax.Value + extraTax).ToString("#.##") + seperator;

                // Add Cost inc. Tax
                basketItem += (detail.ExtendedAmount.Value + extraTotal).ToString("#.##") + seperator;

                // Add Total Cost
                basketItem += (detail.ExtendedAmount.Value + extraTotal).ToString("#.##");

                basket.Append(basketItem);
                basketCount++;
            }

            basket.Insert(0, "&Basket=" + basketCount.ToString());

            return(basket.ToString());
        }
        private static Dictionary <int, string> GetPicklistValues(OptionMetadataCollection options)
        {
            var result = new Dictionary <int, string>();

            foreach (var item in options)
            {
                result.Add(item.Value.Value, item.Label.UserLocalizedLabel.Label.ToString().ToAlphaNumeric());
            }

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 获取OptionMetadataCollection
        /// </summary>
        private OptionMetadataCollection GetOptionMetadataCollection(IDictionary <string, int> options)
        {
            IList <OptionMetadata> list = options.Select(opt => new OptionMetadata()
            {
                Label = new Label(opt.Key, 1033),
                Value = opt.Value
            }).ToList();
            var collection = new OptionMetadataCollection(list);

            return(collection);
        }
        protected override void AddAdditionalMetadata(StatusAttributeMetadata attribute)
        {
            var options = ParseOptions();

            var optionCollection = new OptionMetadataCollection(options.Cast <OptionMetadata>().ToList());

            attribute.OptionSet = new OptionSetMetadata(optionCollection)
            {
                IsGlobal      = false,
                OptionSetType = OptionSetType.Status,
            };
        }
        /// <summary>
        /// Replaces the option set.
        /// </summary>
        /// <param name="localContext">The local context.</param>
        /// <param name="optionSetLabels">The option set labels.</param>
        /// <param name="optionSetValue">The option set value.</param>
        /// <returns></returns>
        private static string ReplaceOptionSet(OptionMetadataCollection optionSetLabels, OptionSetValue optionSetValue)
        {
            if (optionSetValue != null)
            {
                foreach (OptionMetadata optionMetadata in optionSetLabels)
                {
                    if (optionMetadata.Value == optionSetValue.Value)
                    {
                        return(optionMetadata.Label.UserLocalizedLabel.Label);
                    }
                }
            }

            return(String.Empty);
        }
        /// <summary>
        /// Convert OptionMetadataCollection to  List<OptionSetMetadataModel>
        /// </summary>
        /// <param name="_this">OptionMetadataCollection</param>
        /// <returns>string</returns>
        public static string ConvertToModel(this OptionMetadataCollection _this)
        {
            List <OptionSetMetadataModel> options = new List <OptionSetMetadataModel>();

            foreach (StatusOptionMetadata option_ in _this)
            {
                OptionSetMetadataModel model = new OptionSetMetadataModel();
                model.Label      = option_?.Label?.UserLocalizedLabel?.Label != null ? option_.Label.UserLocalizedLabel.Label : string.Empty;
                model.Color      = option_?.Color;
                model.StatusCode = option_.Value.Value;
                model.StateCode  = (int)((StatusOptionMetadata)option_).State;;// option_.ParentValues != null ? option_.ParentValues.FirstOrDefault() : -450;
                options.Add(model);
            }

            return(ToJSON(options));
        }
Exemplo n.º 22
0
        internal static void CheckStatusTransitions(EntityMetadata metadata, Entity newEntity, Entity prevEntity)
        {
            if (newEntity == null || prevEntity == null)
            {
                return;
            }
            if (!newEntity.Attributes.ContainsKey("statuscode") || !prevEntity.Attributes.ContainsKey("statuscode"))
            {
                return;
            }
            if (newEntity.LogicalName != prevEntity.LogicalName || newEntity.Id != prevEntity.Id)
            {
                return;
            }

            var newValue  = newEntity["statuscode"] as OptionSetValue;
            var prevValue = prevEntity["statuscode"] as OptionSetValue;

            if (metadata.EnforceStateTransitions != true)
            {
                return;
            }

            OptionMetadataCollection optionsMeta = GetStatusOptionMetadata(metadata);

            if (!optionsMeta.Any(o => o.Value == newValue.Value))
            {
                return;
            }

            var prevValueOptionMeta = optionsMeta.FirstOrDefault(o => o.Value == prevValue.Value) as StatusOptionMetadata;

            if (prevValueOptionMeta == null)
            {
                return;
            }

            var transitions = prevValueOptionMeta.TransitionData;

            if (transitions != null && transitions != "" &&
                IsValidStatusTransition(transitions, newValue.Value))
            {
                return;
            }

            throw new FaultException($"Trying to switch {newEntity.LogicalName} from status {prevValue.Value} to {newValue.Value}");
        }
        private IOrganizationService SetupIOrganisationService(Entity recordContext, int optionSetValue)
        {
            StubIOrganizationService stubIOrganisationService = new StubIOrganizationService();

            stubIOrganisationService.RetrieveStringGuidColumnSet = (entityLogicalName, recordId, columnSet)
                                                                   =>
            {
                if (entityLogicalName == "dxtools_payment")
                {
                    return(recordContext);
                }
                else
                {
                    return(null);
                }
            };

            stubIOrganisationService.ExecuteOrganizationRequest = (request)
                                                                  =>
            {
                if (request.RequestName == "RetrieveAttribute")
                {
                    RetrieveAttributeResponse response = new RetrieveAttributeResponse();
                    return(response);
                }
                else
                {
                    return(null);
                }
            };

            Microsoft.Xrm.Sdk.Messages.Fakes.ShimRetrieveAttributeResponse.AllInstances.AttributeMetadataGet = (i)
                                                                                                               =>
            {
                OptionMetadataCollection optionMetadataCollection = new OptionMetadataCollection();
                OptionMetadata           optionMetadata           = new OptionMetadata(new Label(), optionSetValue);
                optionMetadata.Label.UserLocalizedLabel = new LocalizedLabel("IN", 1033);
                optionMetadataCollection.Add(optionMetadata);

                PicklistAttributeMetadata picklistAttributeMetadata = new PicklistAttributeMetadata();
                picklistAttributeMetadata.OptionSet = new OptionSetMetadata(optionMetadataCollection);
                return(picklistAttributeMetadata);
            };

            return(stubIOrganisationService);
        }
Exemplo n.º 24
0
        private OptionMetadataCollection getOptionSetValueAndName(string entityname, string attributename, OrganizationServiceProxy organizationProxy)
        {
            //RetrieveOptionSetRequest optionSetRequest = new RetrieveOptionSetRequest { Name = filedName };
            //RetrieveOptionSetResponse optionSetResponse = (RetrieveOptionSetResponse)organizationProxy.Execute(optionSetRequest);

            //OptionSetMetadata optionSetMetaData = (OptionSetMetadata)optionSetResponse.OptionSetMetadata;
            //return optionSetMetaData;

            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest {
                EntityLogicalName = entityname, LogicalName = attributename
            };
            // Execute the request.
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)organizationProxy.Execute(retrieveAttributeRequest);
            OptionMetadataCollection  options = ((PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata).OptionSet.Options;

            return(options);
        }
Exemplo n.º 25
0
        protected override void AddAdditionalMetadata(PicklistAttributeMetadata attribute)
        {
            var options = Options.Split('\n').Select(x =>
                                                     x.Split(':'))
                          .Select(x => new OptionMetadata(new Label(x[1], LanguageCode), Int32.Parse(x[0]))).ToList();

            var optionCollection = new OptionMetadataCollection(options);

            var globalNames = !string.IsNullOrEmpty(GlobalOptionsetName) ? GlobalOptionsetName.Split(':') : null;

            attribute.OptionSet = new OptionSetMetadata(optionCollection)
            {
                IsGlobal      = globalNames != null,
                Name          = globalNames?[0],
                DisplayName   = new Label(globalNames?[1], LanguageCode),
                OptionSetType = OptionSetType.Picklist,
            };
        }
Exemplo n.º 26
0
        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;
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Returns the text associated with specified optionset value for the identified entity and attribute.
        /// </summary>
        /// <param name="entityLogicalName">Schema name of the entity that contains the optionset attribute.</param>
        /// <param name="attributeName">Schema name of the attribute.</param>
        /// <param name="selectedValue">Numeric value of the optionset.</param>
        /// <returns></returns>
        public string GetOptionSetLabel(string entityLogicalName, string attributeName, int optionSetValue)
        {
            string returnLabel = string.Empty;

            OptionMetadataCollection optionsSetLabels = null;

            optionsSetLabels = this.RetrieveOptionSetMetaDataCollection(entityLogicalName, attributeName);

            foreach (OptionMetadata optionMetdaData in optionsSetLabels)
            {
                if (optionMetdaData.Value == optionSetValue)
                {
                    returnLabel = optionMetdaData.Label.UserLocalizedLabel.Label;
                    break;
                }
            }

            return(returnLabel);
        }
Exemplo n.º 28
0
        protected OptionMetadataCollection ParseOptions(string options)
        {
            var result = new OptionMetadataCollection();

            foreach (var option in options.Split(';'))
            {
                var tokens = option.Split('|');
                if (tokens.Length > 1)
                {
                    var metadata = new OptionMetadata
                    {
                        Label = new Label(tokens[0], LcId),
                        Value = Convert.ToInt32(tokens[1])
                    };
                    result.Add(metadata);
                }
            }
            return(result);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Get PickList Metadata
        /// </summary>
        /// <param name="entityLogicalName"></param>
        /// <param name="logicalName"></param>
        /// <returns></returns>
        private static OptionMetadataCollection _GetPicklistMetaData(string entityLogicalName, string logicalName)
        {
            var result = new OptionMetadataCollection();

            RetrieveAttributeRequest request = new RetrieveAttributeRequest();

            request.EntityLogicalName     = entityLogicalName;
            request.LogicalName           = logicalName; // get the reference type
            request.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse response;

            try
            {
                using (OrganizationService svc = new OrganizationService(new CrmConnection("Crm")))
                {
                    response = (RetrieveAttributeResponse)svc.Execute(request);
                }

                if (response.AttributeMetadata is StatusAttributeMetadata)
                {
                    StatusAttributeMetadata  picklist = (StatusAttributeMetadata)response.AttributeMetadata;
                    OptionMetadataCollection omd      = picklist.OptionSet.Options;
                    result = omd;
                }
                else
                {
                    PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;
                    OptionMetadataCollection  omd      = picklist.OptionSet.Options;
                    result = omd;
                }
                return(result);
            }
            catch (Exception ex)
            {
                Util.WriteErrorToLog("_GetPicklistMetaData", new Dictionary <string, string>()
                {
                    { "entityLogicalName", entityLogicalName },
                    { "logicalName", logicalName }
                }, ex);
                throw ex;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Remove optionSet values no longer existing in application
        /// </summary>
        /// <param name="optionSet">OptionSet to clean</param>
        /// <param name="omc">List of all optionsets</param>
        /// <param name="settings">Settings for optionSets sync</param>
        private void CleanOption(AttributeMetadata optionSet, OptionMetadataCollection omc, Settings settings)
        {
            var schemaName = settings.AllMetadata.First(e => e.LogicalName == optionSet.EntityLogicalName).SchemaName;

            var existingOptions = Service.RetrieveMultiple(new QueryExpression("gap_powerbioptionsetref")
            {
                NoLock    = true,
                ColumnSet = new ColumnSet("gap_value"),
                Criteria  = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression("gap_entityschemaname",    ConditionOperator.Equal, schemaName),
                        new ConditionExpression("gap_optionsetschemaname", ConditionOperator.Equal, optionSet.SchemaName),
                    }
                }
            }).Entities;

            var bulkDeleteRequest = new ExecuteMultipleRequest
            {
                Settings = new ExecuteMultipleSettings
                {
                    ContinueOnError = true,
                    ReturnResponses = false
                },
                Requests = new OrganizationRequestCollection()
            };

            foreach (var record in existingOptions)
            {
                if (omc.Any(o => o.Value.HasValue && o.Value.Value == record.GetAttributeValue <int>("gap_value")))
                {
                    continue;
                }

                bulkDeleteRequest.Requests.Add(new DeleteRequest {
                    Target = record.ToEntityReference()
                });
            }

            Service.Execute(bulkDeleteRequest);
        }
 private string GetOptionSetLabelFromValue(OptionMetadataCollection optionMetadataCollection, int value)
 {
     foreach (OptionMetadata optionMetadata in optionMetadataCollection)
     {
         if (optionMetadata.Value.HasValue && optionMetadata.Value == value)
             return optionMetadata.Label.UserLocalizedLabel.Label;
     }
     return string.Empty;
 }
Exemplo n.º 32
0
 private OptionMetadataCollection GetOptionMetadataCollection(AttributeTemplate attributeTemplate)
 {
     var optionMetadataCollection = new OptionMetadataCollection();
     if (attributeTemplate.OptionSetList != null)
     {
         foreach (var optionMetadataTemplate in attributeTemplate.OptionSetList)
         {
             var optionMetadata = new OptionMetadata
             {
                 Description = GetLabelWithLocalized(optionMetadataTemplate.Description),
                 Label = GetLabelWithLocalized(optionMetadataTemplate.Label),
                 Value = optionMetadataTemplate.Value
             };
             optionMetadataCollection.Add(optionMetadata);
         }
     }
     return optionMetadataCollection;
 }
Exemplo n.º 33
0
        /// <summary>
        /// Create a dictionary with all option metadata with key = optionalSetValue, val = text label
        /// </summary>
        /// <param name="omd"></param>
        /// <returns></returns>
        private static Dictionary<string, string> _ProcessMetadataDict(OptionMetadataCollection omd)
        {
            try
            {
                var resultDict = new Dictionary<string, string>();

                foreach (var option in omd)
                {
                    string label = option.Label.UserLocalizedLabel.Label;
                    string value = option.Value.ToString();
                    resultDict.Add(value, label);
                }
                return resultDict;
            }
            catch (Exception ex)
            {
                Util.WriteErrorToLog("_ProcessMetadataDict", new Dictionary<string, string>(), ex);
                throw ex;
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Get PickList Metadata
        /// </summary>
        /// <param name="entityLogicalName"></param>
        /// <param name="logicalName"></param>
        /// <returns></returns>
        private static OptionMetadataCollection _GetPicklistMetaData(string entityLogicalName, string logicalName)
        {
            var result = new OptionMetadataCollection();

            RetrieveAttributeRequest request = new RetrieveAttributeRequest();
            request.EntityLogicalName = entityLogicalName;
            request.LogicalName = logicalName; // get the reference type
            request.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse response;

            try
            {
                using (OrganizationService svc = new OrganizationService(new CrmConnection("Crm")))
                {
                    response = (RetrieveAttributeResponse)svc.Execute(request);
                }

                if (response.AttributeMetadata is StatusAttributeMetadata)
                {
                    StatusAttributeMetadata picklist = (StatusAttributeMetadata)response.AttributeMetadata;
                    OptionMetadataCollection omd = picklist.OptionSet.Options;
                    result = omd;
                }
                else
                {
                    PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;
                    OptionMetadataCollection omd = picklist.OptionSet.Options;
                    result = omd;
                }
                return result;

            }
            catch (Exception ex)
            {
                Util.WriteErrorToLog("_GetPicklistMetaData", new Dictionary<string, string>()
                    {
                        { "entityLogicalName", entityLogicalName },
                        { "logicalName", logicalName}
                    }, ex);
                throw ex;
            }
        }