Com: Interactuar amb taules del Dataverse mitjançant la lògica del servidor

En aquesta guia, configurareu una pàgina web i una plantilla web personalitzada que utilitzarà la lògica del servidor per llegir, escriure, actualitzar i suprimir registres de la taula de contactes.

Pas 1: Crear una lògica de servidor

  1. Inicieu la sessió al Power Pages.

  2. Seleccioneu lloc + Edita.

  3. Aneu a l'àrea de treball Configura i seleccioneu Lògica del servidor (visualització prèvia).

  4. Seleccioneu +Lògica de servidor nova.

  5. Introduïu el nom de la lògica del servidor. Aquest nom s'utilitza a l'API com a identificador de recursos mentre es construeix l'API lògica del servidor.

    Exemple: dataverse-crud-operations

  6. Seleccioneu +Afegeix funcions per assignar la funció web adequada.

  7. Seleccioneu 3 punts (...) al costat del nom i seleccioneu Edita el codi.

  8. Seleccioneu Obre el Visual Studio Code per crear la lògica personalitzada. Trobareu mètodes i scripts predefinits al fitxer.

  9. Definiu el mètode lògic del servidor per llegir, editar, crear i suprimir els registres de contacte.

    Llegiu: Afegiu l'script a continuació dins del mètode 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: afegeix l'script a continuació al mètode de publicació

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

    Actualització: Afegeix l'script a continuació al mètode put

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

    Suprimeix: afegeix dins del mètode

    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. Deseu el fitxer.

  11. Aquí teniu el codi lògic complet del servidor que es pot enganxar

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

Pas 2: Crea una pàgina web

  1. Inicieu l'estudi de disseny del Power Pages.

  2. A l'espai de treball Pages , seleccioneu + Pàgina.

  3. Al diàleg Afegeix una pàgina , introduïu Lògica del servidor al quadre Nom i seleccioneu Comença des de la disposició en blanc .

  4. Seleccioneu Afegeix.

  5. Seleccioneu l'opció Edita el codi a l'extrem superior dret.

  6. Seleccioneu Obre Visual Studio Code.

  7. Copieu el fragment de codi d'exemple següent i enganxeu-lo entre les <div></div> etiquetes de la secció de pàgina.

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

Pas 3: Configurar els permisos

Crear una funció web

Si actualment no teniu una funció web amb permisos per a la taula a la qual accediu mitjançant la lògica del servidor o necessiteu un context diferent per accedir a les dades, els passos següents us mostren com crear una funció web nova i assignar permisos de taula.

  1. Inicieu l'aplicació Administració del portal.
  2. A la subfinestra esquerra, a la secció Seguretat , seleccioneu Funcions web.
  3. Seleccioneu Crea.
  4. Al quadre Nom , introduïu Usuari lògic del servidor (o qualsevol nom que reflecteixi millor la funció de l'usuari que accedeix a aquesta funcionalitat).
  5. A la llista Lloc web , seleccioneu el registre del lloc web.
  6. Seleccioneu Desa.

Crear permisos de taula

  1. Inicieu l'estudi de disseny del Power Pages.
  2. Seleccioneu l'àrea de treball Seguretat .
  3. A la secció Protegeix , seleccioneu Permisos de taula.
  4. Seleccioneu Permís nou.
  5. Al quadre Nom , introduïu el permís de taula de contactes.
  6. A la llista Nom de la taula, seleccioneu Contacte (contacte).
  7. A la llista Tipus d'accés, seleccioneu Global.
  8. Seleccioneu Privilegis de lectura, escriptura, creació i supressió .
  9. Seleccioneu + Afegeix funcions i seleccioneu la funció web que heu seleccionat o creat anteriorment.
  10. Seleccioneu Desa i amp; Tanca.

Afegir contactes a la funció web

  1. Inicieu l'aplicació Administració del portal.
  2. A la subfinestra esquerra, a la secció Seguretat , seleccioneu Contactes.
  3. Seleccioneu un contacte que vulgueu utilitzar en aquest exemple per a la lògica del servidor.

    Nota

    Aquest contacte és el compte d'usuari utilitzat en aquest exemple per provar la lògica del servidor. Assegureu-vos de seleccionar el contacte correcte al portal.

  4. SeleccioneuFuncions web relacionades>.
  5. Seleccioneu Afegeix una funció web existent.
  6. Seleccioneu la funció d'usuari de lògica del servidor , creada anteriorment.
  7. Seleccioneu Afegeix.
  8. Seleccioneu Desa i amp; Tanca.

Pas 4: Utilitzeu la lògica del servidor per llegir, veure, editar, crear i suprimir

Per provar la funcionalitat de l'API web:

  1. Seleccioneu Visualització prèvia i, a continuació, trieu Escriptori.
  2. Inicieu la sessió al vostre lloc amb el compte d'usuari al qual se li ha assignat la funció d'usuari de lògica del servidor que heu creat anteriorment.
  3. Aneu a la pàgina web de lògica del servidor creada anteriorment.

Informació general de la lògica del servidor
Lògica del servidor d'autor
Objectes del servidor