Search Results for

    Show / Hide Table of Contents

    Hsl.OrgService

    ⚠️ The SOAP Endpoint is deprecated. Use Hsl.WebApi instead wherever possible.

    ⚠️ Hsl.OrgService functionality is in library.orgservice.js which needs to be loaded in addition to library.core.js.

    Download the orgservice documentation pdf

    Samples

    Create

    function createAndOpenAccount() {
        const account = Hsl.entity('account');
        account.set('name', 'My Test Account');
        account.setOptionSetValue('preferredcontactmethodcode', 2); // Email
        Hsl.OrgService.create(account).then(function (res) {
            Hsl.openEntityForm('account', res.Id, undefined, {
                openInNewWindow: true
            });
        }, function (err) {
            Hsl.Dialog.showSoapError(err, 'Error creating account:');
        });
    }
    

    ExecuteService

    function callToCreateRecordService() {
        const dlg = Hsl.Dialog.openBusy({ text: 'Creating Records...' });
        const createCount = 150;
        // Call Service to create 150 records. 
        Hsl.OrgService.executeService({
            serviceName: 'hsl_testservice.CreateStuff',
            method: 'create',
            data: {
                createCount: createCount
            },
            progress(e) {
                dlg.update({ progress: e.progress * 100 / createCount });
            },
        }).then(function (result) {
            dlg.close();
            // The service conditionally skips certains records. 
            // Report to the user that we're done and how many records were skipped. 
            const totalSkipped = result.data.skipped;
            Hsl.Dialog.alert('Completed. Skipped ' + totalSkipped + ' records.');
        }, function (error) {
            // Show the error message. 
            dlg.close();
            Hsl.Dialog.showSoapError(error);
        });
    }
    function callToCustomActionService(context) {
        Hsl.OrgService.executeService({
            serviceName: 'hsl_getErpSystemOrders',
            data: {
                fromDate: '2014-01-01',
                toDate: '2014-05-05',
                recordId: '{E852F7C5-806B-4E20-A758-66AB4096C914}',
            }
        }).then(function (result) {
            // This sample assumes the response is defined in the service as:
            // public class Response 
            // {
            //     public List<OrderInfo> orders { get; set; }
            // }
            // public class OrderInfo 
            // {
            //     public string date { get; set; }
            //     public string totalAmount { get; set; }
            // }
            // Which will result in JSON that looks like the text below. 
            // The text will be parsed automatically as long as responseType is JSON.
            // { "orders": [{ "date": "2014-01-01", "totalAmount": "$124,000" }, 
            //              { "date": "2014-04-12", "totalAmount": "€432,000" }] }
            // Depending on the use-case, it might be better to do formatting client-side instead of server-side
            // but it was left server-side for the simplicity of this example: 
            const orders = result.data.orders;
            const ordersMessage = orders.map(order => {
                return order.date + ': ' + order.totalAmount;
            }).join('\r\n');
            Hsl.Dialog.alert('Orders:\r\n' + ordersMessage);
        }, function (error) {
            Hsl.Dialog.showSoapError(error);
        });
    }
    

    Fetch

    function fetchExample() {
        Hsl.OrgService.fetch('<fetch><entity name="account"></entity></fetch>').then((resp) => {
            const count = resp.Entities.length;
            const names = resp.Entities.map(function (entity) {
                const name = entity.get('name');
                const primaryContactName = entity.getValueName('primarycontactid'); // Returns name of the primary contact.
                const industry = entity.getFormattedValue('industrycode') || 'not specified';
                return Hsl.Str.format('{0} ({1}): {2}', name, industry, primaryContactName || 'None');
            });
            const text = count + ' records:\r\n' + names.join('\r\n');
            Hsl.Dialog.alert(text);
            return null;
        }, Hsl.Dialog.showSoapError);
    }
    function queryEntityWhereExample() {
        // Show a list of accounts that have a credit hold.
        const columnSet = ['accountid', 'name'];
        Hsl.OrgService.queryEntityWhere('account', columnSet, '<filter><condition attribute="creditonhold" operator="eq" value="1" /></filter>').then(resp => {
            if (resp.Entities.length === 0) {
                Hsl.Dialog.alert('No accounts have a credit hold');
            }
            else {
                const names = resp.Entities.map(e => e.get('name'));
                Hsl.Dialog.alert('The following accounts have a credit hold:\r\n' + names.join('\r\n'));
            }
        }, Hsl.Dialog.showSoapError);
    }
    function fetchPaging() {
        Hsl.OrgService.fetch("<fetch count='5'><entity name='account'><attribute name='name' /></entity></fetch>")
            .then(printThenQueryNext)
            .catch(Hsl.Dialog.showSoapError);
        function printThenQueryNext(resp) {
            resp.Entities.forEach(function (c) {
                console.log(c.get('name'));
            });
            if (resp.EntityCollection.MoreRecords) {
                return Hsl.OrgService.fetchNextPage(resp).then(printThenQueryNext);
            }
        }
    }
    

    Metadata

    function showAccountNameAttributeDisplayName() {
        Hsl.Metadata.retrieveEntity('account', {
            entityFilters: Hsl.Metadata.EntityFilters.Entity | Hsl.Metadata.EntityFilters.Attributes,
        }).then(function (res) {
            Hsl.Dialog.alert(res.EntityMetadata.getAttribute('name').DisplayName.getLabel());
        }, Hsl.Dialog.showSoapError);
    }
    function showPicklistOptions() {
        Hsl.Metadata.retrieveAttribute('incident', 'casetypecode', { retrieveAsIfPublished: false }).then(function (resp) {
            const attribute = resp.AttributeMetadata;
            const options = attribute.OptionSet.Options.map(function (o) {
                // getLabel returns the label in the user's language. 
                // Use getLabel(langCode) to get a particular language. 
                // For example, o.Label.getLabel(1033) would return the American English label.
                return Hsl.Str.format('{0}: {1}', o.Value.toString(), o.Label.getLabel());
            });
            return Hsl.Dialog.alert(options.join('\r\n'));
        }, Hsl.Dialog.showSoapError);
    }
    

    OrganizationRequest

    // When executing a built-in CRM request, find the request you are interested in running on MSDN
    // http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.aspx
    // http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.messages.aspx
    // Open up the members listing for the request. 
    // Ex http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.instantiatetemplaterequest_members.aspx
    // Set the value for the non-inherited members based on their data types.
    function hisol_executeWorkflow() {
        const req = Hsl.organizationRequest('ExecuteWorkflow');
        req.setGuid('WorkflowId', '{EB51EB41-2F01-41C4-998B-6AEC5FAD58BA}');
        req.setGuid('EntityId', '{45CCE1DC-A7CC-4FCF-BD2C-41713675FB07}');
        return Hsl.OrgService.execute(req);
    }
    function rollupRecords() {
        const rollup = Hsl.organizationRequest('Rollup');
        rollup.setFetchExpression('Query', `<fetch>
        <entity name="activitypointer">
            <attribute name="activityid" />
        </entity>
    </fetch>`);
        rollup.set('RollupType', 2, 'crm:RollupType');
        rollup.setEntityReference('Target', { Id: '{B7DDB715-7DE1-464A-84D2-F14838D0E250}', LogicalName: 'account' });
        return Hsl.OrgService.execute(rollup)
            .then(resp => resp.get('EntityCollection'));
    }
    function recalculateGoal() {
        // Reference http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.recalculaterequest.aspx
        const req = Hsl.organizationRequest('Recalculate');
        req.setEntityReference('Target', { LogicalName: 'goal', Id: '{EE2637A8-791F-453E-91A9-0E985A2451C8}' });
        return Hsl.OrgService.execute(req);
    }
    function copyCampaignAsTemplate() {
        // http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.copycampaignrequest_members.aspx
        const req = Hsl.organizationRequest('CopyCampaign');
        req.setGuid('BaseCampaign', '{2FE6A271-0FB7-40E5-8CAB-0C5862ED8332}');
        req.setBoolean('SaveAsTemplate', true);
        Hsl.OrgService.execute(req).then(function (response) {
            // Data types for response fields can be found here: 
            // http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.copycampaignresponse_members.aspx
            const copyId = response.results.CampaignCopyId;
            Hsl.openEntityForm('campaign', copyId);
        });
    }
    /** Creates Email using template then opens the form for that email. */
    function createEmailUsingTemplate() {
        const request = Hsl.organizationRequest('InstantiateTemplate');
        request.setGuid('ObjectId', '{599EDCEF-2001-4100-ADC2-6703C72BAB5E}');
        request.setString('ObjectType', 'incident');
        request.setGuid('TemplateId', '{F5246224-4EFD-419D-9045-FACC9C94FE70}');
        const busyDlg = Hsl.Dialog.openBusy({ text: 'Creating Email...' });
        // Instantiate the template
        Hsl.OrgService.execute(request).then(function (instantiateResponse) {
            const resultEntities = instantiateResponse.results.EntityCollection;
            const email = resultEntities.Entities[0];
            email.setEntityReference('regardingobjectid', {
                LogicalName: 'incident',
                Id: '{599EDCEF-2001-4100-ADC2-6703C72BAB5E}',
            });
            return Hsl.OrgService.create(email);
        }).then(function (resp) {
            Hsl.openEntityForm('email', resp.Id);
        }).catch(function (error) {
            Hsl.Dialog.showSoapError(error, 'Error Instantiating Email Template');
        }).then(function () {
            busyDlg.close();
        });
    }
    function retrieveEntity() {
        // Most messages can be done using the simple set messages. 
        // Occasionally, certain messages will require XML to be specified for special types.
        // For example, RetrieveEntityRequest's EntityFilters is an enum type. 
        // The xml should be a b: value node that specifies its type.
        // NOTE: This is primary here to demonstrate setting an enum. To retrieve metadata, use the 
        // Hsl.Metadata.retrieveEntity method.
        const entityFilters = 'Attributes Relationships';
        const req = Hsl.organizationRequest('RetrieveEntity');
        req.setEnum('EntityFilters', entityFilters, 'http://schemas.microsoft.com/xrm/2011/Metadata:EntityFilters');
        req.setString('LogicalName', 'contact');
        req.setGuid('MetadataId', '00000000-0000-0000-0000-000000000000');
        req.setBoolean('RetrieveAsIfPublished', true);
        Hsl.OrgService.execute(req).then(function (response) {
            const entityMeta = response.results.EntityMetadata;
        }, function (error) {
            Hsl.Dialog.showSoapError(error);
        });
    }
    function closeOpportunity(context) {
        // Reference: https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.loseopportunityrequest.aspx
        const oppClose = Hsl.entity('opportunityclose');
        oppClose.setEntityReference('opportunityid', {
            Id: context.data.entity.getId(),
            LogicalName: context.data.entity.getEntityName(),
        });
        oppClose.setString('description', 'Opp Close Test');
        oppClose.setString('subject', 'Opp Close Test');
        const closeReq = Hsl.organizationRequest('LoseOpportunity');
        closeReq.setOptionSetValue('Status', -1);
        closeReq.setEntity('OpportunityClose', oppClose);
        Hsl.OrgService.execute(closeReq).then(function () { alert('Close Opportunity'); }, Hsl.Dialog.showSoapError);
    }
    function associateRecordsManyToMany() {
        const related = [{
                Id: 'F8E235B6-8C51-E511-9502-080027E7856E',
                LogicalName: 'fieldsecurityprofile',
            }];
        const request = Hsl.organizationRequest('Associate');
        request.setEntityReferenceCollection('RelatedEntities', related);
        request.setEntityReference('Target', {
            Id: '27D6BCAF-8C51-E511-9502-080027E7856E',
            LogicalName: 'team',
        });
        request.setRelationship('Relationship', { SchemaName: 'teamprofiles_association' });
        Hsl.OrgService.execute(request).then(() => {
            Hsl.Dialog.alert('Success');
        }, Hsl.Dialog.showSoapError);
    }
    

    Party List

    function basicPartyList() {
        const email = Hsl.entity('email');
        email.setPartyList('to', [
            {
                Id: '75a53f2a-fb81-e411-9405-080027092bcc',
                LogicalName: 'contact',
            }, {
                Id: '5EE6AA3B-398E-48CF-8B45-538807DFD6D7',
                LogicalName: 'contact',
            }
        ]);
        Hsl.OrgService.create(email).then(function (resp) {
            Hsl.Dialog.alert(resp.Id);
        }, Hsl.Dialog.showSoapError);
    }
    function addressUsedExample() {
        const appt = Hsl.entity('appointment');
        const ec = Hsl.entityCollection();
        // Set start to the current time
        appt.set('scheduledstart', new Date());
        // Set to end in 30 minutes.
        const end = new Date(new Date().getTime() + 30 * 60000);
        appt.set('scheduledend', end);
        const record1 = Hsl.entity('activityparty');
        record1.setEntityReference('partyid', {
            Id: '75a53f2a-fb81-e411-9405-080027092bcc',
            LogicalName: 'contact',
        });
        const record2 = Hsl.entity('activityparty');
        record2.set('addressused', 'test@example.com');
        ec.Entities.push(record1, record2);
        appt.setEntityCollection('requiredattendees', ec);
        return Hsl.OrgService.create(appt);
    }
    

    Retrieve

    function getAccountIndustry() {
        Hsl.OrgService.retrieve({
            Id: '{C0D00D8F-DE66-426B-B838-981FAF9E70C7}',
            LogicalName: 'account',
        }, ['industrycode']).then(function (resp) {
            const account = resp.Entity;
            const isPublishing = account.get('industrycode') === 864630001;
        }).catch(Hsl.Dialog.showError);
    }
    function getAccountIndustrySync() {
        // Avoid using synchronous ajax whenever possible but if you absolutely need synchronous ajax, 
        // you can do it like this:
        let industryCode = null;
        Hsl.OrgService.retrieve({
            Id: '{C0D00D8F-DE66-426B-B838-981FAF9E70C7}',
            LogicalName: 'account',
        }, ['industrycode'], {
            async: false,
            success(resp) {
                industryCode = resp.Entity.get('industrycode');
            },
            fail(error) {
                Hsl.Dialog.showSoapError(error);
                throw error;
            },
        });
        alert(industryCode);
    }
    
    In This Article
    Back to top Hitachi Solutions JS Library