示例#1
8
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create few types of attributes.
        /// Insert status in the existing status list.
        /// Retrieve attribute.
        /// Update attribute.
        /// Update existing state value.
        /// Optionally delete/revert any attributes 
        /// that were created/changed for this sample.
         /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

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

                    //<snippetWorkWithAttributes1>
                    #region How to create attributes
                    //<snippetWorkWithAttributes2>
                    // Create storage for new attributes being created
                    addedAttributes = new List<AttributeMetadata>();

                    // Create a boolean attribute
                    BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_boolean",
                        DisplayName = new Label("Sample Boolean", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Boolean Attribute", _languageCode),
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Label("True", _languageCode), 1),
                            new OptionMetadata(new Label("False", _languageCode), 0)
                            )
                    };

                    // Add to list
                    addedAttributes.Add(boolAttribute);

                    // Create a date time attribute
                    DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_datetime",
                        DisplayName = new Label("Sample DateTime", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("DateTime Attribute", _languageCode),
                        // Set extended properties
                        Format = DateTimeFormat.DateOnly,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(dtAttribute);

                    // Create a decimal attribute	
                    DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_decimal",
                        DisplayName = new Label("Sample Decimal", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Decimal Attribute", _languageCode),
                        // Set extended properties
                        MaxValue = 100,
                        MinValue = 0,
                        Precision = 1
                    };

                    // Add to list
                    addedAttributes.Add(decimalAttribute);

                    // Create a integer attribute	
                    IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_integer",
                        DisplayName = new Label("Sample Integer", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Integer Attribute", _languageCode),
                        // Set extended properties
                        Format = IntegerFormat.None,
                        MaxValue = 100,
                        MinValue = 0
                    };

                    // Add to list
                    addedAttributes.Add(integerAttribute);

                    // Create a memo attribute 
                    MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_memo",
                        DisplayName = new Label("Sample Memo", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Memo Attribute", _languageCode),
                        // Set extended properties
                        Format = StringFormat.TextArea,
                        ImeMode = ImeMode.Disabled,
                        MaxLength = 500
                    };

                    // Add to list
                    addedAttributes.Add(memoAttribute);

                    // Create a money attribute	
                    MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_money",
                        DisplayName = new Label("Money Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Money Attribue", _languageCode),
                        // Set extended properties
                        MaxValue = 1000.00,
                        MinValue = 0.00,
                        Precision = 1,
                        PrecisionSource = 1,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(moneyAttribute);

                    // Create a picklist attribute	
                    PicklistAttributeMetadata pickListAttribute =
                        new PicklistAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_picklist",
                        DisplayName = new Label("Sample Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("Picklist Attribute", _languageCode),
                        // Set extended properties
                        // Build local picklist options
                        OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = false,
                                OptionSetType = OptionSetType.Picklist,
                                Options = 
                            {
                                new OptionMetadata(
                                    new Label("Created", _languageCode), null),
                                new OptionMetadata(
                                    new Label("Updated", _languageCode), null),
                                new OptionMetadata(
                                    new Label("Deleted", _languageCode), null)
                            }
                            }
                    };

                    // Add to list
                    addedAttributes.Add(pickListAttribute);

                    // Create a string attribute
                    StringAttributeMetadata stringAttribute = new StringAttributeMetadata
                    {
                        // Set base properties
                        SchemaName = "new_string",
                        DisplayName = new Label("Sample String", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description = new Label("String Attribute", _languageCode),
                        // Set extended properties
                        MaxLength = 100
                    };

                    // Add to list
                    addedAttributes.Add(stringAttribute);

                    // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship.
                    // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type.

                    // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK.

                    foreach (AttributeMetadata anAttribute in addedAttributes)
                    {
                        // Create the request.
                        CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = Contact.EntityLogicalName,
                            Attribute = anAttribute
                        };

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

                        Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName);
                    }
                    //</snippetWorkWithAttributes2>
                    #endregion How to create attributes

                    #region How to insert status
                    //<snippetWorkWithAttributes3>
                    // Use InsertStatusValueRequest message to insert a new status 
                    // in an existing status attribute. 
                    // Create the request.
                    InsertStatusValueRequest insertStatusValueRequest =
                        new InsertStatusValueRequest
                    {
                        AttributeLogicalName = "statuscode",
                        EntityLogicalName = Contact.EntityLogicalName,
                        Label = new Label("Dormant", _languageCode),
                        StateCode = 0
                    };

                    // Execute the request and store newly inserted value 
                    // for cleanup, used later part of this sample. 
                    _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute(
                        insertStatusValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                        insertStatusValueRequest.Label.LocalizedLabels[0].Label,
                        _insertedStatusValue);
                    //</snippetWorkWithAttributes3>
                    #endregion How to insert status

                    #region How to retrieve attribute
                    //<snippetWorkWithAttributes4>
                    // Create the request
                    RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName = Contact.EntityLogicalName,
                        LogicalName = "new_string",
                        RetrieveAsIfPublished = true
                    };

                    // Execute the request
                    RetrieveAttributeResponse attributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

                    Console.WriteLine("Retrieved the attribute {0}.",
                        attributeResponse.AttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes4>
                    #endregion How to retrieve attribute
                    
                    #region How to update attribute
                    //<snippetWorkWithAttributes5>
                    // Modify the retrieved attribute
                    AttributeMetadata retrievedAttributeMetadata =
                        attributeResponse.AttributeMetadata;
                    retrievedAttributeMetadata.DisplayName =
                        new Label("Update String Attribute", _languageCode);

                    // Update an attribute retrieved via RetrieveAttributeRequest
                    UpdateAttributeRequest updateRequest = new UpdateAttributeRequest
                    {
                        Attribute = retrievedAttributeMetadata,
                        EntityName = Contact.EntityLogicalName,
                        MergeLabels = false
                    };

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

                    Console.WriteLine("Updated the attribute {0}.",
                        retrievedAttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes5>
                    #endregion How to update attribute

                    #region How to update state value
                    //<snippetWorkWithAttributes6>
                    // Modify the state value label from Active to Open.
                    // Create the request.
                    UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
                    {
                        AttributeLogicalName = "statecode",
                        EntityLogicalName = Contact.EntityLogicalName,
                        Value = 1,
                        Label = new Label("Open", _languageCode)
                    };

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

                    Console.WriteLine(
                        "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.",
                        updateStateValue.AttributeLogicalName,
                        updateStateValue.EntityLogicalName,
                        updateStateValue.Label.LocalizedLabels[0].Label
                        );
                    //</snippetWorkWithAttributes6>
                    #endregion How to update state value

                    #region How to insert a new option item in a local option set
                    //<snippetWorkWithAttributes7>
                    // Create a request.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        AttributeLogicalName = "new_picklist",
                        EntityLogicalName = Contact.EntityLogicalName,
                        Label = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request.
                    int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                        insertOptionValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                        insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                        insertOptionValue);
                    //</snippetWorkWithAttributes7>
                    #endregion How to insert a new option item in a local option set

                    #region How to change the order of options of a local option set
                    //<snippetWorkWithAttributes8>
                    // Use the RetrieveAttributeRequest message to retrieve  
                    // a attribute by it's logical name.
                    RetrieveAttributeRequest retrieveAttributeRequest =
                        new RetrieveAttributeRequest
                    {
                        EntityLogicalName = Contact.EntityLogicalName,
                        LogicalName = "new_picklist",
                        RetrieveAsIfPublished = true
                    };

                    // Execute the request.
                    RetrieveAttributeResponse retrieveAttributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(
                        retrieveAttributeRequest);

                    // Access the retrieved attribute.
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
                        (PicklistAttributeMetadata)
                        retrieveAttributeResponse.AttributeMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

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

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

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

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

                    Console.WriteLine("Option Set option order changed");
                    //</snippetWorkWithAttributes8>
                    #endregion How to change the order of options of a global option set

                    // NOTE: All customizations must be published before they can be used.
                    _serviceProxy.Execute(new PublishAllXmlRequest());
                    Console.WriteLine("Published all customizations.");
                    //</snippetWorkWithAttributes1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
示例#2
0
        public static void AutoNumber()
        {
            CrmServiceClient     client  = new CrmServiceClient("Url=https://revmortage.crm.dynamics.com; [email protected]; Password=9V5$m9xjm#*HDuHT; authtype=Office365");
            IOrganizationService service = (IOrganizationService)
                                           client.OrganizationWebProxyClient ?? (IOrganizationService)client.OrganizationServiceProxy;

            UpdateAttributeRequest mortgageAutoNumber = new UpdateAttributeRequest
            {
                EntityName = "mortage_mortgage",
                Attribute  = new StringAttributeMetadata
                {
                    //Define the format of the attribute
                    AutoNumberFormat = "{DATETIMEUTC:yyyyMM}-{SEQNUM:6}",
                    LogicalName      = "mortage_name",
                    SchemaName       = "mortage_name",
                    DisplayName      = new Label("Mortgage Number", 1033),
                    Description      = new Label("System generated mortgage number for this mortgage.", 1033)
                }
            };
            var result = service.Execute(mortgageAutoNumber);

            Console.WriteLine(result.ResponseName);

            foreach (var item in result.Results)
            {
                Console.WriteLine($"Key: {item.Key} — Value: {item.Value}");
            }
        }
        private void addUpdateRequest(string[] row, List <CrmOperation> crmOp, AttributeMetadata currentAttribute)
        {
            IEnumerable <IExtensibleDataObject> excelAttrMetadataList = attributeReader(row);

            if (excelAttrMetadataList.Count() > 0)
            {
                IExtensibleDataObject excelAttrMetadata = excelAttrMetadataList.First();
                if (excelAttrMetadata != null)
                {
                    if (excelAttrMetadata is AttributeMetadata || excelAttrMetadata is CreateOneToManyRequest)
                    {
                        if (excelAttrMetadata is CreateOneToManyRequest)
                        {
                            excelAttrMetadata = ((CreateOneToManyRequest)excelAttrMetadata).Lookup;
                        }
                        IEnumerable <string> fieldToCahnge = checkDifferenceAttributeMetadata(currentAttribute, excelAttrMetadata as AttributeMetadata);
                        if (fieldToCahnge != null && fieldToCahnge.Count() != 0)
                        {
                            UpdateAttributeRequest updateAttributeRequest = new UpdateAttributeRequest
                            {
                                EntityName  = filteredMetadata[0].EntityLogicalName,
                                Attribute   = currentAttribute,
                                MergeLabels = false
                            };
                            crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.update, CrmOperation.CrmOperationTarget.attribute, updateAttributeRequest, "Update field " + currentAttribute.SchemaName + " in " + filteredMetadata[0].EntityLogicalName));
                        }
                    }
                }
            }
        }
示例#4
0
        public static void Deprecate(IOrganizationService orgSvc, ComponentInfo cInfo)
        {
            Argument.IsNotNull(orgSvc, nameof(orgSvc));
            Argument.IsNotNull(cInfo, nameof(cInfo));
            Argument.IsNotNullOrEmpty(cInfo.EntityLogicalName, nameof(cInfo.EntityLogicalName));

            UpdateAttributeRequest request = CreateRequestStub(cInfo.ComponentId, cInfo.EntityLogicalName);

            if (!cInfo.Name.Contains("[DEP]"))
            {
                var newName = $"[DEP] {cInfo.Name}";
                if (newName.Length > 50)
                {
                    newName = newName.Substring(0, 50);
                }
                request = SetName(request, newName);
            }

            if (cInfo.IsValidForAdvancedFind == true)
            {
                request = SetIsValidForAdvancedFind(request, false);
            }

            if (request.Attribute.IsValidForAdvancedFind != null || request.Attribute.DisplayName != null)
            {
                orgSvc.Execute(request);
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            UpdateAttributeRequest request;

            try
            {
                request = new UpdateAttributeRequest
                {
                    CatalogId              = CatalogId,
                    DataAssetKey           = DataAssetKey,
                    EntityKey              = EntityKey,
                    AttributeKey           = AttributeKey,
                    UpdateAttributeDetails = UpdateAttributeDetails,
                    IfMatch      = IfMatch,
                    OpcRequestId = OpcRequestId
                };

                response = client.UpdateAttribute(request).GetAwaiter().GetResult();
                WriteOutput(response, response.Attribute);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
        private void UpdateDisplayNameColumns()
        {
            var i            = 1;
            var ingoreFields = new List <string> {
                "createdby",
                "createdon",
                "modifiedby",
                "modifiedon",
                "ownerid",
                "transactioncurrencyid"
            };

            foreach (var entity in Entities)
            {
                var requests = new ExecuteMultipleRequest()
                {
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    Requests = new OrganizationRequestCollection()
                };
                var request = new RetrieveEntityRequest
                {
                    EntityFilters         = EntityFilters.Attributes,
                    LogicalName           = entity,
                    RetrieveAsIfPublished = true
                };
                var response = (RetrieveEntityResponse)service.Execute(request);
                foreach (var attr in response.EntityMetadata.Attributes)
                {
                    if (ingoreFields.Contains(attr.LogicalName))
                    {
                        continue;
                    }
                    if (attr.DisplayName?.UserLocalizedLabel?.Label != null)
                    {
                        if (attr.DisplayName.UserLocalizedLabel.Label.StartsWith(NOT_USE))
                        {
                            continue;
                        }
                        attr.DisplayName = new Label($"{NOT_USE}{attr.DisplayName.UserLocalizedLabel.Label}", 1033);
                        var update = new UpdateAttributeRequest()
                        {
                            Attribute  = attr,
                            EntityName = entity
                        };
                        requests.Requests.Add(update);
                    }
                }
                if (requests.Requests.Count > 0)
                {
                    var res = (ExecuteMultipleResponse)service.Execute(requests);
                    CliLog.WriteLine(CliLog.ColorWhite, i, " UpdateDisplayNameColumns - ", entity, " error: ", res.Responses.Count);
                }
                i++;
            }
        }
示例#7
0
        private static UpdateAttributeRequest SetName(UpdateAttributeRequest request, string name)
        {
            Argument.IsNotNull(request, nameof(request));
            Argument.IsNotNull(request.Attribute, nameof(request.Attribute));

            request.Attribute.DisplayName = new Label(name, 1033);
            return(request);
        }
示例#8
0
        private static UpdateAttributeRequest SetIsValidForAdvancedFind(UpdateAttributeRequest request, bool isValidForAdvancedFind)
        {
            Argument.IsNotNull(request, nameof(request));
            Argument.IsNotNull(request.Attribute, nameof(request.Attribute));

            request.Attribute.IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancedFind);
            return(request);
        }
示例#9
0
        private void UpdateAttributeMetadata(AttributeMetadata attributeMetadata)
        {
            var request = new UpdateAttributeRequest()
            {
                Attribute   = attributeMetadata,
                EntityName  = attributeMetadata.EntityLogicalName,
                MergeLabels = false,
            };

            var response = (UpdateAttributeResponse)_service.Execute(request);
        }
示例#10
0
        public override void UpdateAttribute(IOrganizationService service)
        {
            var attribute = GetAttributeMetadata();

            var request = new UpdateAttributeRequest
            {
                EntityName = Entity,
                Attribute  = attribute
            };

            service.Execute(request);
        }
示例#11
0
 public static void UpdateName(IOrganizationService orgSvc, Guid attributeId, string entityName, string name)
 {
     var retrieveAttributeRequest = new UpdateAttributeRequest
     {
         EntityName = entityName,
         Attribute  = new AttributeMetadata
         {
             MetadataId  = attributeId,
             DisplayName = new Label(name, 1033)
         }
     };
     var retrieveAttributeResponse = (UpdateAttributeResponse)orgSvc.Execute(retrieveAttributeRequest);
 }
示例#12
0
 public static void HideFromSearch(IOrganizationService orgSvc, Guid attributeId, string entityName, string name)
 {
     var retrieveAttributeRequest = new UpdateAttributeRequest
     {
         EntityName = entityName,
         Attribute  = new AttributeMetadata
         {
             MetadataId             = attributeId,
             IsValidForAdvancedFind = new BooleanManagedProperty(false)
         }
     };
     var retrieveAttributeResponse = (UpdateAttributeResponse)orgSvc.Execute(retrieveAttributeRequest);
 }
示例#13
0
        public override void UpdateAttribute(IOrganizationService service)
        {
            var relationshipRequest = new UpdateRelationshipRequest
            {
                Relationship = GetRelationshipMetadata()
            };

            service.Execute(relationshipRequest);

            var lookupRequest = new UpdateAttributeRequest
            {
                EntityName = Entity,
                Attribute  = GetAttributeMetadata()
            };

            service.Execute(lookupRequest);
        }
示例#14
0
        public void UpdateAttribute(string logicalname, string displayname, string requirement)
        {
            var requiredlevel = AttributeRequiredLevel.None;

            Enum.TryParse(requirement, out requiredlevel);

            var attribute = new AttributeMetadata();

            // Set base properties
            attribute.LogicalName   = logicalname;
            attribute.DisplayName   = new Label(displayname, languageCode);
            attribute.RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredlevel);

            var request = new UpdateAttributeRequest
            {
                EntityName = entity,
                Attribute  = attribute
            };

            service.Execute(request);
        }
        [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

                    _productVersion = Version.Parse(((RetrieveVersionResponse)service.Execute(new RetrieveVersionRequest())).Version);

                    #region How to create attributes
                    // Create storage for new attributes being created
                    addedAttributes = new List <AttributeMetadata>();

                    // Create a boolean attribute
                    var boolAttribute = new BooleanAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Boolean",
                        LogicalName   = "new_boolean",
                        DisplayName   = new Label("Sample Boolean", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Boolean Attribute", _languageCode),
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Label("True", _languageCode), 1),
                            new OptionMetadata(new Label("False", _languageCode), 0)
                            )
                    };

                    // Add to list
                    addedAttributes.Add(boolAttribute);

                    // Create a date time attribute
                    var dtAttribute = new DateTimeAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Datetime",
                        LogicalName   = "new_datetime",
                        DisplayName   = new Label("Sample DateTime", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("DateTime Attribute", _languageCode),
                        // Set extended properties
                        Format  = DateTimeFormat.DateOnly,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(dtAttribute);

                    // Create a decimal attribute
                    var decimalAttribute = new DecimalAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Decimal",
                        LogicalName   = "new_decimal",
                        DisplayName   = new Label("Sample Decimal", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Decimal Attribute", _languageCode),
                        // Set extended properties
                        MaxValue  = 100,
                        MinValue  = 0,
                        Precision = 1
                    };

                    // Add to list
                    addedAttributes.Add(decimalAttribute);

                    // Create a integer attribute
                    var integerAttribute = new IntegerAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Integer",
                        LogicalName   = "new_integer",
                        DisplayName   = new Label("Sample Integer", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Integer Attribute", _languageCode),
                        // Set extended properties
                        Format   = IntegerFormat.None,
                        MaxValue = 100,
                        MinValue = 0
                    };

                    // Add to list
                    addedAttributes.Add(integerAttribute);

                    // Create a memo attribute
                    var memoAttribute = new MemoAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Memo",
                        LogicalName   = "new_memo",
                        DisplayName   = new Label("Sample Memo", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Memo Attribute", _languageCode),
                        // Set extended properties
                        Format    = StringFormat.TextArea,
                        ImeMode   = ImeMode.Disabled,
                        MaxLength = 500
                    };

                    // Add to list
                    addedAttributes.Add(memoAttribute);

                    // Create a money attribute
                    var moneyAttribute = new MoneyAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Money",
                        LogicalName   = "new_money",
                        DisplayName   = new Label("Money Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Money Attribue", _languageCode),
                        // Set extended properties
                        MaxValue        = 1000.00,
                        MinValue        = 0.00,
                        Precision       = 1,
                        PrecisionSource = 1,
                        ImeMode         = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(moneyAttribute);

                    // Create a picklist attribute
                    var pickListAttribute =
                        new PicklistAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_Picklist",
                        LogicalName   = "new_picklist",
                        DisplayName   = new Label("Sample Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Picklist Attribute", _languageCode),
                        // Set extended properties
                        // Build local picklist options
                        OptionSet = new OptionSetMetadata
                        {
                            IsGlobal      = false,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(
                                    new Label("Created",                        _languageCode), null),
                                new OptionMetadata(
                                    new Label("Updated",                        _languageCode), null),
                                new OptionMetadata(
                                    new Label("Deleted",                        _languageCode), null)
                            }
                        }
                    };

                    // Add to list
                    addedAttributes.Add(pickListAttribute);

                    // Create a string attribute
                    var stringAttribute = new StringAttributeMetadata
                    {
                        // Set base properties
                        SchemaName  = "new_String",
                        LogicalName = "new_string",

                        DisplayName   = new Label("Sample String", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("String Attribute", _languageCode),
                        // Set extended properties
                        MaxLength = 100
                    };

                    // Add to list
                    addedAttributes.Add(stringAttribute);

                    //Multi-select attribute requires version 9.0 or higher.
                    if (_productVersion > new Version("9.0"))
                    {
                        // Create a multi-select optionset
                        var multiSelectOptionSetAttribute = new MultiSelectPicklistAttributeMetadata()
                        {
                            SchemaName    = "new_MultiSelectOptionSet",
                            LogicalName   = "new_multiselectoptionset",
                            DisplayName   = new Label("Multi-Select OptionSet", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            Description   = new Label("Multi-Select OptionSet description", _languageCode),
                            OptionSet     = new OptionSetMetadata()
                            {
                                IsGlobal      = false,
                                OptionSetType = OptionSetType.Picklist,
                                Options       =
                                {
                                    new OptionMetadata(new Label("First Option",  _languageCode), null),
                                    new OptionMetadata(new Label("Second Option", _languageCode), null),
                                    new OptionMetadata(new Label("Third Option",  _languageCode), null)
                                }
                            }
                        };
                        // Add to list
                        addedAttributes.Add(multiSelectOptionSetAttribute);
                    }

                    // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship.
                    // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type.

                    // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK.

                    foreach (AttributeMetadata anAttribute in addedAttributes)
                    {
                        // Create the request.
                        var createAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = Contact.EntityLogicalName,
                            Attribute  = anAttribute
                        };

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

                        Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName);
                    }
                    #endregion How to create attributes

                    #region How to insert status
                    // Use InsertStatusValueRequest message to insert a new status
                    // in an existing status attribute.
                    // Create the request.
                    var insertStatusValueRequest =
                        new InsertStatusValueRequest
                    {
                        AttributeLogicalName = "statuscode",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Label     = new Label("Dormant", _languageCode),
                        StateCode = 0
                    };

                    // Execute the request and store newly inserted value
                    // for cleanup, used later part of this sample.
                    _insertedStatusValue = ((InsertStatusValueResponse)service.Execute(
                                                insertStatusValueRequest)).NewOptionValue;

                    Console.WriteLine("Created status named '{0}' with the value of {1}.",
                                      insertStatusValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedStatusValue);
                    #endregion How to insert status

                    #region How to retrieve attribute
                    // Create the request
                    var attributeRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName     = Contact.EntityLogicalName,
                        LogicalName           = "new_string",
                        RetrieveAsIfPublished = true
                    };

                    // Execute the request
                    RetrieveAttributeResponse attributeResponse =
                        (RetrieveAttributeResponse)service.Execute(attributeRequest);

                    Console.WriteLine("Retrieved the attribute {0}.",
                                      attributeResponse.AttributeMetadata.SchemaName);
                    #endregion How to retrieve attribute

                    #region How to update attribute
                    // Modify the retrieved attribute
                    var retrievedAttributeMetadata =
                        attributeResponse.AttributeMetadata;
                    retrievedAttributeMetadata.DisplayName =
                        new Label("Update String Attribute", _languageCode);

                    // Update an attribute retrieved via RetrieveAttributeRequest
                    var updateRequest = new UpdateAttributeRequest
                    {
                        Attribute   = retrievedAttributeMetadata,
                        EntityName  = Contact.EntityLogicalName,
                        MergeLabels = false
                    };

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

                    Console.WriteLine("Updated the attribute {0}.",
                                      retrievedAttributeMetadata.SchemaName);
                    #endregion How to update attribute

                    #region How to update state value
                    // Modify the state value label from Active to Open.
                    // Create the request.
                    var updateStateValue = new UpdateStateValueRequest
                    {
                        AttributeLogicalName = "statecode",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Value = 1,
                        Label = new Label("Open", _languageCode)
                    };

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

                    Console.WriteLine(
                        "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.",
                        updateStateValue.AttributeLogicalName,
                        updateStateValue.EntityLogicalName,
                        updateStateValue.Label.LocalizedLabels[0].Label
                        );
                    #endregion How to update state value

                    #region How to insert a new option item in a local option set
                    // Create a request.
                    var insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        AttributeLogicalName = "new_picklist",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Label = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request.
                    int insertOptionValue = ((InsertOptionValueResponse)service.Execute(
                                                 insertOptionValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      insertOptionValue);
                    #endregion How to insert a new option item in a local option set

                    #region How to change the order of options of a local option set
                    // Use the RetrieveAttributeRequest message to retrieve
                    // a attribute by it's logical name.
                    var retrieveAttributeRequest =
                        new RetrieveAttributeRequest
                    {
                        EntityLogicalName     = Contact.EntityLogicalName,
                        LogicalName           = "new_picklist",
                        RetrieveAsIfPublished = true
                    };

                    // Execute the request.
                    RetrieveAttributeResponse retrieveAttributeResponse =
                        (RetrieveAttributeResponse)service.Execute(
                            retrieveAttributeRequest);

                    // Access the retrieved attribute.
                    var retrievedPicklistAttributeMetadata =
                        (PicklistAttributeMetadata)
                        retrieveAttributeResponse.AttributeMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

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

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

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

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

                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    // NOTE: All customizations must be published before they can be used.
                    service.Execute(new PublishAllXmlRequest());
                    Console.WriteLine("Published all customizations.");
                    #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();
            }
        }
示例#16
0
        public void Import(ExcelWorksheet sheet, List <EntityMetadata> emds, IOrganizationService service)
        {
            var amds = new List <MasterAttribute>();

            foreach (var row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(row.Cells[0].Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == row.Cells[1].Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName   = row.Cells[1].Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd     = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => a.LogicalName == row.Cells[2].Value.ToString());
                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (row.Cells[3].Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new Label();

                    while (row.Cells[columnIndex].Value != null)
                    {
                        amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
                else if (row.Cells[3].Value.ToString() == "Description")
                {
                    amd.Amd.Description = new Label();

                    while (row.Cells[columnIndex].Value != null)
                    {
                        amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
            }

            var sbError = new StringBuilder();

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label)) ||
                    amd.Amd.IsRenameable.Value == false)
                {
                    continue;
                }

                try
                {
                    var request = new UpdateAttributeRequest
                    {
                        Attribute  = amd.Amd,
                        EntityName = amd.Amd.EntityLogicalName
                    };
                    service.Execute(request);
                }
                catch
                {
                    sbError.AppendLine(string.Format("- {0} ({1})", amd.Amd.LogicalName, amd.Amd.EntityLogicalName));
                }
            }

            if (sbError.Length > 0)
            {
                MessageBox.Show("Following attributes were not updated due to errors:\r\n" + sbError, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
示例#17
0
        public void Import(ExcelWorksheet sheet, List <EntityMetadata> emds, IOrganizationService service)
        {
            var amds = new List <MasterAttribute>();

            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(ZeroBasedSheet.Cell(sheet, rowI, 0).Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName   = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd     = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => a.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString());
                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new Label();

                    while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                    {
                        amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString(), int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString())));

                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                {
                    amd.Amd.Description = new Label();

                    while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                    {
                        amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value.ToString(), int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString())));

                        columnIndex++;
                    }
                }
            }

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label)) ||
                    amd.Amd.IsRenameable.Value == false)
                {
                    continue;
                }

                var request = new UpdateAttributeRequest {
                    Attribute = amd.Amd, EntityName = amd.Amd.EntityLogicalName
                };
                service.Execute(request);
            }
        }
示例#18
0
        private void TsbApplyChangesClick(object sender, EventArgs e)
        {
            if (entityInfos.All(ei => ei.Action == ActionState.None) &&
                attributeInfos.All(ai => ai.Action == ActionState.None))
            {
                return;
            }

            gbEntities.Enabled    = false;
            gbAttributes.Enabled  = false;
            toolStripMenu.Enabled = false;

            WorkAsync("Updating entities...",
                      (bw, evt) =>
            {
                foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                {
                    if (ei.Action == ActionState.Added)
                    {
                        bw.ReportProgress(0, string.Format("Enabling entity '{0}' for audit...", ei.Emd.LogicalName));

                        ei.Emd.IsAuditEnabled.Value = true;
                    }
                    else if (ei.Action == ActionState.Removed)
                    {
                        bw.ReportProgress(0, string.Format("Disabling entity '{0}' for audit...", ei.Emd.LogicalName));

                        ei.Emd.IsAuditEnabled.Value = false;
                    }
                    else
                    {
                        continue;
                    }

                    var request = new UpdateEntityRequest {
                        Entity = ei.Emd
                    };
                    Service.Execute(request);

                    ei.Action = ActionState.None;
                }

                bw.ReportProgress(0, "Updating attributes...");

                foreach (AttributeInfo ai in attributeInfos.OrderBy(a => a.Amd.EntityLogicalName).ThenBy(a => a.Amd.LogicalName))
                {
                    if (ai.Action == ActionState.Added)
                    {
                        bw.ReportProgress(0, string.Format("Enabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                        ai.Amd.IsAuditEnabled.Value = true;
                    }
                    else if (ai.Action == ActionState.Removed)
                    {
                        bw.ReportProgress(0, string.Format("Disabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                        ai.Amd.IsAuditEnabled.Value = false;
                    }
                    else
                    {
                        continue;
                    }

                    var request = new UpdateAttributeRequest {
                        Attribute = ai.Amd, EntityName = ai.Amd.EntityLogicalName
                    };
                    Service.Execute(request);

                    ai.Action = ActionState.None;
                }

                bw.ReportProgress(0, "Publishing changes...");

                var publishRequest = new PublishXmlRequest {
                    ParameterXml = "<importexportxml><entities>"
                };

                foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                {
                    publishRequest.ParameterXml += string.Format("<entity>{0}</entity>", ei.Emd.LogicalName);
                }

                publishRequest.ParameterXml +=
                    "</entities><securityroles/><settings/><workflows/></importexportxml>";

                Service.Execute(publishRequest);
            },
                      evt =>
            {
                if (evt.Error != null)
                {
                    MessageBox.Show(this, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }

                gbEntities.Enabled    = true;
                gbAttributes.Enabled  = true;
                toolStripMenu.Enabled = true;

                tsbApplyChanges.Enabled = !((entityInfos.All(ei => ei.Action == ActionState.None) &&
                                             attributeInfos.All(ai => ai.Action == ActionState.None)));
            },
                      evt => SetWorkingMessage(evt.UserState.ToString()));
        }
        public void UpdateEntityData(BackgroundWorker w, bool bCountMode)
        {
            iEntityCount           = 0;
            iEntityUpdatedCount    = 0;
            iAttributeCount        = 0;
            iAttributeUpdatedCount = 0;

            if (bCountMode) //if this is count mode then initialise counter
            {
                iEntitiesOrAttributesToUpdate = 0;
            }

            LogInfo("Apply updates to CRM (if any)");

            foreach (string sKey in FileEntitySet.entities.Keys) //loop over entities read from file
            {
                iEntityCount++;
                if (CRMEntitySet.entities.ContainsKey(sKey)) //only do this if there is a corresponding entity in CRM - should almost always be so
                {
                    if (RemoveNulls(FileEntitySet.entities[sKey].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)) != RemoveNulls(CRMEntitySet.entities[sKey].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)))
                    {
                        //Entity description has changed so update it unless not updateable
                        if (!CRMEntitySet.entities[sKey].NotUpdateAble)
                        {
                            if (bCountMode)
                            {
                                iEntitiesOrAttributesToUpdate++;
                            }
                            else
                            {
                                string sDescription = FileEntitySet.entities[sKey].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString);
                                LogInfo2(string.Format("About to update entity {0} with description {1}", sKey, sDescription));
                                EntityMetadata entityMeta = new EntityMetadata()
                                {
                                    LogicalName = sKey,
                                    Description = new Microsoft.Xrm.Sdk.Label(sDescription, FileEntitySet.entities[sKey].LanguageCode)
                                };

                                UpdateEntityRequest UpdateRequest = new UpdateEntityRequest()
                                {
                                    Entity = entityMeta
                                };

                                UpdateEntityResponse updateResp = (UpdateEntityResponse)Service.Execute(UpdateRequest);
                                iEntityUpdatedCount++;
                                w.ReportProgress(-1, "Entity/attribute updated. Completed: " + ((iAttributeUpdatedCount + iEntityUpdatedCount) * 100 / iEntitiesOrAttributesToUpdate).ToString() + "%");
                            }
                        }
                        else
                        {
                            LogWarning("Entity description for " + sKey + " could not be updated as this is not permitted by CRM");
                        }
                    }
                    foreach (string sKey2 in FileEntitySet.entities[sKey].attributes.Keys)
                    {
                        iAttributeCount++;
                        if (CRMEntitySet.entities[sKey].attributes.ContainsKey(sKey2))        //only do this if attribute present
                        {
                            if (!CRMEntitySet.entities[sKey].attributes[sKey2].NotUpdateAble) //skip if not updateable
                            {
                                if (RemoveNulls(FileEntitySet.entities[sKey].attributes[sKey2].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)) != RemoveNulls(CRMEntitySet.entities[sKey].attributes[sKey2].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString)))
                                {
                                    if (bCountMode)
                                    {
                                        iEntitiesOrAttributesToUpdate++;
                                    }
                                    else
                                    {
                                        string sDescription = FileEntitySet.entities[sKey].attributes[sKey2].GetTaggedDescription(mySettings.UseTags, mySettings.TagOpeningString, mySettings.TagClosingString);
                                        LogInfo2(string.Format("About to update attribute {0} in entity {1} with description {2}", sKey2, sKey, sDescription));

                                        //Construct metadata. Note special for picklist
                                        if ((CRMEntitySet.entities[sKey].attributes[sKey2].attributeTypeDescription == "Picklist") &&
                                            CRMEntitySet.entities[sKey].attributes[sKey2].DefaultOptionSetValue != null)    //this shows that it is a picklist with non-default default
                                        {
                                            PicklistAttributeMetadata atttributeMeta = new PicklistAttributeMetadata()
                                            {
                                                LogicalName      = sKey2,
                                                Description      = new Microsoft.Xrm.Sdk.Label(sDescription, FileEntitySet.entities[sKey].attributes[sKey2].LanguageCode),
                                                DefaultFormValue = CRMEntitySet.entities[sKey].attributes[sKey2].DefaultOptionSetValue
                                            };
                                            UpdateAttributeRequest UpdateRequest = new UpdateAttributeRequest()
                                            {
                                                Attribute  = atttributeMeta,
                                                EntityName = sKey
                                            };
                                            iAttributeUpdatedCount++;
                                            UpdateAttributeResponse updateResp = (UpdateAttributeResponse)Service.Execute(UpdateRequest);
                                        }
                                        else
                                        {
                                            AttributeMetadata atttributeMeta = new AttributeMetadata()
                                            {
                                                LogicalName = sKey2,
                                                Description = new Microsoft.Xrm.Sdk.Label(sDescription, FileEntitySet.entities[sKey].attributes[sKey2].LanguageCode)
                                            };
                                            UpdateAttributeRequest UpdateRequest = new UpdateAttributeRequest()
                                            {
                                                Attribute  = atttributeMeta,
                                                EntityName = sKey
                                            };
                                            iAttributeUpdatedCount++;
                                            UpdateAttributeResponse updateResp = (UpdateAttributeResponse)Service.Execute(UpdateRequest);
                                        }
                                        w.ReportProgress(-1, "Entity/attribute updated. Completed: " + ((iAttributeUpdatedCount + iEntityUpdatedCount) * 100 / iEntitiesOrAttributesToUpdate).ToString() + "%");
                                    }
                                }
                            }
                            else
                            {
                                LogWarning("Skipping field " + sKey2 + " as not updateable");
                            }
                        }
                        else
                        {
                            LogWarning("Atttibute " + sKey2 + " in entity " + sKey + " from input file not found in CRM. This record will be ignored");
                        }
                    }
                }
                else
                {
                    LogWarning("Entity " + sKey + " from input file not found in CRM. This record will be ignored");
                }
            }
        }
示例#20
0
        private void WriteAttribute(bool update)
        {
            var langid            = int.Parse(txtLanguageId.Text.Trim());
            var solutionname      = (cmbSolution.SelectedItem as SolutionProxy)?.UniqueName;
            var entity            = ((EntityMetadataProxy)cmbEntities.SelectedItem).Metadata;
            var existingattribute = update ? (gridAttributes.SelectedRows[0].DataBoundItem as AttributeProxy).attributeMetadata : null;
            var logicalname       = lblPrefix.Text + txtLogicalName.Text.Trim();
            var schemaname        = update ? (gridAttributes.SelectedRows[0].DataBoundItem as AttributeProxy).attributeMetadata.SchemaName : logicalname;
            var format            = txtNumberFormat.Text.Trim();

            if (!string.IsNullOrEmpty(format))
            {
                try
                {
                    var seqnum = ParseFormatSEQNUM(format, string.Empty);
                    if (format.Equals(seqnum))
                    {
                        if (DialogResult.Cancel == MessageBox.Show("Creating number formats without SEQNUM placeholder can result in non-unique values.\n\nPlease confirm!", "No sequence number", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
                        {
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            var maxlen = int.Parse(txtMaxLen.Text.Trim());
            var seed   = txtSeed.Enabled ? txtSeed.Text.Trim() : string.Empty;
            OrganizationRequest req = null;

            if (update)
            {
                if (existingattribute.AutoNumberFormat != format ||
                    existingattribute.MaxLength != maxlen ||
                    existingattribute.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == langid)?.Label != txtDisplayName.Text ||
                    existingattribute.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == langid)?.Label != txtDescription.Text)
                {
                    var attribute = ((RetrieveAttributeResponse)Service.Execute(new RetrieveAttributeRequest
                    {
                        EntityLogicalName = entity.LogicalName,
                        LogicalName = logicalname,
                        RetrieveAsIfPublished = true
                    })).AttributeMetadata;
                    attribute.AutoNumberFormat = format;
                    req = new UpdateAttributeRequest
                    {
                        EntityName         = entity.LogicalName,
                        Attribute          = attribute,
                        SolutionUniqueName = solutionname
                    };
                }
                if (!string.IsNullOrEmpty(seed))
                {
                    if (DialogResult.Yes != MessageBox.Show("Setting the seed for existing an attribute MAY result in duplicate data!\nDo you really want to change the seed?", "Confirm seed", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
                    {
                        return;
                    }
                }
            }
            else
            {
                var attribute = new StringAttributeMetadata
                {
                    AutoNumberFormat = format,
                    LogicalName      = logicalname,
                    SchemaName       = schemaname,
                    MaxLength        = maxlen,
                    DisplayName      = new Microsoft.Xrm.Sdk.Label(txtDisplayName.Text, langid),
                    Description      = new Microsoft.Xrm.Sdk.Label(txtDescription.Text, langid),
                    RequiredLevel    = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None)
                };
                req = new CreateAttributeRequest
                {
                    EntityName         = entity.LogicalName,
                    Attribute          = attribute,
                    SolutionUniqueName = solutionname
                };
            }
            WorkAsync(new WorkAsyncInfo("Saving attribute...",
                                        (eventargs) =>
            {
                if (req != null)
                {
                    Service.Execute(req);
                }
                if (!string.IsNullOrEmpty(seed))
                {
                    LogUse("SetSeed");
                    Service.Execute(new SetAutoNumberSeedRequest
                    {
                        EntityName    = entity.LogicalName,
                        AttributeName = logicalname,
                        Value         = Int64.Parse(seed)
                    });
                }
            })
            {
                PostWorkCallBack = (completedargs) =>
                {
                    if (completedargs.Error != null)
                    {
                        MessageBox.Show($"Save attribute failed:\n{completedargs.Error}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show("Attribute saved!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    UpdateUI(ForceLoadAttributes);
                }
            });
        }
示例#21
0
        public void Import(ExcelWorksheet sheet, List <EntityMetadata> emds, IOrganizationService service)
        {
            var amds = new List <MasterAttribute>();

            foreach (var row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(row.Cells[0].Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == row.Cells[1].Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName   = row.Cells[1].Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd     = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => a.LogicalName == row.Cells[2].Value.ToString());
                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (row.Cells[3].Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new Label();

                    while (row.Cells[columnIndex].Value != null)
                    {
                        amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
                else if (row.Cells[3].Value.ToString() == "Description")
                {
                    amd.Amd.Description = new Label();

                    while (row.Cells[columnIndex].Value != null)
                    {
                        amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
            }

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label)) ||
                    amd.Amd.IsRenameable.Value == false)
                {
                    continue;
                }

                var request = new UpdateAttributeRequest {
                    Attribute = amd.Amd, EntityName = amd.Amd.EntityLogicalName
                };
                service.Execute(request);
            }
        }
示例#22
0
        /// <summary>
        /// Creates required records for this sample.
        /// </summary>
        private void CreateRequiredRecords()
        {
            // Create a date time attribute for the Account entity
            // with the UserLocal behavior
            dtAttribute = new DateTimeAttributeMetadata
            {
                SchemaName       = "new_SampleDateTimeAttribute",
                DisplayName      = new Label("Sample Date Time Attribute", _languageCode),
                RequiredLevel    = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                Description      = new Label("Created by SDK Sample", _languageCode),
                DateTimeBehavior = DateTimeBehavior.UserLocal,
                Format           = DateTimeFormat.DateAndTime,
                ImeMode          = ImeMode.Disabled
            };

            CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
            {
                EntityName = Account.EntityLogicalName,
                Attribute  = dtAttribute
            };

            _serviceProxy.Execute(createAttributeRequest);
            Console.WriteLine("Created attribute '{0}' with UserLocal behavior\nfor the Account entity.\n",
                              dtAttribute.SchemaName);

            // Create a sample account record with March 31, 2015 11:00 PM UTC
            // value in the new attribute.
            Entity newAccount1 = new Entity("account");

            newAccount1["name"] = "Sample Account 1";
            newAccount1["new_sampledatetimeattribute"] = new DateTime(2015, 3, 31, 23, 0, 0, DateTimeKind.Utc);
            _account1ID = _serviceProxy.Create(newAccount1);
            Console.WriteLine("Created account: '{0}'.", newAccount1.Attributes["name"]);

            // Create a column set to define which attributes should be retrieved.
            ColumnSet attributes1 = new ColumnSet(new string[] { "name", "new_sampledatetimeattribute" });

            // Retrieve the date and time value of the new attribute in the new account record.
            newAccount1 = _serviceProxy.Retrieve(newAccount1.LogicalName, _account1ID, attributes1);
            Console.WriteLine("Retrieved date and time value for '{0}': {1}\n", newAccount1.GetAttributeValue <String>("name"),
                              newAccount1.GetAttributeValue <DateTime>("new_sampledatetimeattribute"));

            // Retrieve the attribute to update its behavior and format
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = Account.EntityLogicalName,
                LogicalName           = "new_sampledatetimeattribute",
                RetrieveAsIfPublished = false
            };
            // Execute the request
            RetrieveAttributeResponse attributeResponse =
                (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

            Console.WriteLine("Retrieved the attribute '{0}'.",
                              attributeResponse.AttributeMetadata.SchemaName);

            // Modify the values of the retrieved attribute
            DateTimeAttributeMetadata retrievedAttributeMetadata =
                (DateTimeAttributeMetadata)attributeResponse.AttributeMetadata;

            retrievedAttributeMetadata.DateTimeBehavior = DateTimeBehavior.DateOnly;
            retrievedAttributeMetadata.Format           = DateTimeFormat.DateOnly;

            // Update the attribute with the modified value
            UpdateAttributeRequest updateRequest = new UpdateAttributeRequest
            {
                Attribute   = retrievedAttributeMetadata,
                EntityName  = Account.EntityLogicalName,
                MergeLabels = false
            };

            _serviceProxy.Execute(updateRequest);
            Console.WriteLine("Updated the behavior and format of '{0}' to DateOnly.",
                              retrievedAttributeMetadata.SchemaName);

            // Publish customizations to the account entity
            PublishXmlRequest pxReq = new PublishXmlRequest
            {
                ParameterXml = String.Format("<importexportxml><entities><entity>account</entity></entities></importexportxml>")
            };

            _serviceProxy.Execute(pxReq);
            Console.WriteLine("Published customizations to the Account entity.\n");

            // Create another sample account record with a
            // DateTime value in the new attribute.
            Entity newAccount2 = new Entity("account");

            newAccount2["name"] = "Sample Account 2";

            // Purposely pass the time value to check if it matters.
            // For DateOnly behavior, only the Date part is considered.
            // Time is always 12 AM (00:00:00)
            newAccount2["new_sampledatetimeattribute"] = new DateTime(2015, 3, 31, 23, 0, 0, DateTimeKind.Utc);

            _account2ID = _serviceProxy.Create(newAccount2);
            Console.WriteLine("Created account '{0}' after the behavior change.\n", newAccount2.Attributes["name"]);

            // Create a column set to define which attributes should be retrieved.
            ColumnSet attributes2 = new ColumnSet(new string[] { "name", "new_sampledatetimeattribute" });

            // Retrieve the date and time values existing and new account records.
            // Though both the values will display value in DateOnly behavior (Time is 12 AM (00:00:00)),
            // the actual value for the date and time value for "Sample Account 1" is still stored
            // in UTC.
            // We will use the UTC value for "Sample Account 1", and apply the conversion rule to
            // display a different date than what CRM converts and displays by default.

            newAccount1 = _serviceProxy.Retrieve(newAccount1.LogicalName, _account1ID, attributes1);
            newAccount2 = _serviceProxy.Retrieve(newAccount2.LogicalName, _account2ID, attributes2);

            Console.WriteLine("Retrieving date and time value for both the account records...");
            Console.WriteLine("'{0}': {1}",
                              newAccount1.GetAttributeValue <String>("name"), newAccount1.GetAttributeValue <DateTime>("new_sampledatetimeattribute"));
            Console.WriteLine("'{0}': {1}\n",
                              newAccount2.GetAttributeValue <String>("name"), newAccount2.GetAttributeValue <DateTime>("new_sampledatetimeattribute"));

            Console.WriteLine("The behavior is displayed as DateOnly when retrieved\nfor existing record ({0}) as well.",
                              newAccount1.Attributes["name"]);
            Console.WriteLine("We will now convert the UTC value in the DB for '{0}'.\n", newAccount1.Attributes["name"]);
        }
示例#23
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create few types of attributes.
        /// Insert status in the existing status list.
        /// Retrieve attribute.
        /// Update attribute.
        /// Update existing state value.
        /// Optionally delete/revert any attributes
        /// that were created/changed for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetWorkWithAttributes1>
                    #region How to create attributes
                    //<snippetWorkWithAttributes2>
                    // Create storage for new attributes being created
                    addedAttributes = new List <AttributeMetadata>();

                    // Create a boolean attribute
                    BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_boolean",
                        DisplayName   = new Label("Sample Boolean", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Boolean Attribute", _languageCode),
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Label("True", _languageCode), 1),
                            new OptionMetadata(new Label("False", _languageCode), 0)
                            )
                    };

                    // Add to list
                    addedAttributes.Add(boolAttribute);

                    // Create a date time attribute
                    DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_datetime",
                        DisplayName   = new Label("Sample DateTime", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("DateTime Attribute", _languageCode),
                        // Set extended properties
                        Format  = DateTimeFormat.DateOnly,
                        ImeMode = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(dtAttribute);

                    // Create a decimal attribute
                    DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_decimal",
                        DisplayName   = new Label("Sample Decimal", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Decimal Attribute", _languageCode),
                        // Set extended properties
                        MaxValue  = 100,
                        MinValue  = 0,
                        Precision = 1
                    };

                    // Add to list
                    addedAttributes.Add(decimalAttribute);

                    // Create a integer attribute
                    IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_integer",
                        DisplayName   = new Label("Sample Integer", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Integer Attribute", _languageCode),
                        // Set extended properties
                        Format   = IntegerFormat.None,
                        MaxValue = 100,
                        MinValue = 0
                    };

                    // Add to list
                    addedAttributes.Add(integerAttribute);

                    // Create a memo attribute
                    MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_memo",
                        DisplayName   = new Label("Sample Memo", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Memo Attribute", _languageCode),
                        // Set extended properties
                        Format    = StringFormat.TextArea,
                        ImeMode   = ImeMode.Disabled,
                        MaxLength = 500
                    };

                    // Add to list
                    addedAttributes.Add(memoAttribute);

                    // Create a money attribute
                    MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_money",
                        DisplayName   = new Label("Money Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Money Attribue", _languageCode),
                        // Set extended properties
                        MaxValue        = 1000.00,
                        MinValue        = 0.00,
                        Precision       = 1,
                        PrecisionSource = 1,
                        ImeMode         = ImeMode.Disabled
                    };

                    // Add to list
                    addedAttributes.Add(moneyAttribute);

                    // Create a picklist attribute
                    PicklistAttributeMetadata pickListAttribute =
                        new PicklistAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_picklist",
                        DisplayName   = new Label("Sample Picklist", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("Picklist Attribute", _languageCode),
                        // Set extended properties
                        // Build local picklist options
                        OptionSet = new OptionSetMetadata
                        {
                            IsGlobal      = false,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(
                                    new Label("Created",                        _languageCode), null),
                                new OptionMetadata(
                                    new Label("Updated",                        _languageCode), null),
                                new OptionMetadata(
                                    new Label("Deleted",                        _languageCode), null)
                            }
                        }
                    };

                    // Add to list
                    addedAttributes.Add(pickListAttribute);

                    // Create a string attribute
                    StringAttributeMetadata stringAttribute = new StringAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = "new_string",
                        DisplayName   = new Label("Sample String", _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Description   = new Label("String Attribute", _languageCode),
                        // Set extended properties
                        MaxLength = 100
                    };

                    // Add to list
                    addedAttributes.Add(stringAttribute);

                    // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship.
                    // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type.

                    // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK.

                    foreach (AttributeMetadata anAttribute in addedAttributes)
                    {
                        // Create the request.
                        CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
                        {
                            EntityName = Contact.EntityLogicalName,
                            Attribute  = anAttribute
                        };

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

                        Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName);
                    }
                    //</snippetWorkWithAttributes2>
                    #endregion How to create attributes

                    #region How to insert status
                    //<snippetWorkWithAttributes3>
                    // Use InsertStatusValueRequest message to insert a new status
                    // in an existing status attribute.
                    // Create the request.
                    InsertStatusValueRequest insertStatusValueRequest =
                        new InsertStatusValueRequest
                    {
                        AttributeLogicalName = "statuscode",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Label     = new Label("Dormant", _languageCode),
                        StateCode = 0
                    };

                    // Execute the request and store newly inserted value
                    // for cleanup, used later part of this sample.
                    _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute(
                                                insertStatusValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertStatusValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedStatusValue);
                    //</snippetWorkWithAttributes3>
                    #endregion How to insert status

                    #region How to retrieve attribute
                    //<snippetWorkWithAttributes4>
                    // Create the request
                    RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName = Contact.EntityLogicalName,
                        LogicalName       = "new_string",
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Execute the request
                    RetrieveAttributeResponse attributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest);

                    Console.WriteLine("Retrieved the attribute {0}.",
                                      attributeResponse.AttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes4>
                    #endregion How to retrieve attribute

                    #region How to update attribute
                    //<snippetWorkWithAttributes5>
                    // Modify the retrieved attribute
                    AttributeMetadata retrievedAttributeMetadata =
                        attributeResponse.AttributeMetadata;
                    retrievedAttributeMetadata.DisplayName =
                        new Label("Update String Attribute", _languageCode);

                    // Update an attribute retrieved via RetrieveAttributeRequest
                    UpdateAttributeRequest updateRequest = new UpdateAttributeRequest
                    {
                        Attribute   = retrievedAttributeMetadata,
                        EntityName  = Contact.EntityLogicalName,
                        MergeLabels = false
                    };

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

                    Console.WriteLine("Updated the attribute {0}.",
                                      retrievedAttributeMetadata.SchemaName);
                    //</snippetWorkWithAttributes5>
                    #endregion How to update attribute

                    #region How to update state value
                    //<snippetWorkWithAttributes6>
                    // Modify the state value label from Active to Open.
                    // Create the request.
                    UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
                    {
                        AttributeLogicalName = "statecode",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Value = 1,
                        Label = new Label("Open", _languageCode)
                    };

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

                    Console.WriteLine(
                        "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.",
                        updateStateValue.AttributeLogicalName,
                        updateStateValue.EntityLogicalName,
                        updateStateValue.Label.LocalizedLabels[0].Label
                        );
                    //</snippetWorkWithAttributes6>
                    #endregion How to update state value

                    #region How to insert a new option item in a local option set
                    //<snippetWorkWithAttributes7>
                    // Create a request.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        AttributeLogicalName = "new_picklist",
                        EntityLogicalName    = Contact.EntityLogicalName,
                        Label = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request.
                    int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                                                 insertOptionValueRequest)).NewOptionValue;

                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      insertOptionValue);
                    //</snippetWorkWithAttributes7>
                    #endregion How to insert a new option item in a local option set

                    #region How to change the order of options of a local option set
                    //<snippetWorkWithAttributes8>
                    // Use the RetrieveAttributeRequest message to retrieve
                    // a attribute by it's logical name.
                    RetrieveAttributeRequest retrieveAttributeRequest =
                        new RetrieveAttributeRequest
                    {
                        EntityLogicalName = Contact.EntityLogicalName,
                        LogicalName       = "new_picklist",
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Execute the request.
                    RetrieveAttributeResponse retrieveAttributeResponse =
                        (RetrieveAttributeResponse)_serviceProxy.Execute(
                            retrieveAttributeRequest);

                    // Access the retrieved attribute.
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
                        (PicklistAttributeMetadata)
                        retrieveAttributeResponse.AttributeMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

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

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

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

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

                    Console.WriteLine("Option Set option order changed");
                    //</snippetWorkWithAttributes8>
                    #endregion How to change the order of options of a global option set

                    // NOTE: All customizations must be published before they can be used.
                    _serviceProxy.Execute(new PublishAllXmlRequest());
                    Console.WriteLine("Published all customizations.");
                    //</snippetWorkWithAttributes1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
示例#24
0
 private void CreateOrUpdateAttribute(string schemaName, string recordType, AttributeMetadata metadata)
 {
     lock (LockObject)
     {
         if (FieldExists(schemaName, recordType))
         {
             var request = new UpdateAttributeRequest
             {
                 EntityName = recordType,
                 Attribute = metadata,
             };
             Execute(request);
             RefreshFieldMetadata(schemaName, recordType);
         }
         else
         {
             var request = new CreateAttributeRequest
             {
                 EntityName = recordType,
                 Attribute = metadata
             };
             Execute(request);
             RefreshFieldMetadata(schemaName, recordType);
         }
     }
 }
示例#25
0
        public void Process(BackgroundWorker worker, ConnectionDetail detail)
        {
            var eiCache = new List <EntityInfo>();

            byte[] file = File.ReadAllBytes(settings.FilePath);
            using (MemoryStream ms = new MemoryStream(file))
                using (ExcelPackage package = new ExcelPackage(ms))
                {
                    ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
                    int            percent   = 0;
                    int            index     = 0;
                    for (int i = 3; i <= workSheet.Dimension.End.Row; i++)
                    {
                        if (string.IsNullOrEmpty(workSheet.GetValue <string>(i, TypeCellIndex)) ||
                            workSheet.GetValue <string>(i, 1) == "Ignore")
                        {
                            continue;
                        }

                        if (worker.CancellationPending)
                        {
                            return;
                        }

                        index++;

                        var info = new ProcessResult
                        {
                            DisplayName = workSheet.GetValue <string>(i, DisplayNameCellIndex),
                            Attribute   = workSheet.GetValue <string>(i, SchemaNameCellIndex),
                            Type        = workSheet.GetValue <string>(i, TypeCellIndex),
                            Entity      = workSheet.GetValue <string>(i, EntityCellIndex),
                            Processing  = true,
                        };

                        if ((info.Type == "Customer" || info.Type == "Lookup") && settings.AddLookupSuffix && !info.Attribute.EndsWith("Id"))
                        {
                            info.Attribute = $"{info.Attribute}Id";
                        }
                        if (info.Type == "OptionSet" && settings.AddOptionSetSuffix && !info.Attribute.ToLower().EndsWith("code"))
                        {
                            info.Attribute = $"{info.Attribute}Code";
                        }

                        worker.ReportProgress(percent, info);
                        percent = index * 100 / (workSheet.Dimension.End.Row - 2);

                        try
                        {
                            AttributeMetadata amd = null;
                            var fakeAmd           = GetFakeAmd(info, workSheet, i);

                            // Check validity for an Update
                            var ei = eiCache.FirstOrDefault(e => e.Name == info.Entity);
                            if (ei == null)
                            {
                                ei = new EntityInfo(info.Entity, service);
                                eiCache.Add(ei);
                            }

                            var existingAttribute = ei.Attributes.FirstOrDefault(a => a.LogicalName == info.Attribute.ToLower());
                            if (existingAttribute != null)
                            {
                                fakeAmd.MetadataId = existingAttribute.MetadataId;
                            }

                            var type = workSheet.GetValue <string>(i, TypeCellIndex);
                            switch (type)
                            {
                            case "Single line of text":

                                if (!string.IsNullOrEmpty(workSheet.GetValue <string>(i, PropertiesFirstCellIndex + 2)) && detail.OrganizationMajorVersion < 9)
                                {
                                    throw new Exception(
                                              "Autonumber attributes can only be created in a version 9 or above of Microsoft Dynamics 365");
                                }

                                amd = CreateStringAttribute(workSheet, i, PropertiesFirstCellIndex);
                                break;

                            case "OptionSet":
                                amd = CreateOptionsetAttribute(workSheet, i, PropertiesFirstCellIndex + 4, false, info.DisplayName, info.Attribute, info.Entity, fakeAmd.Description?.LocalizedLabels[0]?.Label, (existingAttribute as PicklistAttributeMetadata)?.OptionSet);
                                break;

                            case "Multiselect OptionSet":

                                if (detail.OrganizationMajorVersion < 9)
                                {
                                    throw new Exception(
                                              "Multiselect OptionSet can only be created in a version 9 or above of Microsoft Dynamics 365");
                                }

                                amd = CreateOptionsetAttribute(workSheet, i, PropertiesFirstCellIndex + 4, true, info.DisplayName, info.Attribute, info.Entity, fakeAmd.Description?.LocalizedLabels[0]?.Label, (existingAttribute as PicklistAttributeMetadata)?.OptionSet);
                                break;

                            case "Two options":
                                amd = CreateBooleanAttribute(workSheet, i, PropertiesFirstCellIndex + 8);
                                break;

                            case "Whole number":
                                amd = CreateNumberAttribute(workSheet, i, PropertiesFirstCellIndex + 11);
                                break;

                            case "Float number":
                                amd = CreateFloatAttribute(workSheet, i, PropertiesFirstCellIndex + 15);
                                break;

                            case "Decimal number":
                                amd = CreateDecimalAttribute(workSheet, i, PropertiesFirstCellIndex + 19);
                                break;

                            case "Money":
                                amd = CreateMoneyAttribute(workSheet, i, PropertiesFirstCellIndex + 23);
                                break;

                            case "Multiple lines of text":
                                amd = CreateMemoAttribute(workSheet, i, PropertiesFirstCellIndex);
                                break;

                            case "Date and time":
                                amd = CreateDateTimeAttribute(workSheet, i, PropertiesFirstCellIndex + 27);
                                break;

                            case "Lookup":
                                amd = CreateLookupAttribute(workSheet, i, PropertiesFirstCellIndex + 30, fakeAmd, info, !fakeAmd.MetadataId.HasValue);
                                break;

                            case "Customer":
                                amd = CreateCustomerAttribute(workSheet, i, PropertiesFirstCellIndex + 31, fakeAmd, existingAttribute, info, !fakeAmd.MetadataId.HasValue);
                                break;

                            case "File":
                                amd = CreateFileAttribute(workSheet, i, PropertiesFirstCellIndex + 45);
                                break;

                            case "Image":
                                amd = CreateImageAttribute(workSheet, i, PropertiesFirstCellIndex + 47);
                                break;
                            }

                            if (amd == null)
                            {
                                info.Success    = true;
                                info.Processing = false;
                                worker.ReportProgress(percent, info);
                                continue;
                            }

                            if (existingAttribute != null)
                            {
                                if (existingAttribute.GetType() != amd.GetType())
                                {
                                    throw new Exception(
                                              @"Attribute in Excel file is not of same type as existing attribute in organization");
                                }
                            }

                            amd.DisplayName            = fakeAmd.DisplayName;
                            amd.SchemaName             = fakeAmd.SchemaName;
                            amd.LogicalName            = fakeAmd.LogicalName;
                            amd.IsValidForAdvancedFind = fakeAmd.IsValidForAdvancedFind;
                            amd.IsSecured      = fakeAmd.IsSecured;
                            amd.IsAuditEnabled = fakeAmd.IsAuditEnabled;
                            amd.SourceType     = fakeAmd.SourceType;
                            amd.MetadataId     = fakeAmd.MetadataId;
                            amd.RequiredLevel  = fakeAmd.RequiredLevel;
                            if (fakeAmd.Description != null)
                            {
                                amd.Description = fakeAmd.Description;
                            }

                            info.Attribute = amd.SchemaName;

                            OrganizationRequest request;
                            if (amd.MetadataId.HasValue)
                            {
                                request = new UpdateAttributeRequest
                                {
                                    Attribute          = amd,
                                    EntityName         = info.Entity,
                                    SolutionUniqueName = settings.Solution.UniqueName,
                                    MergeLabels        = true
                                };

                                info.IsCreate = false;
                            }
                            else
                            {
                                request = new CreateAttributeRequest
                                {
                                    Attribute          = amd,
                                    EntityName         = info.Entity,
                                    SolutionUniqueName = settings.Solution.UniqueName
                                };

                                info.IsCreate = true;
                            }

                            try
                            {
                                service.Execute(request);
                                info.Success    = true;
                                info.Processing = false;
                                worker.ReportProgress(percent, info);
                            }
                            catch (FaultException <OrganizationServiceFault> error)
                            {
                                // Special handle for file attribute as they are not returned by the query
                                if (info.IsCreate && error.Detail.ErrorCode == -2147192813)
                                {
                                    request = new UpdateAttributeRequest
                                    {
                                        Attribute          = amd,
                                        EntityName         = info.Entity,
                                        SolutionUniqueName = settings.Solution.UniqueName,
                                        MergeLabels        = true
                                    };

                                    info.IsCreate = false;

                                    service.Execute(request);
                                    info.Success    = true;
                                    info.Processing = false;
                                    worker.ReportProgress(percent, info);
                                }
                                else
                                {
                                    info.Success    = false;
                                    info.Processing = false;
                                    info.Message    = error.Message;
                                    worker.ReportProgress(percent, info);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            info.Success    = false;
                            info.Processing = false;
                            info.Message    = e.Message;
                            worker.ReportProgress(percent, info);
                        }
                    }
                }
        }
示例#26
0
        public void Import(ExcelWorksheet sheet, List <EntityMetadata> emds, IOrganizationService service, BackgroundWorker worker)
        {
            var amds = new List <MasterAttribute>();

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

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(ZeroBasedSheet.Cell(sheet, rowI, 0).Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName   = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd     = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => string.Equals(a.LogicalName,
                                                                                         ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString(), StringComparison.OrdinalIgnoreCase));

                    if (amd.Amd == null
                        ) //still null? someone deleted the attribute while we were busy translating. Let's skip it!
                    {
                        OnResult(new TranslationResultEventArgs
                        {
                            Success   = false,
                            SheetName = sheet.Name,
                            Message   =
                                $"Attribute {ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString()} - {ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString()} is missing in CRM!"
                        });
                        continue;
                    }

                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new 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();
                            amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }
                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                {
                    amd.Amd.Description = new 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();
                            amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }

                        columnIndex++;
                    }
                }
            }

            int i = 0;

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label)) ||
                    amd.Amd.IsRenameable.Value == false)
                {
                    i++;
                    worker.ReportProgressIfPossible(0, new ProgressInfo
                    {
                        Item = i * 100 / amds.Count
                    });
                    continue;
                }
                try
                {
                    var request = new UpdateAttributeRequest
                    {
                        Attribute  = amd.Amd,
                        EntityName = amd.Amd.EntityLogicalName
                    };
                    service.Execute(request);

                    OnResult(new TranslationResultEventArgs
                    {
                        Success   = true,
                        SheetName = sheet.Name
                    });
                }
                catch (Exception error)
                {
                    OnResult(new TranslationResultEventArgs
                    {
                        Success   = false,
                        SheetName = sheet.Name,
                        Message   = $"{amd.Amd.SchemaName}: {error.Message}"
                    });
                }

                i++;
                worker.ReportProgressIfPossible(0, new ProgressInfo
                {
                    Item = i * 100 / amds.Count
                });
            }
        }
        public void RegisterDataSource()
        {
            var languageCode  = GetLanguageCode();
            var propertyFalse = new BooleanManagedProperty(false);
            var propertyTrue  = new BooleanManagedProperty(true);

            var request = new CreateEntityRequest
            {
                HasActivities    = false,
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = $"{DataSourceName}Name",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    DisplayName   = new Label(json.displayname, languageCode),
                    ExternalName  = json.displayname
                },
                Entity = new EntityMetadata
                {
                    DataProviderId                     = new Guid?(new Guid("B2112A7E-B26C-42F7-9B63-9A809A9D716F")),
                    IsActivity                         = new bool?(false),
                    SchemaName                         = DataSourceName,
                    DisplayName                        = new Label(json.displayname, languageCode),
                    DisplayCollectionName              = new Label(json.pluralname, languageCode),
                    ExternalCollectionName             = json.pluralname.Replace(" ", string.Empty),
                    ExternalName                       = json.displayname.Replace(" ", string.Empty),
                    OwnershipType                      = new OwnershipTypes?(OwnershipTypes.OrganizationOwned),
                    IsAvailableOffline                 = new bool?(false),
                    Description                        = new Label(string.Empty, languageCode),
                    IsBusinessProcessEnabled           = new bool?(false),
                    IsVisibleInMobile                  = propertyFalse,
                    IsVisibleInMobileClient            = propertyFalse,
                    IsReadOnlyInMobileClient           = propertyFalse,
                    IsOfflineInMobileClient            = propertyFalse,
                    IsAuditEnabled                     = propertyFalse,
                    IsSLAEnabled                       = new bool?(false),
                    IsBPFEntity                        = new bool?(false),
                    IsDuplicateDetectionEnabled        = propertyFalse,
                    IsConnectionsEnabled               = propertyFalse,
                    IsActivityParty                    = new bool?(false),
                    IsReadingPaneEnabled               = new bool?(false),
                    IsQuickCreateEnabled               = new bool?(false),
                    AutoCreateAccessTeams              = new bool?(false),
                    CanCreateCharts                    = propertyFalse,
                    IsMailMergeEnabled                 = propertyFalse,
                    ChangeTrackingEnabled              = new bool?(false),
                    CanChangeTrackingBeEnabled         = propertyFalse,
                    IsEnabledForExternalChannels       = new bool?(false),
                    EntityHelpUrlEnabled               = new bool?(false),
                    IsCustomizable                     = propertyTrue,
                    IsRenameable                       = propertyTrue,
                    IsMappable                         = propertyFalse,
                    SyncToExternalSearchIndex          = new bool?(false),
                    CanEnableSyncToExternalSearchIndex = propertyFalse,
                    CanModifyAdditionalSettings        = propertyFalse,
                    CanChangeHierarchicalRelationship  = propertyFalse
                }
            };

            if (request.Parameters == null)
            {
                request.Parameters = new ParameterCollection();
            }
            if (request.Parameters.ContainsKey("SolutionUniqueName"))
            {
                request.Parameters["SolutionUniqueName"] = json.solution;
            }
            else
            {
                request.Parameters.Add("SolutionUniqueName", json.solution);
            }
            var response = (CreateEntityResponse)crmServiceClient.Execute(request);
            var entityId = response.EntityId;
            var retrieveEntityRequest = new RetrieveEntityRequest()
            {
                EntityFilters = EntityFilters.All,
                MetadataId    = entityId
            };
            EntityMetadata entityMetadata = ((RetrieveEntityResponse)crmServiceClient.Execute(retrieveEntityRequest)).EntityMetadata;

            //Update field Id
            var requestId = new RetrieveAttributeRequest()
            {
                EntityLogicalName = entityMetadata.LogicalName,
                LogicalName       = string.Format("{0}id", entityMetadata.LogicalName)
            };
            var attributeMetadataId = ((RetrieveAttributeResponse)crmServiceClient.Execute(requestId)).AttributeMetadata;

            attributeMetadataId.ExternalName = $"{DataSourceName}Id";
            var updateRequestId = new UpdateAttributeRequest()
            {
                Attribute   = attributeMetadataId,
                EntityName  = entityMetadata.LogicalName,
                MergeLabels = false
            };

            crmServiceClient.Execute(updateRequestId);
            //Update field name
            var requestName = new RetrieveAttributeRequest()
            {
                EntityLogicalName = entityMetadata.LogicalName,
                LogicalName       = string.Format("{0}name", DataSourceName.ToLower())
            };
            var attributeMetadataName = ((RetrieveAttributeResponse)crmServiceClient.Execute(requestName)).AttributeMetadata;

            attributeMetadataName.ExternalName = $"{DataSourceName}Name";
            var updateRequestName = new UpdateAttributeRequest()
            {
                Attribute   = attributeMetadataName,
                EntityName  = entityMetadata.LogicalName,
                MergeLabels = false
            };

            crmServiceClient.Execute(updateRequestName);

            try
            {
                PublishAllXmlRequest  publishAllXmlRequest  = new PublishAllXmlRequest();
                PublishAllXmlResponse publishAllXmlResponse = (PublishAllXmlResponse)crmServiceClient.Execute(publishAllXmlRequest);
            }
            catch
            {
            }
        }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            var amds = new List<MasterAttribute>();

            var rowsCount = sheet.Dimension.Rows;
            var cellsCount = sheet.Dimension.Columns;
            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(ZeroBasedSheet.Cell(sheet, rowI, 0).Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName = ZeroBasedSheet.Cell(sheet, rowI, 1).Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => a.LogicalName == ZeroBasedSheet.Cell(sheet, rowI, 2).Value.ToString());
                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new 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();
                            amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }
                        columnIndex++;
                    }
                }
                else if (ZeroBasedSheet.Cell(sheet, rowI, 3).Value.ToString() == "Description")
                {
                    amd.Amd.Description = new 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();
                            amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(label, lcid));
                        }

                        columnIndex++;
                    }
                }
            }

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label))
                    || amd.Amd.IsRenameable.Value == false)
                    continue;

                var request = new UpdateAttributeRequest { Attribute = amd.Amd, EntityName = amd.Amd.EntityLogicalName };
                service.Execute(request);
            }
        }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            var amds = new List<MasterAttribute>();

            foreach (var row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                var amd = amds.FirstOrDefault(a => a.Amd.MetadataId == new Guid(row.Cells[0].Value.ToString()));
                if (amd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == row.Cells[1].Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName = row.Cells[1].Value.ToString(),
                            EntityFilters = EntityFilters.Entity | EntityFilters.Attributes
                        };

                        var response = ((RetrieveEntityResponse)service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    amd = new MasterAttribute();
                    amd.Amd = currentEntity.Attributes.FirstOrDefault(a => a.LogicalName == row.Cells[2].Value.ToString());
                    amds.Add(amd);
                }

                int columnIndex = 4;

                if (row.Cells[3].Value.ToString() == "DisplayName")
                {
                    amd.Amd.DisplayName = new Label();

                    while (row.Cells[columnIndex].Value != null)
                    {
                        amd.Amd.DisplayName.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
                else if (row.Cells[3].Value.ToString() == "Description")
                {
                    amd.Amd.Description = new Label();

                    while (row.Cells[columnIndex].Value != null)
                    {
                        amd.Amd.Description.LocalizedLabels.Add(new LocalizedLabel(row.Cells[columnIndex].Value.ToString(), int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                        columnIndex++;
                    }
                }
            }

            var sbError = new StringBuilder();

            foreach (var amd in amds)
            {
                if (amd.Amd.DisplayName.LocalizedLabels.All(l => string.IsNullOrEmpty(l.Label))
                    || amd.Amd.IsRenameable.Value == false)
                    continue;

                try
                {
                    var request = new UpdateAttributeRequest
                    {
                        Attribute = amd.Amd,
                        EntityName = amd.Amd.EntityLogicalName
                    };
                    service.Execute(request);
                }
                catch
                {
                    sbError.AppendLine(string.Format("- {0} ({1})", amd.Amd.LogicalName, amd.Amd.EntityLogicalName));
                }
            }

            if (sbError.Length > 0)
            {
                MessageBox.Show("Following attributes were not updated due to errors:\r\n" + sbError, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
示例#30
0
        private void TsbApplyChangesClick(object sender, EventArgs e)
        {
            if (entityInfos.All(ei => ei.Action == ActionState.None) &&
                attributeInfos.All(ai => ai.Action == ActionState.None))
                return;

            gbEntities.Enabled = false;
            gbAttributes.Enabled = false;
            toolStripMenu.Enabled = false;

            WorkAsync("Updating entities...",
                (bw, evt) =>
                {
                    foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                    {
                        if (ei.Action == ActionState.Added)
                        {
                            bw.ReportProgress(0,string.Format("Enabling entity '{0}' for audit...", ei.Emd.LogicalName));

                            ei.Emd.IsAuditEnabled.Value = true;
                        }
                        else if (ei.Action == ActionState.Removed)
                        {
                            bw.ReportProgress(0, string.Format("Disabling entity '{0}' for audit...", ei.Emd.LogicalName));

                            ei.Emd.IsAuditEnabled.Value = false;
                        }
                        else
                        {
                            continue;
                        }

                        var request = new UpdateEntityRequest { Entity = ei.Emd };
                        Service.Execute(request);

                        ei.Action = ActionState.None;
                    }

                    bw.ReportProgress(0, "Updating attributes...");

                    foreach (AttributeInfo ai in attributeInfos.OrderBy(a => a.Amd.EntityLogicalName).ThenBy(a => a.Amd.LogicalName))
                    {
                        if (ai.Action == ActionState.Added)
                        {
                            bw.ReportProgress(0, string.Format("Enabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                            ai.Amd.IsAuditEnabled.Value = true;
                        }
                        else if (ai.Action == ActionState.Removed)
                        {
                            bw.ReportProgress(0, string.Format("Disabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName));

                            ai.Amd.IsAuditEnabled.Value = false;
                        }
                        else
                        {
                            continue;
                        }

                        var request = new UpdateAttributeRequest { Attribute = ai.Amd, EntityName = ai.Amd.EntityLogicalName };
                        Service.Execute(request);

                        ai.Action = ActionState.None;
                    }

                    bw.ReportProgress(0, "Publishing changes...");

                    var publishRequest = new PublishXmlRequest { ParameterXml = "<importexportxml><entities>" };

                    foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName))
                    {
                        publishRequest.ParameterXml += string.Format("<entity>{0}</entity>", ei.Emd.LogicalName);
                    }

                    publishRequest.ParameterXml +=
                        "</entities><securityroles/><settings/><workflows/></importexportxml>";

                    Service.Execute(publishRequest);
                },
                evt =>
                {
                    if (evt.Error != null)
                    {
                        MessageBox.Show(this, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }

                    gbEntities.Enabled = true;
                    gbAttributes.Enabled = true;
                    toolStripMenu.Enabled = true;

                    tsbApplyChanges.Enabled = !((entityInfos.All(ei => ei.Action == ActionState.None) &&
                                          attributeInfos.All(ai => ai.Action == ActionState.None)));
                },
                evt => SetWorkingMessage(evt.UserState.ToString()));
        }