특성 메타데이터에 대한 작업

 

게시 날짜: 2017년 1월

적용 대상: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

이 항목에서는 샘플: 특성 메타데이터에 대한 작업의 코드 조각을 사용하여 특성을 사용할 때 일반적인 작업을 수행하는 방법을 보여 줍니다.

이 항목의 내용

특성 만들기

특성을 검색합니다.

특성 업데이트

조회 특성 만들기

고객 조회 특성 만들기

상태 값 업데이트

전역 옵션 집합을 사용하는 선택 목록 만들기

새 상태 값 삽입

로컬 옵션 집합에 새 옵션을 삽입합니다.

로컬 옵션 집합에서 옵션 순서를 변경

특성 삭제

특성 만들기

AttributeMetadata 유형 중 하나를 정의하여 특성을 만든 후 CreateAttributeRequest 메시지에 전달합니다.

다음 샘플에서는 많은 다른 유형의 특성에 대해 AttributeMetadata를 정의하고 List<AttributeMetadata>에 추가합니다. 코드의 끝에서 특성 정의는 CreateAttributeRequest 클래스의 인스턴스로 전달되고 특성은 Execute 메서드를 사용하여 만듭니다.

다음 샘플에서 조직 솔루션 게시자에 대한 기본 사용자 지정 접두사가 'new'이므로 현재 사용자 지정 접두사는 'new'입니다. 솔루션 게시자에 대해 솔루션 컨텍스트에 맞는 사용자 지정 접두사를 사용해야 합니다.


// 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);
}

특성을 검색합니다.

이 샘플에서는 RetrieveAttributeRequest를 사용하여 특성에 대해 AttributeMetadata를 검색합니다. 이 샘플에서는 특성 만들기에서 만든 연락처 엔터티에서 ‘new_string’이라는 사용자 지정 StringAttributeMetadata 특성에 대한 메타데이터를 검색합니다.

참고

RetrieveAsIfPublished는 true이므로 이 요청은 이 특성의 현재 게시되지 않은 정의를 반환합니다. 특성 편집기를 만들고 특성의 게시되지 않은 정의를 검색하려는 경우 이를 사용할 수 있습니다. 그렇지 않으면 RetrieveAsIfPublished를 지정하지 않아야 합니다.추가 정보:게시되지 않은 메타데이터 검색


// 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);

특성 업데이트

이 샘플에서는 특성을 업데이트하는 방법을 보여 줍니다. 이 샘플에서는 UpdateAttributeRequest를 사용하여 Contact 엔터티에 대해 이전에 검색한 사용자 지정 특성의 AttributeMetadata.DisplayName 속성을 변경합니다.


// 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);

조회 특성 만들기

조회 특성은 CreateOneToManyRequest를 사용하여 만듭니다.

이 샘플 코드는 조회 특성을 만드는 방법을 보여 줍니다. 전체 샘플을 보려면 샘플: 엔터티 메타데이터 만들기 및 업데이트 참조

CreateOneToManyRequest req = new CreateOneToManyRequest()
{
    Lookup = new LookupAttributeMetadata()
    {
        Description = new Label("The referral (lead) from the bank account owner", 1033),
        DisplayName = new Label("Referral", 1033),
        LogicalName = "new_parent_leadid",
        SchemaName = "New_Parent_leadId",
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended)
    },
    OneToManyRelationship = new OneToManyRelationshipMetadata()
    {
        AssociatedMenuConfiguration = new AssociatedMenuConfiguration()
        {
            Behavior = AssociatedMenuBehavior.UseCollectionName,
            Group = AssociatedMenuGroup.Details,
            Label = new Label("Bank Accounts", 1033),
            Order = 10000
        },
        CascadeConfiguration = new CascadeConfiguration()
        {
            Assign = CascadeType.Cascade,
            Delete = CascadeType.Cascade,
            Merge = CascadeType.Cascade,
            Reparent = CascadeType.Cascade,
            Share = CascadeType.Cascade,
            Unshare = CascadeType.Cascade
        },
        ReferencedEntity = "lead",
        ReferencedAttribute = "leadid",
        ReferencingEntity = _customEntityName,
        SchemaName = "new_lead_new_bankaccount"
    }
};
_serviceProxy.Execute(req);

고객 조회 특성 만들기

조회 특성과 달리 고객 조회 특성은 CreateCustomerRelationshipsRequest 메시지를 사용하여 만들어집니다. 이는 조회 특성에 Account 엔터티와 Contact 엔터티와의 두 관계를 추가합니다. 고객 조회 특성에 대한 AccountContact 엔터티를 제외하고 다른 엔터티를 추가할 수 없습니다.

참고

이 기능은 CRM Online 2016 업데이트 1 및 CRM 2016 서비스 팩 1(온-프레미스)에서 소개되었습니다.

이 샘플 코드는 고객 조회 특성을 만드는 방법을 보여 줍니다. 전체 샘플을 보려면 샘플: 엔터티 메타데이터 만들기 및 업데이트 참조

CreateCustomerRelationshipsRequest createCustomerReq = new CreateCustomerRelationshipsRequest
{
    Lookup = new LookupAttributeMetadata
    {
        Description = new Label("The owner of the bank account", 1033),
        DisplayName = new Label("Account owner", 1033),
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired),
        SchemaName = "new_customerid"
    },
    OneToManyRelationships = new OneToManyRelationshipMetadata[]
    {
        new OneToManyRelationshipMetadata()
        {
            ReferencedEntity = "account",
            ReferencingEntity = _customEntityName,
            SchemaName = "new_bankaccount_customer_account",
        },
        new OneToManyRelationshipMetadata()
        {
            ReferencedEntity = "contact",
            ReferencingEntity = _customEntityName,
            SchemaName = "new_bankaccount_customer_contact",
        }
    },
};
_serviceProxy.Execute(createCustomerReq);

전역 옵션 집합을 사용하는 선택 목록 만들기

이 샘플에서는 전역 옵션 집합에 연결되는 PicklistAttributeMetadata 특성을 만드는 방법을 보여 줍니다.

다음 샘플에서는 문자열 변수 _globalOptionSetName으로 표현되는 이름을 가진 전역 옵션 집합을 사용하기 위해 CreateAttributeRequest를 사용하여 PicklistAttributeMetadata 특성에 대한 옵션을 설정합니다.추가 정보:전역 옵션 집합 사용자 지정


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

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

_serviceProxy.Execute(createRequest);

새 상태 값 삽입

이 샘플에서는 StatusAttributeMetadata 특성에 대해 새 상태 설명 옵션을 삽입하는 방법을 보여 줍니다.

다음 샘플에서는 InsertStatusValueRequest를 사용하여 Contact.StateCode이 0(활성)일 때 유효한 Contact 엔터티 Contact.StatusCode 특성에 대한 새 옵션을 지정합니다.IOrganizationService.Execute 메서드는 요청을 처리합니다.

다음 샘플에서는 활성 연락처에 대해 상태 설명 옵션에 활성휴면의 두 가지 올바른 옵션을 허용합니다.


// 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);

상태 값 업데이트

이 샘플에서는 StateAttributeMetadata 특성에서 옵션의 레이블을 변경하는 방법을 보여 줍니다.

다음 샘플에서는 UpdateStateValueRequest를 사용하여 Contact.StateCode 옵션 레이블을 활성에서 시작됨으로 변경합니다.


// 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
    );

StateCode 옵션을 추가하거나 제거할 수 없지만 옵션의 레이블은 변경할 수 있습니다.

로컬 옵션 집합에 새 옵션을 삽입합니다.

이 샘플에서는 로컬 옵션 집합에 새 옵션을 추가하는 방법을 보여 줍니다. 다음 샘플에서는 InsertOptionValueRequest를 사용하여 Contact 엔터티에 대해 사용자 지정 PicklistAttributeMetadata 특성에 새 옵션을 추가합니다.


// 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);

로컬 옵션 집합에서 옵션 순서를 변경

이 샘플에서는 로컬 옵션 집합의 옵션 순서를 변경하는 방법을 보여 줍니다. 다음 샘플에서는 사용자 지정 PicklistAttributeMetadata 특성을 검색하고 OrderByLINQ 함수를 사용하여 원래 옵션의 순서를 변경하여 레이블 텍스트를 오름차순으로 항목을 정렬합니다. 그런 다음 OrderOptionRequest를 사용하여 특성에 대해 옵션의 새로운 순서를 설정합니다.

OrderByDecending linq 함수를 사용하여 내림차순으로 항목을 정렬합니다.


// 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");

특성 삭제

이 샘플에서는 특성 만들기에서 Contact 엔터티에 대해 만든 List<AttributeMetadata**>**로 정렬된 특성을 삭제하는 방법을 보여 줍니다. 각 AttributeMetadata의 경우 DeleteAttributeRequestIOrganizationService.Execute를 사용하여 처리되는 요청을 준비합니다.


// Delete all attributes created for this sample.
foreach (AttributeMetadata anAttribute in addedAttributes)
{
    // Create the request object
    DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest
    {
        // Set the request properties 
        EntityLogicalName = Contact.EntityLogicalName,
        LogicalName = anAttribute.SchemaName
    };
    // Execute the request
    _serviceProxy.Execute(deleteAttribute);
}

참고 항목

Customize 특성 메타데이터 메시지
Entity 특성 메타데이터 메시지
샘플: 특성 메타데이터에 대한 작업
엔터티 사용자 지정 및 특성 매핑

Microsoft Dynamics 365

© 2017 Microsoft. All rights reserved. 저작권 정보