/// <summary>
        /// Get a request to add to the batch.
        /// </summary>
        /// <param name="option">The option for the request.</param>
        /// <param name="operation">The operation we are doing.</param>
        /// <returns>The request created.</returns>
        private static OrganizationRequest GetRequest(EntityItem option, Operation operation)
        {
            OrganizationRequest request = null;

            switch (operation)
            {
            case Operation.Insert:
                request = new InsertOptionValueRequest
                {
                    OptionSetName        = option.Parent.GlobalName,
                    EntityLogicalName    = option.Parent.Global ? null : option.Parent.Parent.LogicalName,
                    AttributeLogicalName = option.Parent.Global ? null : option.Parent.LogicalName,
                    Value       = option.Value,
                    Label       = option.Label,
                    Description = option.Description
                };
                break;

            case Operation.Update:
                request = new UpdateOptionValueRequest
                {
                    OptionSetName        = option.Parent.GlobalName,
                    EntityLogicalName    = option.Parent.Global ? null : option.Parent.Parent.LogicalName,
                    AttributeLogicalName = option.Parent.Global ? null : option.Parent.LogicalName,
                    Value       = option.Value,
                    Label       = option.Label,
                    Description = option.Description
                };

                break;

            case Operation.Delete:
                request = new DeleteOptionValueRequest
                {
                    OptionSetName        = option.GlobalName,
                    EntityLogicalName    = option.Global ? null : option.Parent.LogicalName,
                    AttributeLogicalName = option.Global ? null : option.LogicalName,
                    Value = option.Value
                };

                break;

            default:
                break;
            }

            return(request);
        }
示例#2
0
        /// <summary>
        /// Global OptionSet의 Options 값을 Insert or Update
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private OrganizationResponse InsertOrUpdateForOptionSetOptions(DtoOptionSet dto)
        {
            try
            {
                OrganizationResponse response = null;
                OptionMetadata[]     options  = RetrieveGlobalOptionSetOptions(dto.SchemaName);

                // Add a label and value to Global OptionSet
                foreach (var o in dto.Options)
                {
                    var optionCnt = options.Where(a => a.Value == o.Value).Count();

                    if (optionCnt == 0)
                    {
                        InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest
                        {
                            OptionSetName = dto.SchemaName,
                            Value         = o.Value,                     // optional value - if ommited one will get assigned automatically
                            Label         = new Label(o.Label, _languageCode),
                            Description   = new Label(o.Description ?? string.Empty, _languageCode)
                        };

                        response = _orgService.Execute(insertOptionValueRequest);
                        //	int retVal = ((InsertOptionValueResponse)_orgService.Execute(insertOptionValueRequest)).NewOptionValue;
                    }
                    else                     // (optionCnt > 0)
                    {
                        UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest
                        {
                            OptionSetName = dto.SchemaName,
                            Value         = o.Value,                     // optional value - if ommited one will get assigned automatically
                            Label         = new Label(o.Label, _languageCode),
                            Description   = new Label(o.Description ?? string.Empty, _languageCode)
                        };

                        response = _orgService.Execute(updateOptionValueRequest);
                    }
                }

                return(response);
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#3
0
        public bool addOptionUpdateRequest(string[] row, List <CrmOperation> crmOp, OptionMetadata optionToCompare)
        {
            int valueresult;

            if (!int.TryParse(row[ExcelColumsDefinition.OPTIONSETVALUEEXCELCOL], out valueresult))
            {
                return(false);
            }
            if (Utils.getLocalizedLabel(optionToCompare.Label.LocalizedLabels, languageCode) != row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL])
            {
                UpdateOptionValueRequest updateOptionValueRequest;
                if (optionMetadata.optionData.IsGlobal.Value)
                {
                    updateOptionValueRequest =
                        new UpdateOptionValueRequest
                    {
                        OptionSetName = optionMetadata.optionData.Name,
                        Label         = new Label(row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL], _languageCode),
                        MergeLabels   = true,
                        Value         = valueresult
                    };
                }
                else
                {
                    updateOptionValueRequest = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = optionMetadata.parentAttribute.LogicalName,
                        EntityLogicalName    = optionMetadata.parentAttribute.EntityLogicalName,
                        Label       = new Label(row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL], _languageCode),
                        MergeLabels = true,
                        Value       = valueresult
                    };
                }
                crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.create, CrmOperation.CrmOperationTarget.optionSet, updateOptionValueRequest, string.Format("Update OptionSet {0}", row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL])));
            }
            return(true);
        }
示例#4
0
 public void UpdatePicklistOptions(string fieldName, string recordType,
     IEnumerable<KeyValuePair<int, string>> optionSet)
 {
     if (optionSet.Any())
     {
         var existingOptions = GetPicklistKeyValues(recordType, fieldName);
         var itemUpdated = false;
         foreach (var option in existingOptions)
         {
             if (!optionSet.Any(o => o.Key == option.Key))
             {
                 var request = new DeleteOptionValueRequest
                 {
                     AttributeLogicalName = fieldName,
                     EntityLogicalName = recordType,
                     Value = option.Key
                 };
                 Execute(request);
                 itemUpdated = true;
             }
             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
                 {
                     AttributeLogicalName = fieldName,
                     EntityLogicalName = recordType,
                     Value = option.Key,
                     Label = new Label(newValue.Value, 1033)
                 };
                 Execute(request);
                 itemUpdated = true;
             }
         }
         foreach (var option in optionSet)
         {
             if (!existingOptions.Any(o => o.Key == option.Key))
             {
                 var request = new InsertOptionValueRequest
                 {
                     AttributeLogicalName = fieldName,
                     EntityLogicalName = recordType,
                     Value = option.Key,
                     Label = new Label(option.Value, 1033)
                 };
                 Execute(request);
                 itemUpdated = true;
             }
         }
         if (itemUpdated)
             RefreshFieldMetadata(fieldName, recordType);
     }
 }
        private void SaveGlobalOptionSet()
        {
            WorkAsync("Saving global optionset...",
                (w, e) =>
                {
                    var req = new RetrieveOptionSetRequest()
                    {
                        Name = ((Item)cboOptionSets.SelectedItem).Value,
                    };
                    var resp = (RetrieveOptionSetResponse)Service.Execute(req);
                    OptionSetMetadata md = (OptionSetMetadata)resp.OptionSetMetadata;

                    //foreach (var option in md.Options)
                    //{
                    //    var delReq = new DeleteOptionValueRequest()
                    //    {
                    //        OptionSetName = md.Name,
                    //        Value = option.Value.Value
                    //    };
                    //    Service.Execute(delReq);
                    //}

                    var data = (BindingList<Item>)dgvOptions.DataSource;

                    var execMultiReq = new ExecuteMultipleRequest()
                    {
                        Settings = new Microsoft.Xrm.Sdk.ExecuteMultipleSettings()
                        {
                            ContinueOnError = true,
                            ReturnResponses = false
                        },
                        Requests = new Microsoft.Xrm.Sdk.OrganizationRequestCollection()
                    };

                    foreach (var item in data)
                    {
                        var exists = (from o in md.Options where o.Value.Value == int.Parse(item.Value) select true).FirstOrDefault();
                        if (exists)
                        {
                            var upReq = new UpdateOptionValueRequest()
                            {
                                OptionSetName = md.Name,
                                Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033),
                                Value = int.Parse(item.Value)
                            };
                            execMultiReq.Requests.Add(upReq);
                        }
                        else
                        {
                            var addReq = new InsertOptionValueRequest()
                            {
                                OptionSetName = md.Name,
                                Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033),
                                Value = int.Parse(item.Value)
                            };
                            execMultiReq.Requests.Add(addReq);
                        }
                    }

                    foreach (var item in md.Options)
                    {
                        var exists = (from d in data where int.Parse(d.Value) == item.Value.Value select true).FirstOrDefault();
                        if (!exists)
                        {
                            var delReq = new DeleteOptionValueRequest()
                            {
                                OptionSetName = md.Name,
                                Value = item.Value.Value
                            };
                            execMultiReq.Requests.Add(delReq);
                        }
                    }

                    Service.Execute(execMultiReq);

                    w.ReportProgress(50, "Publishing global optionset...");

                    PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", md.Name) };
                    Service.Execute(pxReq1);
                },
                e =>
                {
                },
                e =>
                {
                    SetWorkingMessage(e.UserState.ToString());
                }
            );
        }
        /// <summary>
        /// Create a global option set.
        /// Set the options for that option set.
        /// Create a new reference to that option set on an entity.
        /// Update the option set's properties.
        /// Check the global option set for dependencies.
        /// Delete the option set.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    #region How to create global option set
                    // Define the request object and pass to the service.
                    CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name          = _globalOptionSetName,
                            DisplayName   = new Label("Example Option Set", _languageCode),
                            IsGlobal      = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(new Label("Open",      _languageCode), null),
                                new OptionMetadata(new Label("Suspended", _languageCode), null),
                                new OptionMetadata(new Label("Cancelled", _languageCode), null),
                                new OptionMetadata(new Label("Closed",    _languageCode), null)
                            }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest);

                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    CreateAttributeRequest createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute  = new PicklistAttributeMetadata
                        {
                            SchemaName    = "sample_examplepicklist",
                            LogicalName   = "sample_examplepicklist",
                            DisplayName   = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name     = _globalOptionSetName
                            }
                        }
                    };

                    _serviceProxy.Execute(createRequest);
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name        = _globalOptionSetName,
                            IsGlobal    = true
                        }
                    };

                    _serviceProxy.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq1 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq1);
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    // Use InsertOptionValueRequest to insert a new option into a
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        Label         = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request and store the newly inserted option value
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                                                insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq2);
                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    // Use the RetrieveOptionSetRequest message to retrieve
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                    {
                        Name = _globalOptionSetName
                    };

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

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

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

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        // Update the second option value.
                        Value = optionList[1].Value.Value,
                        Label = new Label("Updated Option 1", _languageCode)
                    };

                    _serviceProxy.Execute(updateOptionValueRequest);

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



                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    _serviceProxy.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq4);
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)_serviceProxy.Execute(
                            retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                                 retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                              (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    #endregion How to retrieve all global option sets



                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
示例#7
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service)
        {
            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName    = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value       = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString()),
                        Label       = new Label(),
                        Description = new Label(),
                        MergeLabels = true
                    };

                    int columnIndex = 5;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 5;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            foreach (var request in requests)
            {
                service.Execute(request);
            }
        }
示例#8
0
        public void Import(ExcelWorksheet sheet, List <EntityMetadata> emds, IOrganizationService service, BackgroundWorker worker)
        {
            OnLog(new LogEventArgs($"Reading {sheet.Name}"));

            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                if (HasEmptyCells(sheet, rowI, 5))
                {
                    continue;
                }

                var value = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString());

                var emd = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                if (emd == null)
                {
                    var mdRequest = new RetrieveEntityRequest
                    {
                        LogicalName   = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships
                    };

                    var response = ((RetrieveEntityResponse)service.Execute(mdRequest));
                    emd = response.EntityMetadata;

                    emds.Add(emd);
                }

                var            amd    = emd.Attributes.FirstOrDefault(a => a.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString());
                OptionMetadata option = null;
                if (amd is PicklistAttributeMetadata pamd)
                {
                    option = pamd.OptionSet.Options.FirstOrDefault(o => o.Value == value);
                }
                else if (amd is StateAttributeMetadata samd)
                {
                    option = samd.OptionSet.Options.FirstOrDefault(o => o.Value == value);
                }
                else if (amd is StatusAttributeMetadata ssamd)
                {
                    option = ssamd.OptionSet.Options.FirstOrDefault(o => o.Value == value);
                }

                if (option == null)
                {
                    OnLog(new LogEventArgs($"Unable to determine type of the AttributeMetadata for attribute {amd.LogicalName}")
                    {
                        Type = LogType.Error
                    });
                    continue;
                }

                UpdateOptionValueRequest request =
                    requests
                    .FirstOrDefault(
                        r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString() &&
                        r.Value == value);

                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName    = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value       = value,
                        Label       = option.Label ?? new Label(),
                        Description = option.Description ?? new Label(),
                        MergeLabels = true
                    };

                    requests.Add(request);
                }

                int columnIndex = 6;

                if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Label")
                {
                    // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                    while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                    {
                        var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                        var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                        var translatedLabel = request.Label.LocalizedLabels.FirstOrDefault(x => x.LanguageCode == lcid);
                        if (translatedLabel == null)
                        {
                            translatedLabel = new LocalizedLabel(label, lcid);
                            request.Label.LocalizedLabels.Add(translatedLabel);
                        }
                        else
                        {
                            translatedLabel.Label = label;
                        }
                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Description")
                {
                    // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                    while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                    {
                        var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                        var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                        var translatedLabel = request.Description.LocalizedLabels.FirstOrDefault(x => x.LanguageCode == lcid);
                        if (translatedLabel == null)
                        {
                            translatedLabel = new LocalizedLabel(label, lcid);
                            request.Description.LocalizedLabels.Add(translatedLabel);
                        }
                        else
                        {
                            translatedLabel.Label = label;
                        }
                        columnIndex++;
                    }
                }
            }

            OnLog(new LogEventArgs($"Importing {sheet.Name} translations"));

            var arg = new TranslationProgressEventArgs {
                SheetName = sheet.Name
            };

            foreach (var request in requests)
            {
                AddRequest(request);
                ExecuteMultiple(service, arg, requests.Count);
            }
            ExecuteMultiple(service, arg, requests.Count, true);
        }
        public void Import(ExcelWorksheet sheet, IOrganizationService service, BackgroundWorker worker)
        {
            OnLog(new LogEventArgs {
                Message = "Started global optionset import", Type = LogType.Info
            });
            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString() &&
                                                                           r.Value == int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString()));
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        OptionSetName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value         = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString()),
                        Label         = new Label(),
                        Description   = new Label(),
                        MergeLabels   = true
                    };

                    int columnIndex = 4;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                var ll = request.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == int.Parse(sLcid));
                                if (ll != null)
                                {
                                    ll.Label = sLabel;
                                }
                                else
                                {
                                    request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                                }
                            }

                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                var ll = request.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == int.Parse(sLcid));
                                if (ll != null)
                                {
                                    ll.Label = sLabel;
                                }
                                else
                                {
                                    request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                                }
                            }

                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 4;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                var ll = request.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == int.Parse(sLcid));
                                if (ll != null)
                                {
                                    ll.Label = sLabel;
                                }
                                else
                                {
                                    request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                                }
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                var ll = request.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == int.Parse(sLcid));
                                if (ll != null)
                                {
                                    ll.Label = sLabel;
                                }
                                else
                                {
                                    request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                                }
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            var arg = new TranslationProgressEventArgs {
                SheetName = sheet.Name
            };

            foreach (var request in requests)
            {
                AddRequest(request);
                //ExecuteMultiple(service, arg);
            }
            ExecuteMultiple(service, arg, true);
            OnLog(new LogEventArgs {
                Message = "Completed global optionset import", Type = LogType.Info
            });
        }
示例#10
0
        /// <summary>
        /// Create a global option set.
        /// Set the options for that option set.
        /// Create a new reference to that option set on an entity.
        /// Update the option set's properties.
        /// Check the global option set for dependencies.
        /// Delete the option set.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetWorkwithGlobalOptionSets1>
                    //<snippetWorkwithGlobalOptionSets2>
                    #region How to create global option set
                    // Define the request object and pass to the service.
                    CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name = _globalOptionSetName,
                            DisplayName = new Label("Example Option Set", _languageCode),
                            IsGlobal = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options = 
                        {
                            new OptionMetadata(new Label("Open", _languageCode), null),
                            new OptionMetadata(new Label("Suspended", _languageCode), null),
                            new OptionMetadata(new Label("Cancelled", _languageCode), null),
                            new OptionMetadata(new Label("Closed", _languageCode), null)
                        }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest);

                    //</snippetWorkwithGlobalOptionSets2>
                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    //<snippetWorkwithGlobalOptionSets3>
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    CreateAttributeRequest createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute = new PicklistAttributeMetadata
                        {
                            SchemaName = "sample_examplepicklist",
                            LogicalName = "sample_examplepicklist",
                            DisplayName = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name = _globalOptionSetName
                            }
                        }
                    };

                    _serviceProxy.Execute(createRequest);
                    //</snippetWorkwithGlobalOptionSets3>
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    //<snippetWorkwithGlobalOptionSets4>
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name = _globalOptionSetName,
                            IsGlobal = true
                        }
                    };

                    _serviceProxy.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq1);
                    //</snippetWorkwithGlobalOptionSets4>
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    //<snippetWorkwithGlobalOptionSets5>
                    // Use InsertOptionValueRequest to insert a new option into a 
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                        {
                            OptionSetName = _globalOptionSetName,
                            Label = new Label("New Picklist Label", _languageCode)
                        };

                    // Execute the request and store the newly inserted option value 
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                        insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq2);
                    //</snippetWorkwithGlobalOptionSets5>
                    Console.WriteLine("Created {0} with the value of {1}.",
                        insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                        _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    //<snippetWorkwithGlobalOptionSets6>
                    // Use the RetrieveOptionSetRequest message to retrieve  
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                        {
                            Name = _globalOptionSetName
                        };

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

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

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

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    //</snippetWorkwithGlobalOptionSets6>
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    //<snippetWorkwithGlobalOptionSets7>
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest 
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                        {
                            OptionSetName = _globalOptionSetName,
                            // Update the second option value.
                            Value = optionList[1].Value.Value,
                            Label = new Label("Updated Option 1", _languageCode)
                        };

                    _serviceProxy.Execute(updateOptionValueRequest);

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

                    

                    //</snippetWorkwithGlobalOptionSets7>
                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    //<snippetWorkwithGlobalOptionSets8>
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in  
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function 
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    _serviceProxy.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq4);
                    //</snippetWorkwithGlobalOptionSets8>
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    //<snippetWorkwithGlobalOptionSets9>
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)_serviceProxy.Execute(
                        retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to 
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                            retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                (optionSetMetadata.DisplayName.LocalizedLabels.Count >0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    //</snippetWorkwithGlobalOptionSets9>
                    #endregion How to retrieve all global option sets


                    //</snippetWorkwithGlobalOptionSets1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        public void Import(ExcelWorksheet sheet, IOrganizationService service)
        {
            var requests = new List<UpdateOptionValueRequest>();

            foreach (ExcelRow row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == row.Cells[1].Value.ToString()
                    && r.Value == int.Parse(row.Cells[2].Value.ToString()));
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                                  {
                                      OptionSetName = row.Cells[1].Value.ToString(),
                                      Value = int.Parse(row.Cells[2].Value.ToString()),
                                      Label = new Label(),
                                      Description = new Label(),
                                      MergeLabels = true
                                  };

                    int columnIndex = 4;

                    if (row.Cells[3].Value.ToString() == "Label")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }

                            columnIndex++;
                        }
                    }
                    else if (row.Cells[3].Value.ToString() == "Description")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }

                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 4;

                    if (row.Cells[3].Value.ToString() == "Label")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (row.Cells[3].Value.ToString() == "Description")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            foreach (var request in requests)
            {
                service.Execute(request);
            }
        }
示例#12
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service)
        {
            var requests = new List <UpdateOptionValueRequest>();

            foreach (ExcelRow row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == row.Cells[1].Value.ToString() &&
                                                                           r.Value == int.Parse(row.Cells[2].Value.ToString()));
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        OptionSetName = row.Cells[1].Value.ToString(),
                        Value         = int.Parse(row.Cells[2].Value.ToString()),
                        Label         = new Label(),
                        Description   = new Label(),
                        MergeLabels   = true
                    };

                    int columnIndex = 4;

                    if (row.Cells[3].Value.ToString() == "Label")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }

                            columnIndex++;
                        }
                    }
                    else if (row.Cells[3].Value.ToString() == "Description")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }

                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 4;

                    if (row.Cells[3].Value.ToString() == "Label")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (row.Cells[3].Value.ToString() == "Description")
                    {
                        while (row.Cells.Count() > columnIndex && row.Cells[columnIndex] != null && row.Cells[columnIndex].Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = row.Cells[columnIndex].Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            foreach (var request in requests)
            {
                service.Execute(request);
            }
        }
示例#13
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service)
        {
            var requests = new List<UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;
            var cellsCount = sheet.Dimension.Columns;
            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString()),
                        Label = new Label(),
                        Description = new Label(),
                        MergeLabels = true
                    };

                    int columnIndex = 5;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                    {
                        while (columnIndex < cellsCount)
                        {
                            if (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                            {
                                var lcid = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                                var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                            }

                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                    {
                        while (columnIndex < cellsCount)
                        {
                            if (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                            {
                                var lcid = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                                var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                            }

                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 5;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                    {
                        while (columnIndex < cellsCount)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                    {
                        while (columnIndex < cellsCount)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            foreach (var request in requests)
            {
                service.Execute(request);
            }
        }
示例#14
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service, BackgroundWorker worker)
        {
            OnLog(new LogEventArgs($"Reading {sheet.Name}"));

            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request =
                    requests
                    .FirstOrDefault(
                        r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString() &&
                        r.Value == int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString()));

                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName    = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value       = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString()),
                        Label       = new Label(),
                        Description = new Label(),
                        MergeLabels = true
                    };

                    int columnIndex = 6;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 6;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            OnLog(new LogEventArgs($"Importing {sheet.Name} translations"));

            var arg = new TranslationProgressEventArgs {
                SheetName = sheet.Name
            };

            foreach (var request in requests)
            {
                AddRequest(request);
                ExecuteMultiple(service, arg, requests.Count);
            }
            ExecuteMultiple(service, arg, requests.Count, true);
        }
示例#15
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);
        }
        public void Import(ExcelWorksheet sheet, IOrganizationService service)
        {
            var requests = new List<UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString()
                    && r.Value == int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString()));
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        OptionSetName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString()),
                        Label = new Label(),
                        Description = new Label(),
                        MergeLabels = true
                    };

                    int columnIndex = 4;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }

                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }

                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 4;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            foreach (var request in requests)
            {
                service.Execute(request);
            }
        }
示例#17
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    // Define the request object and pass to the service.
                    var createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name          = _globalOptionSetName,
                            DisplayName   = new Label("Example Option Set", _languageCode),
                            IsGlobal      = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(new Label("Open",      _languageCode), null),
                                new OptionMetadata(new Label("Suspended", _languageCode), null),
                                new OptionMetadata(new Label("Cancelled", _languageCode), null),
                                new OptionMetadata(new Label("Closed",    _languageCode), null)
                            }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)service.Execute(createOptionSetRequest);

                    //</snippetWorkwithGlobalOptionSets2>
                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    //<snippetWorkwithGlobalOptionSets3>
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    var createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute  = new PicklistAttributeMetadata
                        {
                            SchemaName    = "sample_examplepicklist",
                            LogicalName   = "sample_examplepicklist",
                            DisplayName   = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name     = _globalOptionSetName
                            }
                        }
                    };

                    service.Execute(createRequest);
                    //</snippetWorkwithGlobalOptionSets3>
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    //<snippetWorkwithGlobalOptionSets4>
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    var updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name        = _globalOptionSetName,
                            IsGlobal    = true
                        }
                    };

                    service.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    var pxReq1 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq1);
                    //</snippetWorkwithGlobalOptionSets4>
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    //<snippetWorkwithGlobalOptionSets5>
                    // Use InsertOptionValueRequest to insert a new option into a
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        Label         = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request and store the newly inserted option value
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)service.Execute(
                                                insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq2);
                    //</snippetWorkwithGlobalOptionSets5>
                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    //<snippetWorkwithGlobalOptionSets6>
                    // Use the RetrieveOptionSetRequest message to retrieve
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                    {
                        Name = _globalOptionSetName
                    };

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

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

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

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    //</snippetWorkwithGlobalOptionSets6>
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    //<snippetWorkwithGlobalOptionSets7>
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        // Update the second option value.
                        Value = optionList[1].Value.Value,
                        Label = new Label("Updated Option 1", _languageCode)
                    };

                    service.Execute(updateOptionValueRequest);

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



                    //</snippetWorkwithGlobalOptionSets7>
                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    //<snippetWorkwithGlobalOptionSets8>
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    service.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq4);
                    //</snippetWorkwithGlobalOptionSets8>
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    //<snippetWorkwithGlobalOptionSets9>
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)service.Execute(
                            retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                                 retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                              (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
示例#18
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service, BackgroundWorker worker)
        {
            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount  = sheet.Dimension.Rows;
            var cellsCount = sheet.Dimension.Columns;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName    = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value       = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString()),
                        Label       = new Label(),
                        Description = new Label(),
                        MergeLabels = true
                    };

                    int columnIndex = 5;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                    {
                        while (columnIndex < cellsCount)
                        {
                            if (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                            {
                                var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                                var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                            }

                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                    {
                        while (columnIndex < cellsCount)
                        {
                            if (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                            {
                                var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                                var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                            }

                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 5;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                    {
                        while (columnIndex < cellsCount)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                    {
                        while (columnIndex < cellsCount)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            var arg = new TranslationProgressEventArgs {
                SheetName = sheet.Name
            };

            foreach (var request in requests)
            {
                AddRequest(request);
                ExecuteMultiple(service, arg);
            }

            ExecuteMultiple(service, arg, true);
        }
示例#19
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service, BackgroundWorker worker)
        {
            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                UpdateOptionValueRequest request =
                    requests
                    .FirstOrDefault(
                        r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString() &&
                        r.Value == int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString()));

                if (request == null)
                {
                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName    = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value       = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString()),
                        Label       = new Label(),
                        Description = new Label(),
                        MergeLabels = true
                    };

                    int columnIndex = 6;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }

                    requests.Add(request);
                }
                else
                {
                    int columnIndex = 6;

                    if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Label")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Label.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                    else if (ZeroBasedSheet.Cell(sheet, rowI, 5).Value.ToString() == "Description")
                    {
                        // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                        while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                        {
                            var sLcid  = ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString();
                            var sLabel = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                            if (sLcid.Length > 0 && sLabel.Length > 0)
                            {
                                request.Description.LocalizedLabels.Add(new LocalizedLabel(sLabel, int.Parse(sLcid)));
                            }
                            columnIndex++;
                        }
                    }
                }
            }

            int i = 0;

            foreach (var request in requests)
            {
                try
                {
                    service.Execute(request);

                    OnResult(new TranslationResultEventArgs
                    {
                        Success   = true,
                        SheetName = sheet.Name
                    });
                }
                catch (Exception error)
                {
                    OnResult(new TranslationResultEventArgs
                    {
                        Success   = false,
                        SheetName = sheet.Name,
                        Message   = $"{request.EntityLogicalName}/{request.AttributeLogicalName}: {error.Message}"
                    });
                }

                i++;
                worker.ReportProgressIfPossible(0, new ProgressInfo
                {
                    Item = i * 100 / requests.Count
                });
            }
        }
示例#20
0
        public void Import(ExcelWorksheet sheet, List <EntityMetadata> emds, IOrganizationService service, BackgroundWorker worker)
        {
            OnLog(new LogEventArgs($"Reading {sheet.Name}"));

            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount  = sheet.Dimension.Rows;
            var cellsCount = sheet.Dimension.Columns;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                if (HasEmptyCells(sheet, rowI, 4))
                {
                    continue;
                }

                var value = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString());

                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.EntityLogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString() &&
                                                                           r.AttributeLogicalName == ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString() &&
                                                                           r.Value == value);

                if (request == null)
                {
                    var emd = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                    if (emd == null)
                    {
                        var mdRequest = new RetrieveEntityRequest
                        {
                            LogicalName   = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(mdRequest));
                        emd = response.EntityMetadata;

                        emds.Add(emd);
                    }

                    var amd       = (BooleanAttributeMetadata)emd.Attributes.FirstOrDefault(a => a.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString());
                    var dLabel    = (value == 0 ? amd?.OptionSet.FalseOption.Label : amd?.OptionSet.TrueOption.Label) ?? new Label();
                    var descLabel = (value == 0 ? amd?.OptionSet.FalseOption.Description : amd?.OptionSet.TrueOption.Description) ?? new Label();

                    request = new UpdateOptionValueRequest
                    {
                        AttributeLogicalName = ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(),
                        EntityLogicalName    = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        Value       = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString()),
                        Label       = dLabel,
                        Description = descLabel,
                        MergeLabels = true
                    };

                    requests.Add(request);
                }

                int columnIndex = 5;

                if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Label")
                {
                    while (columnIndex < cellsCount)
                    {
                        var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                        var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                        if (label.Length > 0)
                        {
                            var translatedLabel = request.Label.LocalizedLabels.FirstOrDefault(x => x.LanguageCode == lcid);
                            if (translatedLabel == null)
                            {
                                translatedLabel = new LocalizedLabel(label, lcid);
                                request.Label.LocalizedLabels.Add(translatedLabel);
                            }
                            else
                            {
                                translatedLabel.Label = label;
                            }
                        }
                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 4).Value.ToString() == "Description")
                {
                    while (columnIndex < cellsCount)
                    {
                        var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                        var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                        if (label.Length > 0)
                        {
                            var translatedLabel = request.Description.LocalizedLabels.FirstOrDefault(x => x.LanguageCode == lcid);
                            if (translatedLabel == null)
                            {
                                translatedLabel = new LocalizedLabel(label, lcid);
                                request.Description.LocalizedLabels.Add(translatedLabel);
                            }
                            else
                            {
                                translatedLabel.Label = label;
                            }
                        }
                        columnIndex++;
                    }
                }
            }

            OnLog(new LogEventArgs($"Importing {sheet.Name} translations"));

            var arg = new TranslationProgressEventArgs {
                SheetName = sheet.Name
            };

            foreach (var request in requests)
            {
                AddRequest(request);
                ExecuteMultiple(service, arg, requests.Count);
            }

            ExecuteMultiple(service, arg, requests.Count, true);
        }
        public void Import(ExcelWorksheet sheet, IOrganizationService service, BackgroundWorker worker)
        {
            OnLog(new LogEventArgs($"Reading {sheet.Name}"));

            var requests = new List <UpdateOptionValueRequest>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                if (HasEmptyCells(sheet, rowI, 3))
                {
                    continue;
                }

                var value = int.Parse(ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString());

                UpdateOptionValueRequest request = requests.FirstOrDefault(r => r.OptionSetName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString() &&
                                                                           r.Value == value);

                if (request == null)
                {
                    var md = ((RetrieveOptionSetResponse)service.Execute(new RetrieveOptionSetRequest
                    {
                        Name = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                        RetrieveAsIfPublished = true
                    })).OptionSetMetadata;

                    if (md is OptionSetMetadata osm)
                    {
                        var option = osm.Options.FirstOrDefault(o => o.Value == value);

                        request = new UpdateOptionValueRequest
                        {
                            OptionSetName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            Value         = value,
                            Label         = option?.Label ?? new Label(),
                            Description   = option?.Description ?? new Label(),
                            MergeLabels   = true
                        };
                    }
                    else if (md is BooleanOptionSetMetadata bosm)
                    {
                        var option = value == 0 ? bosm.FalseOption : bosm.TrueOption;

                        request = new UpdateOptionValueRequest
                        {
                            OptionSetName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            Value         = value,
                            Label         = option?.Label ?? new Label(),
                            Description   = option?.Description ?? new Label(),
                            MergeLabels   = true
                        };
                    }

                    requests.Add(request);
                }

                int columnIndex = 4;

                if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Label")
                {
                    // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                    while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                    {
                        var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                        var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                        var translatedLabel = request.Label.LocalizedLabels.FirstOrDefault(x => x.LanguageCode == lcid);
                        if (translatedLabel == null)
                        {
                            translatedLabel = new LocalizedLabel(label, lcid);
                            request.Label.LocalizedLabels.Add(translatedLabel);
                        }
                        else
                        {
                            translatedLabel.Label = label;
                        }

                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                {
                    // WTF: QUESTIONABLE DELETION: row.Cells.Count() > columnIndex &&
                    while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex) != null && ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                    {
                        var lcid  = int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString());
                        var label = ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString();

                        var translatedLabel = request.Description.LocalizedLabels.FirstOrDefault(x => x.LanguageCode == lcid);
                        if (translatedLabel == null)
                        {
                            translatedLabel = new LocalizedLabel(label, lcid);
                            request.Description.LocalizedLabels.Add(translatedLabel);
                        }
                        else
                        {
                            translatedLabel.Label = label;
                        }

                        columnIndex++;
                    }
                }
            }

            OnLog(new LogEventArgs($"Importing {sheet.Name} translations"));

            var arg = new TranslationProgressEventArgs {
                SheetName = sheet.Name
            };

            foreach (var request in requests)
            {
                AddRequest(request);
                ExecuteMultiple(service, arg, requests.Count);
            }
            ExecuteMultiple(service, arg, requests.Count, true);
        }