コード例 #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 void SetSealedPropertyValue_should_update_attribute_metadata()
        {
            var fakeAttribute = new StringAttributeMetadata();

            fakeAttribute.SetSealedPropertyValue("IsManaged", false);
            Assert.Equal(false, fakeAttribute.IsManaged);
        }
コード例 #3
0
        public int?getMaxLength(string stringFieldName)
        {
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = _entity.LogicalName,
                LogicalName           = stringFieldName,
                RetrieveAsIfPublished = true
            };

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

            if (attributeResponse != null)
            {
                if (attributeResponse.AttributeMetadata is StringAttributeMetadata)
                {
                    StringAttributeMetadata attributeMetadata = (StringAttributeMetadata)attributeResponse.AttributeMetadata;

                    if (attributeMetadata.MaxLength != null)
                    {
                        return(attributeMetadata.MaxLength);
                    }
                }
            }
            return(null);
        }
コード例 #4
0
        private StringAttributeMetadata BuildAttribute()
        {
            AttributeRequiredLevel requiredLevel = AttributeRequiredLevel.ApplicationRequired;

            if (AttributeRequired == CrmRequiredLevel.Required)
            {
                requiredLevel = AttributeRequiredLevel.ApplicationRequired;
            }
            if (AttributeRequired == CrmRequiredLevel.Recommended)
            {
                requiredLevel = AttributeRequiredLevel.Recommended;
            }
            if (AttributeRequired == CrmRequiredLevel.Optional)
            {
                requiredLevel = AttributeRequiredLevel.None;
            }

            StringAttributeMetadata attribute = new StringAttributeMetadata();

            if (!IsActivity)
            {
                attribute.SchemaName    = AttributeName;
                attribute.RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel);
                attribute.MaxLength     = AttributeLength ?? 100;
                attribute.DisplayName   = new Label(AttributeDisplayName, CrmContext.Language);
                attribute.Description   = new Label(AttributeDescription ?? string.Empty, CrmContext.Language);
                attribute.Format        = StringFormat.Text;
            }
            else
            {
                attribute.SchemaName = "Subject";
                attribute.MaxLength  = 100;
            }
            return(attribute);
        }
コード例 #5
0
        public void CustomAttributesMatchingPatternMustSucceedTest()
        {
            EntityMetadata entity = new EntityMetadata()
            {
                SchemaName = "Account",
            };

            entity.SetSealedPropertyValue("IsManaged", true);
            entity.SetSealedPropertyValue("IsCustomEntity", false);

            var field1Metadata = new StringAttributeMetadata("foo_CustomField");

            field1Metadata.SetSealedPropertyValue("IsManaged", false);
            field1Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var attributes = new List <AttributeMetadata> {
                field1Metadata
            };

            var isOwnedBySolution = false;

            var validSolutionEntity = new SolutionEntity(entity,
                                                         attributes,
                                                         isOwnedBySolution);

            var regexPattern = @"^[A-Za-z]+_[A-Z]{1}[a-z]{1}[A-Za-z]*$";
            var scope        = RuleScope.Attribute;

            var ruleToTest = new RegexRule(regexPattern, scope);

            var results = ruleToTest.Validate(validSolutionEntity);

            Assert.True(results.Passed);
        }
コード例 #6
0
        public void Create(EntityMetadata entity, string primaryFieldName)
        {
            if (entity.SchemaName == null)
            {
                return;
            }

            var em = this._cdsConnection.GetEntityMetadata(entity.SchemaName);

            if (em == null)
            {
                var createRequest = new CreateEntityRequest();
                createRequest.Entity = entity;

                StringAttributeMetadata atr = new StringAttributeMetadata();
                atr.SchemaName    = primaryFieldName;
                atr.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                atr.MaxLength     = 100;
                atr.FormatName    = StringFormatName.Text;
                atr.DisplayName   = new Label("Name", 1033);
                createRequest.PrimaryAttribute = atr;

                Console.WriteLine("Creating entity...");
                this._cdsConnection.Execute(createRequest);
                Console.WriteLine("Entity created.");
            }
        }
コード例 #7
0
        public static void When_retrieve_attribute_request_is_called_correctly_attribute_is_returned()
        {
            var ctx     = new XrmFakedContext();
            var service = ctx.GetOrganizationService();

            var entityMetadata = new EntityMetadata()
            {
                LogicalName = "account"
            };
            var nameAttribute = new StringAttributeMetadata()
            {
                LogicalName   = "name",
                RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired)
            };

            entityMetadata.SetAttributeCollection(new[] { nameAttribute });

            ctx.InitializeMetadata(entityMetadata);

            RetrieveAttributeRequest req = new RetrieveAttributeRequest()
            {
                EntityLogicalName = "account",
                LogicalName       = "name"
            };

            var response = service.Execute(req) as RetrieveAttributeResponse;

            Assert.NotNull(response.AttributeMetadata);
            Assert.Equal(AttributeRequiredLevel.ApplicationRequired, response.AttributeMetadata.RequiredLevel.Value);
            Assert.Equal("name", response.AttributeMetadata.LogicalName);
        }
コード例 #8
0
        public void GetNameForRelationship_LooksUpReferencingEntityAttribute()
        {
            organizationMetadata.Entities.Returns(new[] {
                new EntityMetadata {
                    LogicalName = "ee_testprop", DisplayName = new Label("Test Prop", 1033)
                }
            });

            var relationship = new OneToManyRelationshipMetadata {
                ReferencingEntity = "ee_test", ReferencingAttribute = "ee_testid",
                ReferencedEntity  = "ee_testprop"
            };
            var attMetadata = new StringAttributeMetadata {
                LogicalName = "ee_testid", DisplayName = new Label("Test Id", 1033)
            };
            var metadata = new EntityMetadata {
                LogicalName = "ee_test"
            }
            .Set(x => x.Attributes, new AttributeMetadata[] { attMetadata })
            .Set(x => x.ManyToOneRelationships, new OneToManyRelationshipMetadata[]
            {
                relationship,
                new OneToManyRelationshipMetadata {
                    ReferencingEntity = "ee_testprop", ReferencingAttribute = "ee_testid"
                }
            });

            var output = sut.GetNameForRelationship(metadata, relationship, null, serviceProvider);

            Assert.AreEqual("TestId_TestProp", output);
        }
コード例 #9
0
        private object CopyValueInternal(AttributeMetadata oldAttribute, StringAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping)
        {
            var    copy = value.ToString();
            string mappedValue;

            return(migrationMapping.TryGetValue(copy, out mappedValue) ? mappedValue : copy);
        }
コード例 #10
0
        private StringAttributeMetadata BuildCreateStringAttribute()
        {
            // var createAttRequest = new CreateAttributeRequest();
            //DateTimeFormat dtFormat = DateTimeFormat.DateOnly;
            var stringAttribute = new StringAttributeMetadata();
            var dataType        = this.CurrentColumnDefinition.DataType;
            int maxLength       = 1; // default string max length 1.

            if (dataType.Arguments != null && dataType.Arguments.Any())
            {
                // first is scale, second is precision.

                var argsCount = dataType.Arguments.Count();
                if (argsCount > 1)
                {
                    throw new InvalidOperationException("Datatype can have a maximum of 1 size arguments.");
                }

                var maxLengthArg = dataType.Arguments.First();
                ((IVisitableBuilder)maxLengthArg).Accept(this);
                if (CurrentNumericLiteralValue != null)
                {
                    maxLength = Convert.ToInt32(CurrentNumericLiteralValue);
                    CurrentNumericLiteralValue = null;
                }
            }
            stringAttribute.MaxLength = maxLength;
            return(stringAttribute);
        }
コード例 #11
0
        private AttributeMetadata CreateStringAttribute(object[] dataRowValues)
        {
            var metadata = new StringAttributeMetadata
            {
                FormatName = StringFormatName.Text,
                MaxLength  = 100,
                ImeMode    = ImeMode.Auto
            };

            foreach (var column in Columns)
            {
                var value = dataRowValues[column.Position - 1];
                var field = (ConfigurationFile.AttributeFields)column.TargetField;

                if (value != null && !string.IsNullOrEmpty(value as string))
                {
                    switch (field)
                    {
                    case ConfigurationFile.AttributeFields.StringFormat:
                        var selectedBehavior = (int)EnumUtils.GetSelectedOption(field, value);
                        if (selectedBehavior == 0)
                        {
                            metadata.FormatName = StringFormatName.Email;
                        }
                        else if (selectedBehavior == 2)
                        {
                            metadata.FormatName = StringFormatName.TextArea;
                        }
                        else if (selectedBehavior == 3)
                        {
                            metadata.FormatName = StringFormatName.Url;
                        }
                        else if (selectedBehavior == 4)
                        {
                            metadata.FormatName = StringFormatName.TickerSymbol;
                        }
                        else if (selectedBehavior == 7)
                        {
                            metadata.FormatName = StringFormatName.Phone;
                        }
                        break;

                    case ConfigurationFile.AttributeFields.MaxLength:
                        metadata.MaxLength = Convert.ToInt32(value);
                        break;

                    case ConfigurationFile.AttributeFields.ImeMode:
                        metadata.ImeMode = (ImeMode)EnumUtils.GetSelectedOption(field, value);
                        break;
                    }
                }
                else if (!EnumUtils.IsOptional(field))
                {
                    throw new ArgumentException($"Mandatory data field {EnumUtils.Label(field)} does not contain a value.");
                }
            }

            return(metadata);
        }
コード例 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="SchemaName">Schema Name</param>
        /// <param name="DisplayName">Display Name</param>
        /// <param name="StringFormat">StringFormat.Url, StringFormat.Phone, StringFormat.Email</param>
        /// <param name="addedAttributes">Pass by reference.</param>
        /// <param name="lines">Pick among theses: 'singleLine', 'money', 'multi'. The option 'multi' is for memo.</param>
        static void createFieldString(string SchemaName, string DisplayName, StringFormat StringFormat, ref List <AttributeMetadata> addedAttributes, string lines = "singleLine")
        {
            if ("singleLine" == lines)
            {
                var EntityAttribute = new StringAttributeMetadata("new_" + SchemaName)
                {
                    SchemaName     = "new_" + SchemaName,
                    LogicalName    = "new_" + SchemaName,
                    DisplayName    = new Label(DisplayName + " *", 1033),
                    RequiredLevel  = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    Description    = new Label("MSVProperties CRM - " + DisplayName, 1033),
                    MaxLength      = 255,
                    IsValidForForm = true,
                    IsValidForGrid = true,
                    Format         = StringFormat,
                };
                addedAttributes.Add(EntityAttribute);
            }
            else if ("money" == lines)
            {
                var EntityAttribute = new MoneyAttributeMetadata("new_" + SchemaName)
                {
                    SchemaName    = "new_" + SchemaName,
                    LogicalName   = "new_" + SchemaName,
                    DisplayName   = new Label(DisplayName + " *", 1033),
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    Description   = new Label("MSVProperties CRM - " + DisplayName, 1033),
                    // Set extended properties
                    MinValue        = 0.00,
                    Precision       = 2,
                    PrecisionSource = 1,
                    ImeMode         = ImeMode.Disabled,
                    IsValidForForm  = true,
                    IsValidForGrid  = true,
                };

                addedAttributes.Add(EntityAttribute);
            }
            else
            {
                var EntityAttribute = new MemoAttributeMetadata("new_" + SchemaName)
                {
                    SchemaName    = "new_" + SchemaName,
                    LogicalName   = "new_" + SchemaName,
                    DisplayName   = new Label(DisplayName + " *", 1033),
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    Description   = new Label("MSVProperties CRM - " + DisplayName, 1033),
                    // Set extended properties
                    Format         = StringFormat.TextArea,
                    ImeMode        = ImeMode.Disabled,
                    MaxLength      = 1000,
                    IsValidForForm = true,
                    IsValidForGrid = true,
                };
                addedAttributes.Add(EntityAttribute);
            }
        }
コード例 #13
0
        public void OptionSetBeanTest04()
        {
            LocalizedLabel lLabel = new LocalizedLabel("Option1", 1041);

            StringAttributeMetadata meta = new StringAttributeMetadata();

            OptionSetBean cls = new OptionSetBean(meta);

            Assert.False(cls.HasOptionSet());
        }
コード例 #14
0
 private AttributeMetadata CloneAttributes(StringAttributeMetadata att)
 {
     return(new StringAttributeMetadata
     {
         Format = att.Format,
         FormatName = att.FormatName,
         ImeMode = att.ImeMode,
         MaxLength = att.MaxLength,
         YomiOf = att.YomiOf,
         FormulaDefinition = att.FormulaDefinition
     });
 }
コード例 #15
0
        public void UnmanagedAttributesOnOobEntityWithIncorrectNamesFailureDescriptionIsCorrectTest()
        {
            EntityMetadata entity = new EntityMetadata()
            {
                SchemaName  = "Account",
                DisplayName = new Label()
                {
                    UserLocalizedLabel = new LocalizedLabel("Asiakas", 1035)
                }
            };

            entity.SetSealedPropertyValue("IsManaged", true);
            entity.SetSealedPropertyValue("IsCustomEntity", false);

            var field1Metadata = new StringAttributeMetadata("foo_customField");

            field1Metadata.SetSealedPropertyValue("IsManaged", false);
            field1Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var field2Metadata = new StringAttributeMetadata("foo_c");

            field2Metadata.SetSealedPropertyValue("IsManaged", false);
            field2Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var field3Metadata = new StringAttributeMetadata("foo_CustomField");

            field3Metadata.SetSealedPropertyValue("IsManaged", false);
            field3Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var attributes = new List <AttributeMetadata> {
                field1Metadata,
                field2Metadata,
                field3Metadata
            };

            var isOwnedBySolution = false;

            var validSolutionEntity = new SolutionEntity(entity,
                                                         attributes,
                                                         isOwnedBySolution);

            var regexPattern = @"^[A-Za-z]+_[A-Z]{1}[a-z]{1}[A-Za-z]*$";
            var scope        = RuleScope.Attribute;

            var ruleToTest = new RegexRule(regexPattern, scope);

            var results = ruleToTest.Validate(validSolutionEntity);

            Assert.Equal($"Rule failed: {ruleToTest.Description} " +
                         "Following attributes do not match given pattern: " +
                         "foo_customField, foo_c.",
                         results.FormatValidationResult());
        }
コード例 #16
0
        private object CopyValueInternal(AttributeMetadata oldAttribute, StringAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping)
        {
            var copy = value.ToString();

            copy = migrationMapping.TryGetValue(copy, out var mappedValue) ? mappedValue : copy;
            if (copy.Length > newAttribute.MaxLength)
            {
                copy = copy.Limit(newAttribute.MaxLength ?? 100);
            }

            return(copy);
        }
コード例 #17
0
        public void SetAttribute_should_not_throw_error()
        {
            var entityMetadata = new EntityMetadata();
            var fakeAttribute  = new StringAttributeMetadata()
            {
                LogicalName = "name"
            };


            entityMetadata.SetAttribute(fakeAttribute);
            Assert.Equal(1, entityMetadata.Attributes.Length);
            Assert.Equal("name", entityMetadata.Attributes[0].LogicalName);
        }
コード例 #18
0
        public void GenerateAttributes()
        {
            var entityMetadata = new EntityMetadata {
                LogicalName = "ee_test", MetadataId = Guid.NewGuid(), DisplayName = new Label("Test", 1033)
            };
            var stringAttributeMetadata = new StringAttributeMetadata {
                LogicalName = "ee_teststring",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test String", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName);
            var picklistAttributeMetadata = new PicklistAttributeMetadata
            {
                LogicalName = "ee_testpicklist",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test Picklist", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName);
            var stateAttributeMetadata = new StateAttributeMetadata
            {
                LogicalName = "ee_teststate",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test State", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName);
            var imageAttributeMetadata = new ImageAttributeMetadata
            {
                LogicalName = "ee_testimage",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test Image", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName).Set(x => x.AttributeOf, "blah");

            organizationMetadata.Entities.Returns(new[] {
                entityMetadata.Set(x => x.Attributes, new AttributeMetadata [] { stringAttributeMetadata, picklistAttributeMetadata, stateAttributeMetadata, imageAttributeMetadata })
            });

            var f = Builder.Create <SolutionComponent>();

            f.Set(x => x.Regarding, entityMetadata.MetadataId);

            SolutionHelper.organisationService.RetrieveMultiple(Arg.Any <QueryExpression>())
            .Returns(new EntityCollection(new List <Entity> {
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, entityMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Entity),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, stringAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, picklistAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, stateAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, imageAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute)
            }));

            Assert.IsTrue(sut.GenerateAttribute(stringAttributeMetadata, serviceProvider));
            Assert.IsTrue(sut.GenerateAttribute(picklistAttributeMetadata, serviceProvider));
            Assert.IsTrue(sut.GenerateAttribute(stateAttributeMetadata, serviceProvider));
            Assert.IsTrue(sut.GenerateAttribute(imageAttributeMetadata, serviceProvider));
        }
コード例 #19
0
        static void Main(string[] args)
        {
            try
            {
                CrmServiceClient crmServiceClientObj = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CrmOnlineStringFromAppConfig"].ConnectionString);
                if (!crmServiceClientObj.IsReady)
                {
                    Console.WriteLine("No Connection was Made.");
                }
                Console.WriteLine("Connected");
                Console.WriteLine("Creating Auto number Attribute for Entity {0}", entityName);
                var attributeMetaData = new StringAttributeMetadata()
                {
                    //{DATETIMEUTC:yyyyMMddhhmmss} can also be used
                    AutoNumberFormat = "SYS {RANDSTRING:4} - ORG {SEQNUM:4}",

                    //this should be unique
                    SchemaName = "new_AutoNumAtt",

                    //set it as per required
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                    //Lable Name
                    DisplayName = new Microsoft.Xrm.Sdk.Label("Entity Code", 1033),

                    // On hover description
                    Description = new Microsoft.Xrm.Sdk.Label("The value will be AUTO GENERATED", 1033),

                    IsAuditEnabled = new Microsoft.Xrm.Sdk.BooleanManagedProperty(false),

                    // we need it to be searched direclty from global search.
                    IsGlobalFilterEnabled = new Microsoft.Xrm.Sdk.BooleanManagedProperty(true),
                    MaxLength             = 100 //
                };

                CreateAttributeRequest req = new CreateAttributeRequest()
                {
                    EntityName = entityName,
                    Attribute  = attributeMetaData
                };

                crmServiceClientObj.Execute(req);
                Console.WriteLine("Created Auto number Attribute for Entity {0}", entityName);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error here. " + e.Message);
                Console.ReadLine();
            }
        }
コード例 #20
0
        public void ExcludeUnmanagedAttributesWithIncorrectNamesFromValidationTest()
        {
            EntityMetadata entity = new EntityMetadata()
            {
                SchemaName = "Account",
            };

            entity.SetSealedPropertyValue("IsManaged", true);
            entity.SetSealedPropertyValue("IsCustomEntity", false);

            var field1Metadata = new StringAttributeMetadata("foo_customField");

            field1Metadata.SetSealedPropertyValue("IsManaged", false);
            field1Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var field2Metadata = new StringAttributeMetadata("foo_c");

            field2Metadata.SetSealedPropertyValue("IsManaged", false);
            field2Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var field3Metadata = new StringAttributeMetadata("foo_CustomField");

            field3Metadata.SetSealedPropertyValue("IsManaged", false);
            field3Metadata.SetSealedPropertyValue("IsCustomAttribute", true);

            var attributes = new List <AttributeMetadata> {
                field1Metadata,
                field2Metadata,
                field3Metadata
            };

            var isOwnedBySolution = false;

            var validSolutionEntity = new SolutionEntity(entity,
                                                         attributes,
                                                         isOwnedBySolution);

            var regexPattern       = @"^[A-Za-z]+_[A-Z]{1}[a-z]{1}[A-Za-z]*$";
            var scope              = RuleScope.Attribute;
            var excludedAttributes = new List <string> {
                "Account.foo_customField",
                "Account.foo_c"
            };

            var ruleToTest = new RegexRule(regexPattern, scope,
                                           excludedAttributes);

            var results = ruleToTest.Validate(validSolutionEntity);

            Assert.True(results.Passed);
        }
コード例 #21
0
        public void AddPrimaryAttributeNameMetadataToMock(string entityLogicalName, string attributeLogicalName)
        {
            var metadata = FakeXrmContext.GetEntityMetadataByName(entityLogicalName);

            var nameAttribute = new StringAttributeMetadata()
            {
                LogicalName   = attributeLogicalName,
                RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired),
            };

            metadata.SetAttributeCollection(new[] { nameAttribute });
            metadata.SetFieldValue("_primaryNameAttribute", attributeLogicalName);
            FakeXrmContext.SetEntityMetadata(metadata);
        }
コード例 #22
0
        public void GetNameForRelationship_ManyToMany()
        {
            organizationMetadata.Entities.Returns(new[] {
                new EntityMetadata {
                    LogicalName           = "ee_testprop",
                    DisplayCollectionName = new Label("Test Props", 1033)
                }
                .Set(x => x.Attributes, new AttributeMetadata[]
                {
                    new StringAttributeMetadata {
                        LogicalName = "ee_testid",
                        DisplayName = "Test Id".AsLabel()
                    }
                })
            });

            var relationship = new OneToManyRelationshipMetadata
            {
                ReferencingEntity    = "ee_testprop",
                ReferencingAttribute = "ee_testid",
                ReferencedEntity     = "ee_test",
                SchemaName           = "ee_two"
            };
            var many2Many = new ManyToManyRelationshipMetadata
            {
                Entity1LogicalName = "ee_test",
                Entity2LogicalName = "ee_testprop",
                SchemaName         = "ee_testProp_association"
            };
            var attMetadata = new StringAttributeMetadata {
                LogicalName = "ee_testid", DisplayName = "Test Id".AsLabel()
            };
            var metadata = new EntityMetadata {
                LogicalName = "ee_test"
            }
            .Set(x => x.Attributes, new AttributeMetadata[] { attMetadata })
            .Set(x => x.OneToManyRelationships, new OneToManyRelationshipMetadata[]
            {
                relationship,
                new OneToManyRelationshipMetadata {
                    ReferencingEntity = "ee_testprop", ReferencingAttribute = "ee_testid", SchemaName = "ee_one"
                }
            })
            .Set(x => x.ManyToManyRelationships, new[] { many2Many });

            var output = sut.GetNameForRelationship(metadata, many2Many, null, serviceProvider);

            Assert.AreEqual("TestProps", output);
        }
コード例 #23
0
        private void CreateTextField(JToken field)
        {
            var entitySchemaName = JSONUtil.GetText(field, "entity");
            var displayName      = JSONUtil.GetText(field, "displayname");
            var fieldSchemaName  = JSONUtil.GetText(field, "schemaname");

            var req = new CreateAttributeRequest();

            req.EntityName = entitySchemaName;

            var format = JSONUtil.GetText(field, "format");

            if (format == null)
            {
                format = "single";
            }

            int?maxlength = JSONUtil.GetInt32(field, "maxlength");

            if (format == "single")
            {
                var am = new StringAttributeMetadata();
                am.SchemaName    = field["schemaname"].ToString();
                am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);

                maxlength    = maxlength == null ? 100 : maxlength;
                am.MaxLength = maxlength;

                am.FormatName  = StringFormatName.Text;
                am.DisplayName = new Label(displayName, 1033);
                am.Description = new Label("", 1033);
                req.Attribute  = am;
            }
            else if (format == "multi")
            {
                var am = new MemoAttributeMetadata();
                am.SchemaName    = fieldSchemaName;
                am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);

                maxlength    = maxlength == null ? 2000 : maxlength;
                am.MaxLength = maxlength;

                am.DisplayName = new Label(displayName, 1033);
                am.Description = new Label("", 1033);
                req.Attribute  = am;
            }

            this._cdsConnection.Execute(req);
        }
コード例 #24
0
        public StringAttributeMetadata CreateString(string schema, string label, int lang, AttributeRequiredLevel requiredLevel, int size)
        {
            StringAttributeMetadata stringAttribute = new StringAttributeMetadata
            {
                // Set base properties
                SchemaName    = schema,
                DisplayName   = new Label(label, lang),
                RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                Description   = new Label(label, lang),
                // Set extended properties
                MaxLength = size
            };

            return(stringAttribute);
        }
コード例 #25
0
        private void SetupContext(XrmFakedContext context)
        {
            context.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata = new EntityMetadata();

                var property = entityMetadata
                               .GetType()
                               .GetProperty("Attributes");

                var subjectLabel = new StringAttributeMetadata
                {
                    LogicalName = "subject",
                    DisplayName = new Label
                    {
                        UserLocalizedLabel = new LocalizedLabel
                        {
                            LanguageCode = 1033,
                            Label        = "Subject Label"
                        }
                    }
                };

                var descriptionLabel = new StringAttributeMetadata
                {
                    LogicalName = "description",
                    DisplayName = new Label
                    {
                        UserLocalizedLabel = new LocalizedLabel
                        {
                            LanguageCode = 1033,
                            Label        = "Description Label"
                        }
                    }
                };

                var attributes = new AttributeMetadata[] { subjectLabel, descriptionLabel };
                property.GetSetMethod(true).Invoke(entityMetadata, new object[] { attributes });

                return(new RetrieveEntityResponse
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                });
            });
        }
コード例 #26
0
        public static void When_using_proxy_types_assembly_the_attribute_metadata_is_inferred_from_injected_metadata_as_a_fallback()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["injectedAttribute"] = "Contact 1";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["injectedAttribute"] = "Contact 2";

            fakedContext.Initialize(new List <Entity>()
            {
                contact1, contact2
            });

            var contactMetadata = new EntityMetadata()
            {
                LogicalName = "contact"
            };

            var injectedAttribute = new StringAttributeMetadata()
            {
                LogicalName = "injectedAttribute"
            };

            contactMetadata.SetAttribute(injectedAttribute);
            fakedContext.InitializeMetadata(contactMetadata);

            var guid = Guid.NewGuid();

            //Empty contecxt (no Initialize), but we should be able to query any typed entity without an entity not found exception

            var service = fakedContext.GetOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c["injectedAttribute"].Equals("Contact 1")
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
コード例 #27
0
        public StringAttributeMetadata Create(AttributeMetadata baseMetadata, int?maxLength)
        {
            var stringAttribute = new StringAttributeMetadata
            {
                // Set base properties
                SchemaName    = baseMetadata.SchemaName,
                DisplayName   = baseMetadata.DisplayName,
                RequiredLevel = baseMetadata.RequiredLevel,
                Description   = baseMetadata.Description,

                // Set extended properties
                MaxLength = maxLength
            };

            return(stringAttribute);
        }
        private IEnumerable <string> checkDifferenceStringAttribute(StringAttributeMetadata originalAttributeMetadata, StringAttributeMetadata readAttributeMetadata)
        {
            List <string> attributeToChange = new List <string>();

            if (originalAttributeMetadata.MaxLength != readAttributeMetadata.MaxLength)
            {
                originalAttributeMetadata.MaxLength = readAttributeMetadata.MaxLength;
                attributeToChange.Add("MaxLength");
            }
            if (originalAttributeMetadata.ImeMode != readAttributeMetadata.ImeMode)
            {
                originalAttributeMetadata.ImeMode = readAttributeMetadata.ImeMode;
                attributeToChange.Add("ImeMode");
            }
            return(attributeToChange);
        }
        private AttributeMetadata stringFieldCreation(string[] row)
        {
            StringAttributeMetadata attrMetadata = new StringAttributeMetadata(Utils.addOrgPrefix(row[ExcelColumsDefinition.SCHEMANAMEEXCELCOL], organizationPrefix, currentOperationCreate));

            generalFieldCreation(row, attrMetadata);
            int parseResult;

            attrMetadata.MaxLength = int.TryParse(row[ExcelColumsDefinition.STRINGMAXLENGTHCOL], out parseResult) ? parseResult : 100;
            string imeModeFormatString = row[ExcelColumsDefinition.STRINGIMEMODECOL];

            attrMetadata.ImeMode = Enum.IsDefined(typeof(ImeMode), imeModeFormatString) ? (ImeMode)Enum.Parse(typeof(ImeMode), imeModeFormatString, true) : (ImeMode?)null;
            string       formatString = row[ExcelColumsDefinition.STRINGFORMATCOL];
            StringFormat?stringFormat = Enum.IsDefined(typeof(StringFormat), formatString) ? (StringFormat)Enum.Parse(typeof(StringFormat), formatString, true) : StringFormat.Text;

            attrMetadata.Format = stringFormat;
            return(attrMetadata);
        }
コード例 #30
0
        private static StringAttributeMetadata CreateStringAttribute(string name, string displayName, AttributeRequiredLevel attributeRequiredLevel, string desription, int maxLength, StringFormat format = StringFormat.Text)
        {
            // Create a boolean attribute
            StringAttributeMetadata stringAttribute = new StringAttributeMetadata
            {
                // Set base properties
                SchemaName    = publisherPrefix + name,
                LogicalName   = publisherPrefix + name,
                DisplayName   = new Label(displayName, _languageCode),
                RequiredLevel = new AttributeRequiredLevelManagedProperty(attributeRequiredLevel),
                Description   = new Label(desription, _languageCode),
                Format        = format,
                // Set extended properties
                MaxLength = maxLength
            };

            return(stringAttribute);
        }
コード例 #31
0
        public EntityAttributeMetadataBuilder StringAttribute(string schemaName, string displayName, string description,
                                                              AttributeRequiredLevel requiredLevel,
                                                              int maxLength, StringFormat format)
        {
            // Define the primary attribute for the entity
            var newAtt = new StringAttributeMetadata
            {
                SchemaName    = schemaName,
                RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                MaxLength     = maxLength,
                Format        = format,
                DisplayName   = new Label(displayName, 1033),
                Description   = new Label(description, 1033)
            };

            this.Attributes.Add(newAtt);
            return(this);
        }
コード例 #32
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Link the custom attributes.
        /// Optionally delete any entity records that were created 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();


                    //<snippetLinkCustomAttributesBetweenSeriesandInstances1>                

                    // Create a custom string attribute for the appointment instance
                    StringAttributeMetadata customAppointmentInstanceAttribute = new StringAttributeMetadata
                    {
                        LogicalName = "new_customAppInstanceAttribute",
                        DisplayName = new Label("CustomAppInstanceAttribute", 1033),
                        Description = new Label("Sample Custom Appointment Instance Attribute", 1033),
                        MaxLength = 500,
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        SchemaName = "new_customAppInstanceAttribute"
                    };

                    CreateAttributeRequest instanceAttributeRequest = new CreateAttributeRequest
                    {
                        Attribute = customAppointmentInstanceAttribute,
                        EntityName = "appointment"
                    };

                    CreateAttributeResponse instanceAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(instanceAttributeRequest);
                    _instanceAttributeID = instanceAttributeResponse.AttributeId;

                    // Create a custom string attribute for the recurring appointment master (series)
                    StringAttributeMetadata customAppointmentSeriesAttribute = new StringAttributeMetadata
                    {
                        LogicalName = "new_customAppSeriesAttribute",
                        DisplayName = new Label("CustomAppSeriesAttribute", 1033),
                        Description = new Label("Sample Custom Appointment Series Attribute", 1033),
                        MaxLength = 500,
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        SchemaName = "new_customAppSeriesAttribute",
                        LinkedAttributeId = _instanceAttributeID // Link the custom attribute to the appointment’s custom attribute.
                    };

                    CreateAttributeRequest seriesAttributeRequest = new CreateAttributeRequest
                    {
                        Attribute = customAppointmentSeriesAttribute,
                        EntityName = "recurringappointmentmaster"
                    };

                    CreateAttributeResponse seriesAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(seriesAttributeRequest);
                    _seriesAttributeID = seriesAttributeResponse.AttributeId;

                    // Publish all the changes to the solution.
                    PublishAllXmlRequest createRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(createRequest);

                    Console.WriteLine("Created a custom string attribute, {0}, for the appointment.", customAppointmentInstanceAttribute.LogicalName);
                    Console.WriteLine("Created a custom string attribute, {0}, for the recurring appointment, and linked it with {1}.", customAppointmentSeriesAttribute.LogicalName, customAppointmentInstanceAttribute.LogicalName);

                    //</snippetLinkCustomAttributesBetweenSeriesandInstances1>

                    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;
            }
        }
コード例 #33
0
 private StringAttributeMetadata CreateStringAttributeMetadata(AttributeTemplate attributeTemplate)
 {
     var stringAttributeMetadata = new StringAttributeMetadata
     {
         MaxLength = attributeTemplate.MaxLength == default(int)
             ? DefaultConfiguration.DefaultStringMaxLength
             : attributeTemplate.MaxLength,
         FormatName = attributeTemplate.StringFormatName == default(StringFormatName)
             ? DefaultConfiguration.DefaultStringFormatName
             : attributeTemplate.StringFormatName
     };
     return stringAttributeMetadata;
 }
コード例 #34
0
        private StringAttributeMetadata GetPrimaryAttribute(EntityTemplate entityTemplate)
        {
            var primaryAttribute = (from attribute in entityTemplate.AttributeList where attribute.AttributeType == typeof(Primary) select attribute).FirstOrDefault();

            var stringAttributeMetadata = new StringAttributeMetadata
            {
                SchemaName = primaryAttribute != null ? primaryAttribute.LogicalName : DefaultConfiguration.DefaultPrimaryAttribute,
                RequiredLevel = new AttributeRequiredLevelManagedProperty(
                    primaryAttribute != null && primaryAttribute.IsRequired ? AttributeRequiredLevel.SystemRequired : AttributeRequiredLevel.None),
                DisplayName = GetLabelWithLocalized(primaryAttribute != null ? primaryAttribute.DisplayNameShort : DefaultConfiguration.DefaultPrimaryAttributeDisplayName),
                Description = GetLabelWithLocalized(primaryAttribute != null ? primaryAttribute.Description : DefaultConfiguration.DefaultPrimaryAttributeDescription),
                MaxLength = primaryAttribute != null ? primaryAttribute.MaxLength : DefaultConfiguration.DefaultStringMaxLength,
                FormatName = DefaultConfiguration.DefaultStringFormatName
            };
            return stringAttributeMetadata;
        }
コード例 #35
0
        internal void CreatePowerBiOptionSetRefEntity(int lcid, BackgroundWorker bw = null)
        {
            bool entityCreated = false;

            try
            {
                var emd = new EntityMetadata
                {
                    LogicalName = "gap_powerbioptionsetref",
                    SchemaName = "gap_PowerBIOptionsetRef",
                    DisplayName = new Label("Power BI Option-Set Xref", lcid),
                    DisplayCollectionName = new Label("Power BI Option-Set Xrefs", lcid),
                    Description = new Label("Created automatically by Power BI Option-Set Xref XrmToolBox plugin", lcid),
                    OwnershipType = OwnershipTypes.OrganizationOwned,
                };

                var pamd = new StringAttributeMetadata
                {
                    LogicalName = "gap_optionsetschemaname",
                    SchemaName = "gap_OptionsetSchemaName",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength = 100,
                    FormatName = StringFormatName.Text,
                    DisplayName = new Label("Option Set Schema Name", lcid)
                };

                service.Execute(new CreateEntityRequest
                {
                    Entity = emd,
                    PrimaryAttribute = pamd,
                    HasActivities = false,
                    HasNotes = false
                });

                entityCreated = true;

                if (bw != null && bw.WorkerReportsProgress)
                {
                    bw.ReportProgress(0, "Creating Entity schema name attribute");
                }

                // Entity schema name
                service.Execute(new CreateAttributeRequest
                {
                    EntityName = emd.LogicalName,
                    Attribute = new StringAttributeMetadata
                    {
                        SchemaName = "gap_EntitySchemaName",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        MaxLength = 100,
                        FormatName = StringFormatName.Text,
                        DisplayName = new Label("Entity Schema Name", lcid),
                    }
                });

                if (bw != null && bw.WorkerReportsProgress)
                {
                    bw.ReportProgress(0, "Creating Entity name attribute");
                }

                // Entity name
                service.Execute(new CreateAttributeRequest
                {
                    EntityName = emd.LogicalName,
                    Attribute = new StringAttributeMetadata
                    {
                        SchemaName = "gap_EntityName",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        MaxLength = 100,
                        FormatName = StringFormatName.Text,
                        DisplayName = new Label("Entity Name", lcid),
                    }
                });

                if (bw != null && bw.WorkerReportsProgress)
                {
                    bw.ReportProgress(0, "Creating Language attribute");
                }

                // LCID
                service.Execute(new CreateAttributeRequest
                {
                    EntityName = emd.LogicalName,
                    Attribute = new IntegerAttributeMetadata
                    {
                        SchemaName = "gap_Language",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Format = IntegerFormat.Language,
                        DisplayName = new Label("Language", lcid),
                    }
                });

                if (bw != null && bw.WorkerReportsProgress)
                {
                    bw.ReportProgress(0, "Creating Option Value attribute");
                }

                // Value
                service.Execute(new CreateAttributeRequest
                {
                    EntityName = emd.LogicalName,
                    Attribute = new IntegerAttributeMetadata
                    {
                        SchemaName = "gap_Value",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        Format = IntegerFormat.None,
                        DisplayName = new Label("Option Value", lcid),
                    }
                });

                if (bw != null && bw.WorkerReportsProgress)
                {
                    bw.ReportProgress(0, "Creating Option Label attribute");
                }

                // Label
                service.Execute(new CreateAttributeRequest
                {
                    EntityName = emd.LogicalName,
                    Attribute = new StringAttributeMetadata
                    {
                        SchemaName = "gap_Label",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        MaxLength = 200,
                        FormatName = StringFormatName.Text,
                        DisplayName = new Label("Option Label", lcid),
                    }
                });
            }
            catch (Exception)
            {
                if (entityCreated)
                {
                    DeleteEntity("gap_powerbioptionsetref");
                }

                throw;
            }
        }
コード例 #36
0
 private AttributeMetadata CloneAttributes(StringAttributeMetadata att)
 {
     return new StringAttributeMetadata
     {
         Format = att.Format,
         FormatName = att.FormatName,
         ImeMode = att.ImeMode,
         MaxLength = att.MaxLength,
         YomiOf = att.YomiOf,
         FormulaDefinition = att.FormulaDefinition
     };
 }
コード例 #37
0
 public EntityAttributeMetadataBuilder StringAttribute(string schemaName, string displayName, string description,
                                                        AttributeRequiredLevel requiredLevel,
                                                        int maxLength, StringFormat format)
 {
     // Define the primary attribute for the entity
     var newAtt = new StringAttributeMetadata
     {
         SchemaName = schemaName,
         RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
         MaxLength = maxLength,
         Format = format,
         DisplayName = new Label(displayName, 1033),
         Description = new Label(description, 1033)
     };
     this.Attributes.Add(newAtt);
     return this;
 }
コード例 #38
0
ファイル: XrmService.cs プロジェクト: josephmcmac/JosephM.Xrm
        /// <summary>
        ///     DOESN'T UPDATE PRIMARY FIELD - CALL THE CREATEORUPDATESTRING METHOD
        /// </summary>
        public void CreateOrUpdateEntity(string schemaName, string displayName, string displayCollectionName,
            string description, bool audit, string primaryFieldSchemaName,
            string primaryFieldDisplayName, string primaryFieldDescription,
            int primaryFieldMaxLength, bool primaryFieldIsMandatory, bool primaryFieldAudit, bool isActivityType,
            bool notes, bool activities, bool connections, bool mailMerge, bool queues)
        {
            lock (LockObject)
            {
                var metadata = new EntityMetadata();

                var exists = EntityExists(schemaName);
                if (exists)
                    metadata = GetEntityMetadata(schemaName);

                metadata.SchemaName = schemaName;
                metadata.LogicalName = schemaName;
                metadata.DisplayName = new Label(displayName, 1033);
                metadata.DisplayCollectionName = new Label(displayCollectionName, 1033);
                metadata.IsAuditEnabled = new BooleanManagedProperty(audit);
                metadata.IsActivity = isActivityType;
                metadata.IsValidForQueue = new BooleanManagedProperty(queues);
                metadata.IsMailMergeEnabled = new BooleanManagedProperty(mailMerge);
                metadata.IsConnectionsEnabled = new BooleanManagedProperty(connections);
                metadata.IsActivity = isActivityType;
                if (!String.IsNullOrWhiteSpace(description))
                    metadata.Description = new Label(description, 1033);

                if (exists)
                {
                    var request = new UpdateEntityRequest
                    {
                        Entity = metadata,
                        HasActivities = activities,
                        HasNotes = notes
                    };
                    Execute(request);
                }
                else
                {
                    metadata.OwnershipType = OwnershipTypes.UserOwned;

                    var primaryFieldMetadata = new StringAttributeMetadata();
                    SetCommon(primaryFieldMetadata, primaryFieldSchemaName, primaryFieldDisplayName,
                        primaryFieldDescription,
                        primaryFieldIsMandatory, primaryFieldAudit, true);
                    primaryFieldMetadata.MaxLength = primaryFieldMaxLength;

                    var request = new CreateEntityRequest
                    {
                        Entity = metadata,
                        PrimaryAttribute = primaryFieldMetadata,
                        HasActivities = activities,
                        HasNotes = notes
                    };
                    Execute(request);
                    RefreshFieldMetadata(primaryFieldSchemaName, schemaName);
                }
                RefreshEntityMetadata(schemaName);
            }
        }
コード例 #39
0
ファイル: XrmService.cs プロジェクト: josephmcmac/JosephM.Xrm
        public void CreateOrUpdateStringAttribute(string schemaName, string displayName, string description,
            bool isRequired, bool audit, bool searchable,
            string recordType, int? maxLength, StringFormat stringFormat)
        {
            StringAttributeMetadata metadata;
            if (FieldExists(schemaName, recordType))
                metadata = (StringAttributeMetadata) GetFieldMetadata(schemaName, recordType);
            else
                metadata = new StringAttributeMetadata();
            SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable);

            metadata.MaxLength = maxLength;
            metadata.Format = stringFormat;

            CreateOrUpdateAttribute(schemaName, recordType, metadata);

            if (GetEntityMetadata(recordType).PrimaryNameAttribute == schemaName)
                RefreshEntityMetadata(recordType);
        }
コード例 #40
0
        public void OptionSetBeanTest04()
        {
            LocalizedLabel lLabel = new LocalizedLabel("Option1", 1041);

            StringAttributeMetadata meta = new StringAttributeMetadata();

            OptionSetBean cls = new OptionSetBean(meta);

            Assert.False(cls.HasOptionSet());
        }
 private static UpdateFormulaResponse UpdateInternal(StringAttributeMetadata   att, AttributeMetadata from, AttributeMetadata to) { return UpdateForumlaDefinition(att, from, to); }
コード例 #42
0
 public StringAttributeMetadataInfo(StringAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
コード例 #43
0
 private object CopyValueInternal(AttributeMetadata oldAttribute, StringAttributeMetadata newAttribute, object value)
 {
     return value.ToString();
 }