Creatio development guide
This documentation is valid for Creatio version 7.14.0. We recommend using the newest version of Creatio documentation.

Working with bpm'online objects over the OData protocol using Http request

Glossary Item Box

The following issues will be considered in this article: 

    To ensure successful compilation of the examples below, the following must be added to the software code:

    Using directives

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Xml;
    using System.Xml.Linq; 
    

     

    Declaration of variables and constants

    // String of address bpm’online OData servise.
    private const string serverUri = "http://<server_name>/<BPMonline application_name>/0/ServiceModel/EntityDataService.svc/";
    private const string authServiceUtri = "http://<server_name>/<BPMonline application_name>/ServiceModel/AuthService.svc/Login";
    
    // Links to XML name spaces.
    private static readonly XNamespace ds = "http://schemas.microsoft.com/ado/2007/08/dataservices";
    private static readonly XNamespace dsmd = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
    private static readonly XNamespace atom = "http://www.w3.org/2005/Atom"; 
    

    Operations of working with objects and object collections

    Receiving the objects collection

    To receive the object collection, the HTTP-method GET is used.

    Records are returned by pages, 40 records per page. If a request is supposed to return more than 40 records, the reception of the next page must be ensured to reach the end of the current page.

    The example below demonstrates the use the $select structure to receive separate object fields (see OData Version 3.0 Core Protocol). The example shows that the request implementation results in the return of the contacts collection with the Id and Name fields.

    The example below also uses Forms authentication. The bpm'online user name and password are transmitted in parameters of the GetOdataCollectionByAuthByHttpExample(string userName, string userPassword) method.

    // Request string
    // GET <BPMonline application address>/0/ServiceModel/EntityDataService.svc/ContactCollection?$select=Id,Name
    
    public static void GetOdataCollectionByAuthByHttpExample(string userName, string userPassword)
    {
        // Creating an authentication request.
        var authRequest = HttpWebRequest.Create(authServiceUtri) as HttpWebRequest;
        authRequest.Method = "POST";
        authRequest.ContentType = "application/json";
        var bpmCookieContainer = new CookieContainer();
        // Including the cookie use into the request.
        authRequest.CookieContainer = bpmCookieContainer;
        // Receiving a stream associated with the authentication request.
        using (var requestStream = authRequest.GetRequestStream())
        {
            // Recording the BPMonline user accounts and additional request parameters into the stream.
            using (var writer = new StreamWriter(requestStream))
            {
                writer.Write(@"{
                                    ""UserName"":""" + userName + @""",
                                    ""UserPassword"":""" + userPassword + @""",
                                    ""SolutionName"":""TSBpm"",
                                    ""TimeZoneOffset"":-120,
                                    ""Language"":""En-us""
                                    }");
            }
        }
        // Receiving an answer from the server. If the authentication is successful, cookies will placed in the
        // bpmCookieContainer object and they may be used for further requests.
        using (var response = (HttpWebResponse)authRequest.GetResponse())
        {
            // Creating a request for data reception from the OData service.
            var dataRequest = HttpWebRequest.Create(serverUri + "ContactCollection?$select=Id, Name")
                                    as HttpWebRequest;
            // The HTTP method GET is used to receive data.
            dataRequest.Method = "GET";
            // Adding pre-received authentication cookie to the data receipt request.
            dataRequest.CookieContainer = bpmCookieContainer;
            // Receiving a response from the server.
            using (var dataResponse = (HttpWebResponse)dataRequest.GetResponse())
            {
                // Uploading the server response to an xml-document for further processing.
                XDocument xmlDoc = XDocument.Load(dataResponse.GetResponseStream());
                // Receiving the collection of contact objects that comply with the request condition.
                var contacts = from entry in xmlDoc.Descendants(atom + "entry")
                               select new
                                   {
                                       Id = new Guid(entry.Element(atom + "content")
                                                          .Element(dsmd + "properties")
                                                          .Element(ds + "Id").Value),
                                       Name = entry.Element(atom + "content")
                                                   .Element(dsmd + "properties")
                                                   .Element(ds + "Name").Value
                                   };
                foreach (var contact in contacts)
                {
                    // Implementing actions with contacts.
                }
            }
        } 
    

     

    NOTE

    If it is necessary to send a request and get a response in the JSON format, use the following key-value pairs in the request header:

    Content-Type = "application/json"

    Accept = "application/json;odata=verbose"

    If the request is required to return more than 40 records at once, this may be implemented using the $top parameter, where the required number of records returned by the request is specified. The example below forms a string of the request to the server to receive the first 60 objects of the contacts collection.

    Example of using the $top parameter

    string requestUri = serverUri + "ContactCollection?$top=60";
    

    Bpm'online supports the use of the $skip parameter, which allows requesting resources from the service by bypassing the set number of records.

    The example below demonstrates the formation of a string of the request to the service to receive the contacts collection starting with the eleventh record.

    Example of using the $skip parameter

    string requestUri = serverUri + "ContactCollection?$skip=10";
    

    The service resources may be received in the sorted form. For this purpose, the $orderby [asc|desc] parameter must be used in a request. The field, by which the results are to be sorted, must be specified in the parameter. In addition, one of the following sorting directions may be specified for this parameter:

    • ascending (asc)
    • descending (desc)

    The ascending sorting (asc) is used by default.

    The example below forms a string of the request to the service to receive the contacts collection sorted by the ascending Name field value.

    Example of using the $orderby parameter for ascending sorting

    string requestUri = serverUri + "ContactCollection?$orderby=Name";
    

    The $top, $skip, $orderby parameters may be used in various combinations to receive a certain fragment of the collection (see OData Version 3.0 Core Protocol).

    Example of using the combined $orderby, $top, $skip parameters

    string requestUri = serverUri + "ContactCollection?$top=4&$skip=1&$orderby=City/Name";
    

    Receiving an object with set features

    The HTTP-method GET is used to receive an object.

    A certain object which meets specific conditions (for example, contact with the set Id or account with a certain name, etc.) may be received by several methods (the examples below use Basic authentication of requests).

    Setting the Id of the sought object as a parameter of the collection

    // Request string:
    // GET <BPMonline application address>/0/ServiceModel/EntityDataService.svc/ContactCollection(guid'00000000-0000-0000-0000-000000000000')
    
    public static void GetOdataObjectByIdExample()
    {
        // Id of the sought object.
        string contactId = "00000000-0000-0000-0000-000000000000";
    
        // Forming a string of the request to the service.
        string requestUri = serverUri + "ContactCollection(guid'" + contactId + "')";
    
        // Creating an object of the request to the service.
        var request = HttpWebRequest.Create(requestUri) as HttpWebRequest;
        request.Method = "GET";
        request.Credentials = new NetworkCredential("BPMUserName", "BPMUserPassword");
        using (var response = request.GetResponse())
        {
            // Receiving a response from the service in the xml format.
            XDocument xmlDoc = XDocument.Load(response.GetResponseStream());
            // Receiving the contact objects collection satsifying the request condition.
            var contacts = from entry in xmlDoc.Descendants(atom + "entry")
                           select new
                               {
                                   Id = new Guid(entry.Element(atom + "content")
                                                     .Element(dsmd + "properties")
                                                     .Element(ds + "Id").Value),
                                   Name = entry.Element(atom + "content")
                                               .Element(dsmd + "properties")
                                               .Element(ds + "Name").Value
                                   // Initiating the object properties required for further use.
                               };
            foreach (var contact in contacts)
            {
                // Implementing actions over the contact.
            }
        }
    } 
    

     

    This method may be used only if an object with the set Id must be received.

    If the sought object parameter is not Id or the sought object is determined by several parameters, the $filter structure must be used to determine the parameters.

    Using the $filter structure to form a complex condition for the object selection

    The $filter structure allows building logic expressions using the sought object selection conditions .

    The $filter expressions may use links to properties and literals, strings, numbers and logical expressions (true, false). The $filter expressions use arithmetical, logical operations, grouping operations, operations with strings, date and time. The full list of operations implemented by the $filter structure is provided in the OData specification

    Below is the example of receiving the object with the set Id, using the $filter structure to set the condition.

    // Request string:
    // GET <BPMonline application address>/0/ServiceModel/EntityDataService.svc/ContactCollection?$filter=Id eq guid'00000000-0000-0000-0000-000000000000'
    
    public static void GetOdataObjectByFilterConditionExample()
    {
        // Id of the sought object.
        string contactId = "00000000-0000-0000-0000-000000000000";
        // Forming a string of the request to the service.
        string requestUri = serverUri + "ContactCollection?$filter = Id eq guid'" + contactId + "'";
        // Creating an object of the request to the service.
        var request = HttpWebRequest.Create(requestUri) as HttpWebRequest;
        request.Method = "GET";
        request.Credentials = new NetworkCredential("BPMUserName", "BPMUserPassword");
        using (var response = request.GetResponse())
        {
            // Receiving a response from the service in the xml format.
            XDocument xmlDoc = XDocument.Load(response.GetResponseStream());
            // Receiving the contact objects collection satisfying the request condition.
            var contacts = from entry in xmlDoc.Descendants(atom + "entry")
                           select new
                           {
                               Id = new Guid(entry.Element(atom + "content")
                                                 .Element(dsmd + "properties")
                                                 .Element(ds + "Id").Value),
                               Name = entry.Element(atom + "content")
                                           .Element(dsmd + "properties")
                                           .Element(ds + "Name").Value
                               // Initiating the object properties required for further use.
                           };
            foreach (var contact in contacts)
            {
               // Implementing actions over the contact.
            }
        }
    } 
    

    Complex conditions for several fields of an object may be created using the $filter structure.

    Below is the example of returning the contact objects collections created by a SomeUserName user after 2012-11-01.

    // Request string:
    // GET <BPMonline applicationn address>/0/ServiceModel/EntityDataService.svc/ContactCollection?$filter=CreatedOn gt datetime'2012-11-01' and CreatedBy/Name eq 'SomeUserName'
    
    public static void GetOdataObjectByFilterDiffConditionExample()
    {
        // Name of the user that created the objects.
        string userName = "BPMUserName";
        // Objects creation date.
        string datetime = "2012-11-01";
        // Forming a string of the request to the service.
        string requestUri = serverUri + "ContactCollection?$filter=CreatedOn gt datetime'" + datetime +
                                        "'and CreatedBy/Name eq '" + userName + "'";
        // Creating an object of the request to the service.
        var request = HttpWebRequest.Create(requestUri) as HttpWebRequest;
        request.Method = "GET";
        request.Credentials = new NetworkCredential(userName, "BPMUserPassword");
        using (var response = request.GetResponse())
        {
            // Receiving a response from the service in the xml format.
            XDocument xmlDoc = XDocument.Load(response.GetResponseStream());
            // Receiving the contact objects collection satisfying the request condition.
            var contacts = from entry in xmlDoc.Descendants(atom + "entry")
                           select new
                           {
                               Id = new Guid(entry.Element(atom + "content")
                                                 .Element(dsmd + "properties")
                                                 .Element(ds + "Id").Value),
                               Name = entry.Element(atom + "content")
                                           .Element(dsmd + "properties")
                                           .Element(ds + "Name").Value
                               // Initiating the object properties required for further use.
                           };
            foreach (var contact in contacts)
            {
                // Implementing actions over the contact.
            }
        }
    } 
    

    More examples of building requests using the $filter structure may be found in the article "Examples of requests for filter selection".

    Creating a new object

    The HTTP-method POST is used to create an object.

    In this case, the request subject must be formed in the Atom/XML or JSON format so that it contains all required object fields. All possible fields of the created object are described in the service metadata .

    NOTE

    If it is necessary to send a request and get a response in the JSON format, use the following key-value pairs in the request header:

    Content-Type = "application/json"

    Accept = "application/json;odata=verbose"

    Below is the example of creating a new contact. The example uses Basic authentication of the request .

    // Request string:
    // POST <BPMonline application address>/0/ServiceModel/EntityDataService.svc/ContactCollection/
    
    public static void CreateBpmEntityByOdataHttpExample()
    {
        // Creating a xml message containing data on the created object.
        var content = new XElement(dsmd + "properties",
                      new XElement(ds + "Name", "Jhon Gilts"),
                      new XElement(ds + "Dear", "Jhon"));
        var entry = new XElement(atom + "entry",
                    new XElement(atom + "content",
                    new XAttribute("type", "application/xml"), content));
        Console.WriteLine(entry.ToString());
        // Creating a request to the service which will add a new object to the contacts collection.
        var request = (HttpWebRequest)HttpWebRequest.Create(serverUri + "ContactCollection/");
        request.Credentials = new NetworkCredential("BPMUserName", "BPMUserPassword");
        request.Method = "POST";
        request.Accept = "application/atom+xml";
        request.ContentType = "application/atom+xml;type=entry";
        // Recording the xml message to the request stream.
        using (var writer = XmlWriter.Create(request.GetRequestStream()))
        {
            entry.WriteTo(writer);
        }
        // Receiving a response from the service regarding the operation implementation result.
        using (WebResponse response = request.GetResponse())
        {
            if (((HttpWebResponse)response).StatusCode == HttpStatusCode.Created)
            {
                // Processing the operation implementation result.
            }
        }
    } 
    

    Modifying an existing object

    The PUT (or MERGE in the latest OData versions) HTTP-method is used to modify a record.

    New values of the fields to be modified are transmitted in the request subject. The collection whose object is modified must be specified in the request string and the modified object Id must be specified as the collection parameter.

    Below is the example of modifying the name of the contact with the Id 00000000-0000-0000-0000- 000000000000 from the ContactCollection contacts collection. The example uses the Basic authentication of requests.

    NOTE

    If it is necessary to send a request and get a response in the JSON format, use the following key-value pairs in the request header:

    Content-Type = "application/json"

    Accept = "application/json;odata=verbose"

     

    // Request string:
    // PUT <BPMonline application address>/0/ServiceModel/EntityDataService.svc/ContactCollection(guid'00000000-0000-0000-0000-000000000000')
    // or
    // MERGE <Адрес приложения BPMonline>/0/ServiceModel/EntityDataService.svc/ContactCollection(guid'00000000-0000-0000-0000-000000000000')
    public static void UpdateExistingBpmEnyityByOdataHttpExample()
    {
        // Id of the object record to be modified.
        string contactId = "00000000-0000-0000-0000-000000000000";
        // Creating an xml message containing data on the modified object.
        var content = new XElement(dsmd + "properties",
                new XElement(ds + "Name", "New name")
        );
        var entry = new XElement(atom + "entry",
                new XElement(atom + "content",
                        new XAttribute("type", "application/xml"),
                        content)
                );
        // Creating a request to the service which will modify the object data.
        var request = (HttpWebRequest)HttpWebRequest.Create(serverUri
                + "ContactCollection(guid'" + contactId + "')");
        request.Credentials = new NetworkCredential("BPMUserName", "BPMUserPassword");
        // or request.Method = "MERGE";
        request.Method = "PUT";
        request.Accept = "application/atom+xml";
        request.ContentType = "application/atom+xml;type=entry";
        // Recording the xml message to the request stream.
        using (var writer = XmlWriter.Create(request.GetRequestStream()))
        {
            entry.WriteTo(writer);
        }
        // Receiving a response from the service regarding the operation implementation result.
        using (WebResponse response = request.GetResponse())
        {
            // Processing the operation implementation result.
        }
    } 
    

    Deleting an object

    The HTTP-method DELETE is used to delete a record .

    The collection whose object is deleted must be specified in the request string and the deleted object Id must be specified as the collection parameter .

    Below is the example of deleting the contact with the Id 00000000-0000-0000-0000-000000000000 from the ContactCollection contacts collection. The example uses the Basic authentication of requests .

    NOTE

    If it is necessary to send a request and get a response in the JSON format, use the following key-value pairs in the request header:

    Content-Type = "application/json"

    Accept = "application/json;odata=verbose"

     

    // Request string:
    // DELETE <BPMonline application address>/0/ServiceModel/EntityDataService.svc/ContactCollection(guid'00000000-0000-0000-0000-000000000000')
    
    public static void DeleteBpmEntityByOdataHttpExample()
    {
        // Id of the object record to be deleted.
        string contactId = "00000000-0000-0000-0000-000000000000";
        // Creating a request to the service which will delete the data.
        var request = (HttpWebRequest)HttpWebRequest.Create(serverUri
                + "ContactCollection(guid'" + contactId + "')");
        request.Credentials = new NetworkCredential("BPMUserName", "BPMUserPassword");
        request.Method = "DELETE";
        // Receiving a response from the service regarding the operation implementation result.
        using (WebResponse response = request.GetResponse())
        {
            // Processing the operation implementation result.
        }
    } 
    

    Functions of work with strings

    BPMonline supports the following functions of work with the OData protocol strings which may be used for building expressions of the $filter structure.

    Function Example of the request string Request implementation result
    bool substringof(string po, string p) <Service address >/ContactCollection?$filter=substringof('Smith', Name) Collection of contacts whose name contains the 'Smith' sub-string.
    string toupper(string p0) <Service address > /ContactCollection?$filter=toupper(Name) eq 'TEST USER' Collection of contacts whose name is equal to 'TEST USER' in the upper case.
    bool endswith(string p0, string p1) <Service address > /ContactCollection?$filter=endswith(Name, 'User') Collection of contacts whose name ends with the 'User' sub-string.
    int length(string p0) <Service address > /ContactCollection?$filter=length(Name) gt 10 Collection of contacts whose name length exceeds 10 characters.
    string trim(string p0) <Service address > / ContactCollection?$filter=trim(Name) eq 'Test User' Collection of contacts whose name is equal to 'Test User' after removing the initial and end spaces.

    The full list of functions for working with the OData protocol strings is provided in the official OData specification.

    Functions of working with date and time

    BPMonline supports the following functions of work with the OData protocol dates which may be used for building expressions of the $filter structure.

    Function Example of the request string Request implementation result
    int year(DateTime p0) <Service address >/ContactCollection?$filter=year(BirthDate) ge 1950 and year(BirthDate) le 1990 Collection of contacts whose year of birth is within the range of the year 1950 to 1990, inclusive.
    int month(DateTime p0) <Service address >/ContactCollection?$filter=month(BirthDate) eq 5 Collection of contacts born in May.
    int day(DateTime p0) <Service address >/ContactCollection?$filter=day(BirthDate) eq 15 Collection of contacts born on the 15th day.

    The full list of functions for working with the OData protocol dates is provided in the official OData specification.

    © bpm'online 2002-2019.

    Did you find this information useful?

    How can we improve it?