Procedura: Interagire con le tabelle di Dataverse usando la logica del server

In questa guida si configurerà una pagina Web e un modello Web personalizzato che userà la logica del server per leggere, scrivere, aggiornare ed eliminare record dalla tabella dei contatti.

Passaggio 1: Creare una logica del server

  1. Accedere a Power Pages.

  2. Selezionare sito e modifica.

  3. Passare all'area di lavoro Configura, quindi selezionare Logica del server (anteprima).

  4. Selezionare +Nuova logica del server.

  5. Immettere il nome per la logica del server. Questo nome viene usato nell'API come identificatore di risorsa durante la costruzione dell'API per la logica del server.

    Esempio: _dataverse-crud-operations_

  6. Selezionare +Aggiungi ruoli per assegnare il ruolo Web appropriato.

  7. Selezionare 3 puntini (...) accanto al nome e selezionare Modifica codice.

  8. Selezionare Apri Visual Studio Code per creare la logica personalizzata. Nel file sono disponibili metodi e script predefiniti.

  9. Definire il metodo di logica del server per leggere, modificare, creare ed eliminare i record dei contatti.

    Lettura: Aggiungere lo script seguente all'interno del metodo get

    const entitySetName = Server.Context.QueryParameters["entitySetName"];
    if (!Server.Context.QueryParameters["id"]) {
        return Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName);
    } else {
        const id = Server.Context.QueryParameters["id"]; // Context reference
        return Server.Connector.Dataverse.RetrieveRecord(entitySetName, id);
    }
    

    Crea: Aggiungi lo script seguente nel metodo POST

    const data = Server.Context.Body;
    const entitySetName = Server.Context.QueryParameters["entitySetName"];
    return Server.Connector.Dataverse.CreateRecord(entitySetName, data);
    

    Aggiornamento: aggiungere lo script seguente nel metodo put

    const id = Server.Context.QueryParameters["id"];
    const data = Server.Context.Body;
    return Server.Connector.Dataverse.UpdateRecord("accounts", id, data);
    

    Elimina: Aggiungi all'interno del metodo del

    const id = Server.Context.QueryParameters["id"];
    const entitySetName = Server.Context.QueryParameters["entitySetName"];
    Server.Logger.Log("Entity Set name:" + entitySetName);
    return Server.Connector.Dataverse.DeleteRecord(entitySetName, id);
    
  10. Salva il file.

  11. Ecco il codice completo della logica del server che può essere incollato

    function get() {
     try {
         Server.Logger.Log("GET called"); // Logger reference
         const entitySetName = Server.Context.QueryParameters["entitySetName"];
         const additionParameters = Server.Context.QueryParameters['additionalParameters'];
         if (!Server.Context.QueryParameters["id"]) {
             const response = Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName,additionParameters);
             return response;
         }
         else{            
             const id = Server.Context.QueryParameters["id"]; // Context reference
             const response = Server.Connector.Dataverse.RetrieveRecord(entitySetName, id,additionParameters);
             return response;
         }        
     } catch (err) {
         Server.Logger.Error("GET failed: " + err.message);
         return JSON.stringify({ status: "error", method: "GET", message: err.message });
     }
     }
     function post() {
     try {
         Server.Logger.Log("POST called");
         const data = Server.Context.Body;
         const entitySetName = Server.Context.QueryParameters["entitySetName"];
          return Server.Connector.Dataverse.CreateRecord(entitySetName, data);
      } catch (err) {
         Server.Logger.Error("POST failed: " + err.message);
         return JSON.stringify({ status: "error", method: "POST", message: err.message });
     }
     } 
     function put() {
     try {
         Server.Logger.Log("PUT called");
         const id = Server.Context.QueryParameters["id"];
         const data = Server.Context.Body;
         const entitySetName = Server.Context.QueryParameters["entitySetName"];
         return Server.Connector.Dataverse.UpdateRecord(entitySetName, id, data);
      } catch (err) {
         Server.Logger.Error("PUT failed: " + err.message);
         return JSON.stringify({ status: "error", method: "PUT", message: err.message });
     }
     }   
     function del() {
     try {
         // "delete" keyword should not be used in script file.
         Server.Logger.Log("DEL called");
         const id = Server.Context.QueryParameters["id"];
           const entitySetName = Server.Context.QueryParameters["entitySetName"];
         return Server.Connector.Dataverse.DeleteRecord(entitySetName, id);
      } catch (err) {
         Server.Logger.Error("Deletion failed: " + err.message);
         return JSON.stringify({ status: "error", method: "DEL", message: err.message });
     }
     }
    

Passaggio 2: Creare una pagina Web

  1. Avviare lo studio di progettazione di Power Pages.

  2. Nell'area di lavoro Pagine selezionare + Pagina.

  3. Nella finestra di dialogo Aggiungi una pagina immettere Logica server nella casella Nome e selezionare Avvia dal layout vuoto .

  4. Seleziona Aggiungi.

  5. Selezionare l'opzione Modifica codice nell'angolo superiore destro.

  6. Selezionare Apri Visual Studio Code.

  7. Copiare il frammento di codice di esempio seguente e incollarlo tra i <div></div> tag della sezione della pagina.

    <style>
    #processingMsg {
        padding: 6px 12px; background: #eee; border-radius: 4px;
        position: fixed; top: 10px; left: 50%; transform: translateX(-50%);
        display: none; z-index: 9999; text-align: center; font-weight: bold;
    }
    table { border-collapse: collapse; width: 100%; margin-top: 10px; font-family: Arial, sans-serif; }
    th, td { border: 1px solid #ccc; padding: 6px; text-align: left; }
    button { cursor: pointer; border: 1px solid #aaa; padding: 4px 8px; border-radius: 4px; background: #fff; font-size: 14px; margin-right: 2px; }
    button.add { color: green; }
    button.save { color: green; }
    button.cancel { color: orange; }
    button.delete { color: red; }
    input { width: 95%; box-sizing: border-box; }
    td.actions { white-space: nowrap; }
    </style>
    
    <div id="processingMsg">Processing...</div>
    <div id="dataTable"></div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(function() {
        // --- safeAjax wrapper ---
        (function(webapi, $) {
            function safeAjax(ajaxOptions) {
                var dfd = $.Deferred();
                shell.getTokenDeferred().done(function(token) {
                    ajaxOptions.headers = ajaxOptions.headers || {};
                    ajaxOptions.headers["__RequestVerificationToken"] = token;
                    $.ajax(ajaxOptions)
                        .done((data, ts, jq) => validateLoginSession(data, ts, jq, dfd.resolve))
                        .fail(dfd.reject);
                }).fail(() => dfd.rejectWith(this, arguments));
                return dfd.promise();
            }
            webapi.safeAjax = safeAjax;
        })(window.webapi = window.webapi || {}, jQuery);
    
        // --- notification banner ---
        const notify = (function() {
            const $m = $('#processingMsg'); let s = 0, t;
            return {
                show: (msg = 'Processing...') => { $m.text(msg); if (!s) clearTimeout(t), $m.show(); s++; },
                hide: () => { s = Math.max(0, s - 1); if (!s) clearTimeout(t), t = setTimeout(() => $m.hide(), 300); }
            };
        })();
    
        function ajaxCall(msg, opts) {
            notify.show(msg);
            return webapi.safeAjax(opts)
                .fail(r => alert(r.responseJSON?.error?.message || 'Server logic not available'))
                .always(notify.hide);
        }
    
        // --- Table config ---
        const cols = [
            { name: 'firstname', label: 'First Name' },
            { name: 'lastname', label: 'Last Name' },
            { name: 'emailaddress1', label: 'Email' },
            { name: 'telephone1', label: 'Telephone' }
        ];
        let data = [];
    
        function render() {
            const html = `<table>
                <thead>
                    <tr>
                        ${cols.map(c => `<th>${c.label}</th>`).join('')}
                        <th>Actions <button class="add">➕</button></th>
                    </tr>
                </thead>
                <tbody>
                    ${data.map(r => `<tr data-id="${r.id}" data-name="${r.fullname}">
                        ${cols.map(c => `<td data-attribute="${c.name}" data-value="${r[c.name] || ''}">${r[c.name] || ''}</td>`).join('')}
                        <td class="actions">
                            <button class="delete">🗑️</button>
                        </td>
                    </tr>`).join('')}
                </tbody>
            </table>`;
            $('#dataTable').html(html);
        }
    
        function addRecord(r) { data.unshift(r); render(); }
        function removeRecord(id) { data = data.filter(r => r.id !== id); render(); }
        function updateRecord(id, attr, val) { const r = data.find(r => r.id === id); if (r) { r[attr] = val; render(); } }
    
        // --- Events ---
        $('#dataTable').on('dblclick', 'tr', function() {
            const $tr = $(this);
            if ($tr.hasClass('editing')) return; // prevent double edit
            $tr.addClass('editing');
            $tr.data('original', $tr.find('td[data-attribute]').map(function() { return $(this).text(); }).get());
            $tr.find('td[data-attribute]').each(function() {
                const $td = $(this);
                const oldVal = $td.text();
                $td.html(`<input type="text" value="${oldVal}" data-attr="${$td.data('attribute')}" />`);
            });
            const $actions = $tr.find('td.actions');
            $actions.append('<button class="save">✅</button><button class="cancel">❌</button>');
        });
    
        $('#dataTable').on('click', '.save', function() {
            const $tr = $(this).closest('tr');
            const id = $tr.data('id');
            const updates = {};
            $tr.find('input').each(function() {
                updates[$(this).data('attr')] = $(this).val();
            });
            ajaxCall('Updating...', {
                type: 'PUT',
                url: `/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&id=${id}`,
                contentType: 'application/json',
                data: JSON.stringify(updates),
                success: () => { Object.assign(data.find(r => r.id === id), updates); render(); }
            });
        });
    
        $('#dataTable').on('click', '.cancel', function() {
            const $tr = $(this).closest('tr');
            const original = $tr.data('original');
            $tr.find('td[data-attribute]').each(function(i) {
                $(this).text(original[i]);
            });
            $tr.removeClass('editing');
            $tr.find('button.save, button.cancel').remove();
        });
    
        $('#dataTable').on('click', '.delete', function() {
            const $tr = $(this).closest('tr');
            if (confirm('Delete "' + $tr.data('name') + '"?')) {
                ajaxCall('Deleting...', {
                    type: 'DELETE',
                    url: `/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&id=${$tr.data('id')}`,
                    contentType: 'application/json',
                    success: () => removeRecord($tr.data('id'))
                });
            }
        });
    
        $('#dataTable').on('click', '.add', function() {
            const r = { firstname: 'Alton', lastname: 'Stott' + Math.floor(Math.random() * 900 + 100), emailaddress1: 'Alton.Stott@contoso.com', telephone1: '555-123-4567' };
            ajaxCall('Adding...', {
                type: 'POST',
                url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts',
                contentType: 'application/json',
                data: JSON.stringify(r),
                success: (res, s, xhr) => { r.id = xhr.getResponseHeader('entityid'); r.fullname = r.firstname + ' ' + r.lastname; addRecord(r); }
            });
        });
    
        ajaxCall('Loading...', {
            type: 'GET',
            url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&additionalParameters=$select=fullname,firstname,lastname,emailaddress1,telephone1',
            contentType: 'application/json'
        }).done(res => {
            try {
                const p = JSON.parse(res.data); const b = JSON.parse(p.Body);
                data = (b.value || []).map(r => ({ ...r, id: r.contactid, fullname: r.fullname }));
                render();
            } catch (e) { console.error(e); }
        });
    });
    </script>
    

Passaggio 3: Configurare le autorizzazioni

Creare un ruolo Web

Se attualmente non si dispone di un ruolo Web con autorizzazioni per la tabella a cui si accede tramite la logica del server o si richiede un contesto diverso per l'accesso ai dati, i passaggi seguenti illustrano come creare un nuovo ruolo Web e assegnare autorizzazioni di tabella.

  1. Avvia l'app di Gestione del Portale.
  2. Nel riquadro sinistro selezionare Ruoli Web nella sezione Sicurezza.
  3. Selezionare Nuovo.
  4. Nella casella Nome immettere Utente logica server (o qualsiasi nome che rifletta meglio il ruolo dell'utente che accede a questa funzionalità).
  5. Nell'elenco Sito Web selezionare il record relativo al sito web.
  6. Seleziona Salva.

Creazione delle autorizzazioni di tabella

  1. Avviare lo studio di progettazione di Power Pages.
  2. Selezionare l'area di lavoro Sicurezza .
  3. Nella sezione Proteggi selezionare Autorizzazioni tabella.
  4. Selezionare Nuova autorizzazione.
  5. Nella casella Nome immettere Contact Table Permission.
  6. Nell'elenco Nome tabella, selezionare Contatto (contatto).
  7. Nell'elenco Tipo di accesso selezionare Globale.
  8. Selezionare Lettura, Scrittura, Crea ed Elimina privilegi.
  9. Selezionare + Aggiungi ruoli e selezionare il ruolo Web selezionato o creato in precedenza.
  10. Selezionare Salva e chiudi.

Aggiungere contatti al ruolo web

  1. Avvia L'app di Gestione del Portale.
  2. Nella sezione Sicurezza del riquadro sinistro selezionare Contatti.
  3. Selezionare un contatto da usare in questo esempio per la logica del server.

    Annotazioni

    Questo contatto è l'account utente usato in questo esempio per testare la logica del server. Assicurarsi di selezionare il contatto corretto nel portale.

  4. SelezionareRuoli Web>.
  5. Selezionare Aggiungi ruolo Web esistente.
  6. Selezionare il ruolo utente della logica del server creato in precedenza.
  7. Seleziona Aggiungi.
  8. Selezionare Salva e chiudi.

Passaggio 4: Usare la logica del server per leggere, visualizzare, modificare, creare ed eliminare

Per testare la funzionalità dell'API Web:

  1. Selezionare Anteprima e quindi desktop.
  2. Accedere al sito con l'account utente a cui è stato assegnato il ruolo utente della logica del server creato in precedenza.
  3. Passare alla pagina Web Logica server creata in precedenza.

Panoramica della logica del server
Crea la logica del server
Oggetti server