Utilizzare i metadati degli attributi

 

Data di pubblicazione: gennaio 2017

Si applica a: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

In questo argomento vengono utilizzati frammenti di codice da Esempio: Utilizzare i metadati degli attributi per mostrare come eseguire attività comuni quando si utilizzano attributi.

In questo argomento

Creare attributi

Recuperare un attributo

Aggiornare un attributo

Creare un attributo di tipo lookup

Creare un attributo di tipo lookup cliente

Aggiornare un valore di stato

Creare un elenco a discesa che utilizza un set di opzioni globale

Inserire un nuovo valore di stato

Inserire una nuova opzione in un set di opzioni locale.

Modificare l'ordine delle opzioni di un set di opzioni locale

Eliminare un attributo

Creare attributi

Si creano attributi definendo uno dei tipi AttributeMetadata e quindi passandolo al messaggio CreateAttributeRequest.

Nell'esempio di seguito viene definito AttributeMetadata per una serie di tipi di attributi diversi e vengono aggiunti a un List<AttributeMetadata>. Al termine del codice le definizioni di attributo vengono passate a un'istanza della classe CreateAttributeRequest e l'attributo viene creato utilizzando il metodo Execute.

Nell'esempio di seguito viene presupposto che il prefisso corrente di personalizzazione sia "nuovo" poiché si tratta del prefisso predefinito di personalizzazione per l'autore di soluzioni dell'organizzazione. È consigliabile utilizzare il prefisso di personalizzazione per l'autore di soluzioni appropriato per il contesto della soluzione.


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

Recuperare un attributo

In questo esempio vengono illustrate le procedure per recuperare AttributeMetadata per un attributo usando RetrieveAttributeRequest. In questo esempio vengono recuperati i metadati per un attributo StringAttributeMetadata personalizzato denominato "new_string" dall'entità Contatto creata in Creare attributi.

Nota

Poiché RetrieveAsIfPublished è true, questa richiesta restituisce la definizione corrente non pubblicata di tale attributo. È possibile utilizzare questo approccio se si sta creando un editor di attributo e si desidera recuperare la definizione non pubblicata dell'attributo. Altrimenti, non è consigliabile specificare RetrieveAsIfPublished.Ulteriori informazioni:Recupero di metadati non pubblicati


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

Aggiornare un attributo

In questo esempio vengono illustrate le procedure per aggiornare un attributo. In questo esempio viene utilizzato UpdateAttributeRequest per modificare la proprietà AttributeMetadata.DisplayName di un attributo personalizzato recuperato in precedenza per l'entità di Contact.


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

Creare un attributo di tipo lookup

Un attributo di tipo lookup viene creato con CreateOneToManyRequest.

In questo esempio di codice vengono illustrate le procedure per creare un attributo di tipo lookup. Per un esempio completo, vedere Esempio: creare e aggiornare i metadati di un'entità.

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

Creare un attributo di tipo lookup cliente

A differenza di un attributo di tipo lookup, un attributo di tipo lookup cliente viene creato utilizzando il messaggio CreateCustomerRelationshipsRequest, che consente di aggiungere due relazioni all'attributo di tipo lookup: una con l'entità Account e l'altra con l'entità Contact. Per attributi di tipo lookup cliente, non è possibile aggiungere relazioni ad alcuna entità ad eccezione di Account e Contact.

Nota

Questa funzionalità è stata introdotta nell'Aggiornamento 1 di CRM Online 2016 e in CRM 2016 Service Pack 1 (locale).

In questo esempio di codice vengono illustrate le procedure per creare un attributo di tipo lookup cliente. Per un esempio completo, vedere Esempio: creare e aggiornare i metadati di un'entità.

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

Creare un elenco a discesa che utilizza un set di opzioni globale

In questo esempio vengono illustrate le procedure per creare un attributo PicklistAttributeMetadata associato a un set di opzioni globale.

Nell'esempio di seguito viene utilizzato CreateAttributeRequest per impostare le opzioni per un attributo PicklistAttributeMetadata per utilizzare un set di opzioni globale con un nome rappresentato dalla variabile della stringa _globalOptionSetName.Ulteriori informazioni:Personalizzare set di opzioni globali


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

Inserire un nuovo valore di stato

In questo esempio vengono illustrate le procedure per inserire una nuova opzione Motivo stato per l'attributo StatusAttributeMetadata.

Nell'esempio seguente viene utilizzato InsertStatusValueRequest per specificare una nuova opzione per l'attributo Contact.StatusCode dell'entità Contact che è valido se Contact.StateCode è 0 (Attivo). Il metodo IOrganizationService.Execute elabora la richiesta.

Nell'esempio seguente vengono consentite due opzioni valide Motivo stato per i contatti attivi: Attivo e Inattivo.


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

Aggiornare un valore di stato

In questo esempio vengono illustrate le procedure per modificare l'etichetta di un'opzione in un attributo di StateAttributeMetadata.

Nell'esempio seguente viene utilizzato UpdateStateValueRequest per modificare l'etichetta dell'opzione Contact.StateCode da Attiva in Aperta.


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

Non è possibile aggiungere o rimuovere opzioni StateCode, ma è possibile modificare le etichette per le opzioni.

Inserire una nuova opzione in un set di opzioni locale.

In questo esempio vengono illustrate le procedure per aggiungere una nuova opzione a un set di opzioni locale. Nell'esempio seguente viene utilizzato InsertOptionValueRequest per aggiungere una nuova opzione a un attributo personalizzato PicklistAttributeMetadata per l'entità di Contact.


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

Modificare l'ordine delle opzioni di un set di opzioni locale

In questo esempio vengono illustrate le procedure per modificare l'ordine delle opzioni in un set di opzioni locale. Nell'esempio seguente viene recuperato un attributo personalizzato PicklistAttributeMetadata e modificato l'ordine delle opzioni originale utilizzando la funzione LINQOrderBy per ordinare gli elementi in ordine crescente in base al testo dell'etichetta. Quindi utilizza OrderOptionRequest per impostare il nuovo ordine delle opzioni per l'attributo.

Utilizzare la funzione LINQ OrderByDecending per ordinare gli elementi in ordine decrescente.


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

Eliminare un attributo

In questo esempio vengono illustrate le procedure per eliminare gli attributi salvati in un List<AttributeMetadata> creati per l'entità Contact in Creare attributi. Per ogni AttributeMetadata, DeleteAttributeRequest redige la richiesta che viene elaborata utilizzando IOrganizationService.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);
}

Vedere anche

Personalizzare i metadati degli attributi di entità
Messaggi dei metadati degli attributi di entità
Esempio: Utilizzare i metadati degli attributi
Personalizzare mapping di entità e attributi

Microsoft Dynamics 365

© 2017 Microsoft. Tutti i diritti sono riservati. Copyright