Oggetti server

La logica del server fornisce oggetti predefiniti nello spazio dei nomi del server. Questi oggetti semplificano lo sviluppo consentendo di registrare messaggi, chiamare servizi esterni, usare Dataverse o accedere ai dettagli delle richieste.

HttpClient

Usare il client HTTP per l'integrazione con i servizi esterni inviando richieste HTTP.

Annotazioni

Attualmente, la logica del server supporta solo application/jsoni tipi di contenuto , text/htmle application/x-www-form-urlencoded nel corpo della richiesta.

Examples

HTTP GET

let url = "https://contoso.com/objects";
let header = { client_id: "00001111-aaaa-2222-bbbb-3333cccc4444" };

let response = await Server.Connector.HttpClient.GetAsync(url, header);

HTTP POST

let url = "https://contoso.com/objects";
let body = JSON.stringify({ name: "Sample Account" });
let header = { client_id: "00001111-aaaa-2222-bbbb-3333cccc4444" };
let contentType = "application/json";

// Make the POST request
let response = await Server.Connector.HttpClient.PostAsync(url, body, header, contentType);

HTTP PUT

let url = "https://contoso.com/objects/6";
let body = JSON.stringify({ name: "Updated Sample Account" });
let header = { client_id: "00001111-aaaa-2222-bbbb-3333cccc4444" };
let contentType = "application/json";

// Make the PUT request
let response = await Server.Connector.HttpClient.PutAsync(url, body, header, contentType);

HTTP PATCH

let url = "https://contoso.com/objects/6";
let body = JSON.stringify({ name: "{\"capacity\": \"2 TB\"}" });
let header = { client_id: "00001111-aaaa-2222-bbbb-3333cccc4444" };
let contentType = "application/json";

// Make the PATCH request
let response = await Server.Connector.HttpClient.PatchAsync(url, body, header, contentType);

HTTP DELETE

let url = "https://contoso.com/objects/6";
let header = { contentType: "application/json" };

let response = await Server.Connector.HttpClient.DeleteAsync(url, header);

Esempio: risposta

{
    "StatusCode": 200,
    "Body": "JsonString",
    "IsSuccessStatusCode": true,
    "ReasonPhrase": "OK",
    "ServerError": false,
    "ServerErrorMessage": null,
    "Headers": {
        "Transfer-Encoding": "chunked",
        "Connection": "keep-alive",
        "Server": "",
        "Content-Type": "application/json"
    }
}

SiteSetting

Consente di leggere i valori delle impostazioni del sito per il sito Web corrente.

Annotazioni

Non archiviare segreti, ad esempio chiavi API o credenziali, direttamente nella logica del server. Al contrario, archiviarli in modo sicuro in Azure Key Vault, eseguirne l'origine tramite le variabili di ambiente e farvi riferimento usando le impostazioni del sito.

Example

Server.SiteSetting.Get("Search/Enabled");

EnvironmentVariable

Legge il valore di una variabile di ambiente.

Example

Server.EnvironmentVariable.get("SITEPATH");

Sito web

Fornisce i dettagli del record del sito Web corrente in Dataverse.

Example

Server.Website.adx_primarydomain;

Utente

Fornisce i dettagli dell'utente connesso. Restituisce Null se anonimo.

Example

Server.User.fullname;

Dataverse

Usare l'oggetto Server.Connector.Dataverse per eseguire operazioni CRUD sulle tabelle dataverse e richiamare API personalizzate.

Annotazioni

  • Quando si fa riferimento a tabelle di Dataverse nel codice, usare EntitySetName. Ad esempio, per accedere alla account tabella, usare EntitySetName accounts.

CreaRecord

Creare un nuovo record.

Server.Connector.Dataverse.CreateRecord(string entitySetName, string payload)   

Esempio

Server.Connector.Dataverse.CreateRecord("accounts", "{\"name\": \"Contoso Ltd.\", \"telephone1\": \"555-555-0100\", \"websiteurl\": \"https://contoso.com\"}");

Recupera record

Recupera un singolo record in base all'ID.

Server.Connector.Dataverse.RetrieveRecord(string entitySetName, string id)
Server.Connector.Dataverse.RetrieveRecord(string entitySetName, string id, string options)
Server.Connector.Dataverse.RetrieveRecord(string entitySetName, string id, string options, bool skipCache)

Example

Server.Connector.Dataverse.RetrieveRecord("accounts", "00000000-0000-0000-0000-000000000001", "$select=name,telephone1");

RetrieveMultipleRecords

Recupera una raccolta di record.

Server.Connector.Dataverse.RetrieveMultipleRecords(string entitySetName)
Server.Connector.Dataverse.RetrieveMultipleRecords(string entitySetName, string options)
Server.Connector.Dataverse.RetrieveMultipleRecords(string entitySetName, string options, bool skipCache) 

Example

Server.Connector.Dataverse.RetrieveMultipleRecords("accounts", "$select=name,emailaddress1&$top=3");

Aggiorna record

Aggiorna un record esistente in base all'ID.

Server.Connector.Dataverse.UpdateRecord(string entitySetName, string id, string payload)   

Example

Server.Connector.Dataverse.UpdateRecord("accounts", "00000000-0000-0000-0000-000000000001", "{ \"telephone1\": \"555-555-0100\" }");

CancellaRecord

Elimina un record in base all'ID.

Server.Connector.Dataverse.DeleteRecord(string entitySetName, string id) 

Example

Server.Connector.Dataverse.DeleteRecord("accounts", "00000000-0000-0000-0000-000000000001");

InvokeCustomApi

Server.Connector.Dataverse.InvokeCustomApi(string httpMethod, string url, string payload = null) 

Richiamare una funzione associata:

Server.Connector.Dataverse.InvokeCustomApi("get", "accounts(00000000-0000-0000-0000-000000000001)/Microsoft.Dynamics.CRM.new_CustomBoundFunction");

Richiamare un'azione associata:

Server.Connector.Dataverse.InvokeCustomApi("post", "accounts(00000000-0000-0000-0000-000000000001)/Microsoft.Dynamics.CRM.new_CustomBoundAction", "{ \"parameter1\": \"value1\" }");

Richiamare un'azione non associato:

Server.Connector.Dataverse.InvokeCustomApi("post", "new_Action", "{ \"parameter1\": \"value1\" }");

Esempio: risposta

{
    "StatusCode": 204,
    "Body": "",
    "IsSuccessStatusCode": true,
    "ReasonPhrase": "No Content",
    "ServerError": false,
    "ServerErrorMessage": null,
    "Headers": {
        "x-ms-cds-service-request-id": "00001111-aaaa-2222-bbbb-3333cccc4444"
    }
}

Logger

Usare il logger per scrivere messaggi di diagnostica che è possibile visualizzare nell'estensione DevTools.

Esempio:

Server.Logger.Log("Information message");
Server.Logger.Warn("Warning message");
Server.Logger.Error("Error message");

Context

L'oggetto Server.Context fornisce informazioni sulla chiamata alla logica del server corrente. Le proprietà disponibili dipendono dal fatto che la logica del server sia stata richiamata tramite una richiesta HTTP o da un modello Liquid.

Properties

Nome Disponibile per Descrizione
ActivityId HTTP e Liquid Identificatore univoco per la chiamata alla logica del server. Usare questo valore per correlare i log e risolvere i problemi relativi a un'operazione.
Body HTTP Corpo della richiesta HTTP non elaborato.
FunctionName HTTP e Liquid Nome della funzione JavaScript richiamata. Per una chiamata Liquid, questo valore corrisponde al operation parametro del serverlogic tag.
Headers HTTP Intestazioni di richiesta HTTP.
HttpMethod HTTP Metodo di richiesta HTTP, ad esempio GET, PUTPOST, PATCH, o DELETE.
Input Liquid Stringa di input fornita tramite il input parametro del serverlogic tag Liquid. Quando l'input contiene dati strutturati, analizzarlo come JSON prima di usarlo.
QueryParameters HTTP Parametri di stringa di query dalla richiesta HTTP.
ServerLogicName HTTP e Liquid Nome del record della logica del server richiamato.
Url HTTP URL completo della richiesta HTTP.

Accedere al contesto della richiesta HTTP

L'esempio seguente legge il parametro di query quando viene richiamata la id logica del server tramite una richiesta HTTP:

var id = Server.Context.QueryParameters["id"];

È anche possibile accedere ai metadati delle richieste:

function getRequestInformation() {
    return JSON.stringify({
        activityId: Server.Context.ActivityId,
        functionName: Server.Context.FunctionName,
        httpMethod: Server.Context.HttpMethod,
        serverLogicName: Server.Context.ServerLogicName,
        url: Server.Context.Url
    });
}

Contesto di chiamata liquida

Quando la logica del server viene richiamata da Liquid, usare Server.Context.Input per leggere il valore fornito tramite il parametro del input tag.

Ad esempio, il codice Liquid seguente passa l'input JSON:

{% assign inputData = '{"category":"active","maximumResults":5}' %}

{% serverlogic output: result, name: 'customer-summary', operation: 'getSummary', input: inputData %}

L'operazione per la logica del server può analizzare l'input e accedere alle informazioni sulla chiamata Liquid:

function getSummary() {
    var input = JSON.parse(Server.Context.Input || "{}");

    return JSON.stringify({
        category: input.category,
        maximumResults: input.maximumResults,
        activityId: Server.Context.ActivityId,
        functionName: Server.Context.FunctionName,
        serverLogicName: Server.Context.ServerLogicName
    });
}

Passo successivo

Come interagire con le tabelle di Dataverse usando la logica del server

Panoramica della logica del server
Sviluppare la logica del server