PATCH call to Creatio using oData3

Hello, 

 

Would anyone have an example of how they are sending PATCH requests to Creatio?

 

Apparently this does not work, I get the error "{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}"

 

public static void UpdateThingInCreatio(string section, Guid object, Guid idofyetanotherobject, string text1, string text2)
        {
            string data = " somedata";
 
            string requestUri = serverUri + "ActivityCollection(guid'" + objectUID + "')";
            Encoding encoding = Encoding.Default;
            var request = WebRequest.Create(requestUri) as HttpWebRequest;
            request.Method = "PATCH";
            request.ContentType = "application/json; charset=utf-8";
            request.Credentials = new NetworkCredential(username, password);
            byte[] buffer = encoding.GetBytes(data);
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(buffer, 0, buffer.Length);
            dataStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string result = "";
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default))
            {
                result = reader.ReadToEnd();
            }
            MessageBox.Show(dataStream.ToString());

Have looked here: https://documenter.getpostman.com/view/10204500/SztHX5Qb?version=latest#78ea2d20-a8a5-4293-8aa5-0fa694d14d33

 

here:https://community.creatio.com/taxonomy/term/5162

 

and here: https://academy.creatio.com/documents/technic-sdk/7-16/integrations-and-external-api

 

with no luck.

 

Any suggestions or code snipit's are welcome!

Like 0

Like

2 comments

Solved it doing something along the lines of this:



 

using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(//Auth here);
 
            using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri))
                {
                    request.Headers.TryAddWithoutValidation("Accept", "application/json; odata=verbose");
                    request.Headers.TryAddWithoutValidation("ForceUseSession", "true");
                    request.Headers.TryAddWithoutValidation("BPMCSRF", "value");                    
                    request.Content = new StringContent("data");
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=verbose");
 
                    var response = await httpClient.SendAsync(request);
                }
            }

If there are any other examples the community would like to share please do here!

Dear Philip,

 

Please find the example of the code below:

 

ExternalRequest.cs

using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
 
namespace ThirdPartyIntegration
{
    class ExternalRequest
    {
        #region Fields: Private
 
        private readonly string appUrl = "http://localhost:3030/";
        private readonly string authServiceUrl = "ServiceModel/AuthService.svc/Login";
        private readonly string OData3ServiceUrl = "0/ServiceModel/EntityDataService.svc/";
 
        private CookieContainer authCookie = new CookieContainer();
 
        #endregion
 
        #region Methods: Private
 
        private HttpWebRequest CreateRequest(string url, string methodType, string requestData = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json;";
            request.Method = methodType;
            request.Accept = "application/json;";
            //request.KeepAlive = true;
            if (!string.IsNullOrEmpty(requestData))
            {
                using (var requestStream = request.GetRequestStream())
                {
                    using (var writer = new StreamWriter(requestStream))
                    {
                        writer.Write(requestData);
                    }
                }
            }
            return request;
        }
 
        // Method realizes protection from CSRF attacks: copies cookie, which contents CSRF-token 
        // and pass it to the header of the next request.
        private void AddCsrfToken(HttpWebRequest request)
        {
            var cookie = request.CookieContainer.GetCookies(new Uri(appUrl))["BPMCSRF"];
            if (cookie != null)
            {
                request.Headers.Add("BPMCSRF", cookie.Value);
            }
        }
 
        private string GenerateRequestData(IDictionary<string, string> columnValuesPairs)
        {
            List<string> data = new List<string>();
            foreach (var pairs in columnValuesPairs)
            {
                data.Add($"\"{pairs.Key}\": \"{pairs.Value}\"");
            }
 
            var massData = data.ToArray();
            return "{ " + string.Join(", ", massData) + " }";
        }
 
        #endregion
 
        #region Methods: Public
 
        public void TryLogin(string userName, string userPassword)
        {
            var authData = "{ " + $"\"UserName\": \"{userName}\", \"UserPassword\": \"{userPassword}\"" + " }";
            var request = CreateRequest(appUrl + authServiceUrl, "POST", authData);
            request.CookieContainer = authCookie;
            // Upon successful authentication, we save authentication cookies for
            // further use in requests to Creatio. In case of failure
            // authentication application console displays a message about the reason
            // of the mistake.
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var responseMessage = reader.ReadToEnd();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine(responseMessage);
                        if (responseMessage.Contains("\"Code\":1"))
                        {
                            throw new UnauthorizedAccessException($"Unauthorized {userName} for {appUrl}");
                        }
 
                        string authName = ".ASPXAUTH";
                        string authCookieValue = response.Cookies[authName].Value;
                        authCookie.Add(new Uri(appUrl), new Cookie(authName, authCookieValue));
                        Console.WriteLine(responseMessage);
                    }
                    else
                    {
                        Console.WriteLine(response.StatusCode + responseMessage);
                    }
                }
            }
        }
 
        public void PatchRequestCreatio(string objectName, Guid objectId, IDictionary<string, string> columnValuesPairs)
        {
            string requestData = GenerateRequestData(columnValuesPairs);
            string finalUrl = appUrl + OData3ServiceUrl + objectName + "Collection(guid'" + objectId + "')";
            var request = CreateRequest(finalUrl, "PATCH", requestData);
 
            request.ContentType += " odata=verbose";
            request.Accept += " odata=verbose";
            request.Headers.Add("ForceUseSession", "true");
 
            request.CookieContainer = authCookie;
            AddCsrfToken(request);
 
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var responseMessage = reader.ReadToEnd();
                }
 
            }
 
        }
 
        #endregion
    }
}

 

 

Program.cs

using System;
using System.Collections.Generic;
 
namespace ThirdPartyIntegration
{
    class Program
    {
        static void Main(string[] args)
        {
            ExternalRequest request = new ExternalRequest();
            request.TryLogin("UserName", "UserPassword");
 
            string @object = "Account";
            Guid objectId = new Guid("405947D0-2FFB-4DED-8675-0475F19F5A81");
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            keyValuePairs.Add("Fax", "Test");
            keyValuePairs.Add("Code", "111");
 
            request.PatchRequestCreatio(@object, objectId, keyValuePairs);
        }
    }
}

 

Best regards,

Norton



 

Show all comments