I have the following script task in a bpm.
This is responsible for taking the results of this api and inserting the records into a Creatio object.

Script task:

 var baseUrl = "https://angelbaraldo.creatio.com";
    var authUrl = baseUrl + "/ServiceModel/AuthService.svc/Login";
    var apiUrl = baseUrl + "/0/rest/CustomStockService/GetNoConciliadosData";
    var username = "MyUser";
    var password = "MyPassword";
 
    // Cuerpo de autenticación
    var authBody = new
    {
        UserName = username,
        UserPassword = password
    };
 
    var authBodyJson = Newtonsoft.Json.JsonConvert.SerializeObject(authBody);
 
    // Solicitud de autenticación
    var authRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(authUrl);
    authRequest.Method = "POST";
    authRequest.ContentType = "application/json; charset=utf-8";
 
    using (var streamWriter = new System.IO.StreamWriter(authRequest.GetRequestStream()))
    {
        streamWriter.Write(authBodyJson);
    }
 
    string authCookies = null;
    string bpmcsrf = null;
 
    // Obtener la respuesta de autenticación
    using (var authResponse = (System.Net.HttpWebResponse)authRequest.GetResponse())
    {
        authCookies = authResponse.Headers["Set-Cookie"];
 
        // Buscar el token BPMCSRF en las cookies
        var cookies = authResponse.Headers.GetValues("Set-Cookie");
        if (cookies != null)
        {
            foreach (var cookie in cookies)
            {
                if (cookie.Contains("BPMCSRF"))
                {
                    bpmcsrf = cookie.Split('=')[1].Split(';')[0];
                }
            }
        }
 
        if (string.IsNullOrEmpty(authCookies) || string.IsNullOrEmpty(bpmcsrf))
        {
            throw new Exception("Autenticación fallida: no se obtuvieron cookies o token BPMCSRF.");
        }
    }
 
    // Solicitud autenticada a la API
    var apiRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(apiUrl);
    apiRequest.Method = "GET";
    apiRequest.ContentType = "application/json";
    apiRequest.Headers["ForceUseSession"] = "true";
    apiRequest.Headers["Cookie"] = authCookies;
    apiRequest.Headers["BPMCSRF"] = bpmcsrf;
 
    // Obtener respuesta de la API
    string apiResponseContent;
    using (var apiResponse = (System.Net.HttpWebResponse)apiRequest.GetResponse())
    {
        using (var streamReader = new System.IO.StreamReader(apiResponse.GetResponseStream()))
        {
            apiResponseContent = streamReader.ReadToEnd();
        }
    }
 
    // Parsear los datos de la API
    var jsonRecords = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, object>>>(apiResponseContent);
    // Procesar los registros (como en tu código original)
    var cantidadInsertados = 0;
 
    foreach (var record in jsonRecords)
    {
        var tipo = record.ContainsKey("Tipo") ? record["Tipo"]?.ToString() : null;
        var letter = record.ContainsKey("Letter") ? record["Letter"]?.ToString() : null;
        var cardCode = record.ContainsKey("CardCode") ? record["CardCode"]?.ToString() : null;
        var nroComprobante = record.ContainsKey("Nro Comprobante") ? record["Nro Comprobante"]?.ToString() : null;
        var nroOv = record.ContainsKey("Nro OV") ? record["Nro OV"]?.ToString() : null;
        var pymentGroup = record.ContainsKey("PymntGroup") ? record["PymntGroup"]?.ToString() : null;
        var docDate = record.ContainsKey("DocDate") ? record["DocDate"]?.ToString() : null;
        var vencimiento = record.ContainsKey("Vencimiento") ? record["Vencimiento"]?.ToString() : null;
        var docCur = record.ContainsKey("DocCur") ? record["DocCur"]?.ToString() : null;
        var docRate = record.ContainsKey("DocRate") ? record["DocRate"] : null;
        var debe = record.ContainsKey("Debe") ? record["Debe"] : null;
        var haber = record.ContainsKey("Haber") ? record["Haber"] : null;
        var debeUsd = record.ContainsKey("Debe USD") ? record["Debe USD"] : null;
        var haberUsd = record.ContainsKey("Haber USD") ? record["Haber USD"] : null;
 
        // Verificar si el registro ya existe
        var esq = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "AgbCuentaCteSocioNegocios");
        var idColumn = esq.AddColumn("Id");
        esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "AgbCuemtaCteNumeroComprobante", nroComprobante));
        var entityCollection = esq.GetEntityCollection(UserConnection);
 
        // Consultar la cuenta relacionada
        var esq2 = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "Account");
        var accountIdColumn = esq2.AddColumn("Id");
        esq2.Filters.Add(esq2.CreateFilterWithParameters(FilterComparisonType.Equal, "AgbCodigoSocioDeNegocios", cardCode));
        var accountCollection = esq2.GetEntityCollection(UserConnection);
 
        Guid? accountId = accountCollection.Count == 1 ? accountCollection[0].GetTypedColumnValue<Guid>(accountIdColumn.Name) : (Guid?)null;
 
        // Insertar el registro si no existe
        if (entityCollection.Count == 0 && !string.IsNullOrEmpty(nroComprobante))
        {
            var newEntity = UserConnection.EntitySchemaManager.GetInstanceByName("AgbCuentaCteSocioNegocios").CreateEntity(UserConnection);
 
            newEntity.SetDefColumnValues();
 
            newEntity.SetColumnValue("AgbCuemtaCteNumeroComprobante", nroComprobante);
            newEntity.SetColumnValue("AgbCuentaCteCodigoSn", cardCode);
            newEntity.SetColumnValue("AgbCuentaCteCondicionPago", pymentGroup);
            newEntity.SetColumnValue("AgbCuentaCteCuentas", accountId);
            newEntity.SetColumnValue("AgbCuentaCteDebe", debe);
            newEntity.SetColumnValue("AgbCuentaCteDebeUsd", debeUsd);
            newEntity.SetColumnValue("AgbCuentaCteFechaDocumento", docDate);
            newEntity.SetColumnValue("AgbCuentaCteFechaVencimiento", vencimiento);
            newEntity.SetColumnValue("AgbCuentaCteHaber", haber);
            newEntity.SetColumnValue("AgbCuentaCteHaberUsd", haberUsd);
            newEntity.SetColumnValue("AgbCuentaCteLetra", letter);
            newEntity.SetColumnValue("AgbCuentaCteMoneda", docCur);
            newEntity.SetColumnValue("AgbCuentaCteNumeroOv", nroOv);
            newEntity.SetColumnValue("AgbCuentaCteTipoCambio", docRate);
            newEntity.SetColumnValue("AgbCuentaCteTipoDocumento", tipo);
 
            newEntity.Save();
 
            // Incrementar el contador de registros insertados
            cantidadInsertados++;
        }
    }
 
    // Establecer el valor de registros insertados en la variable del proceso
    Set<int>("CantidadInsertados", cantidadInsertados);
 
    return true;

 

But when I run the bpm I get this error

Error:

System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at Terrasoft.Core.Process.AgbProcess_93e521fAngelBaraldo1MethodsWrapper.ScriptTask1Execute(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessScriptTask.InternalExecute(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessFlowElement.CallInternalExecute(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessFlowElement.ExecuteItem(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessFlowElement.Execute(ProcessExecutingContext context)

 

Like 1

Like

2 comments

Are you trying to send requests from Creatio to the same Creatio environment? 

If that's so, it's really strange implementation. I think it's much better to call the service logic directly rather then  send an HTTP request to the endpoint and parse the response json. 

the mock code would look like this 

var service = new CustomStockServiceHelper(userConnection); 
var response = service.GetNoConciliadosData();

I assumed that you use a CustomStockServiceHelper in CustomStockService to retrieve the data. 

 

DM me if you need more help. 

Best regards, 
Yurii

 

Yuri Sokil,

Yuri thanks for you response.

Show all comments

Is it possible to override an OOTB C#-defined REST endpoint in Creatio? In our case, we need to trigger some action when a file is uploaded, and since the file record creation doesn't trigger business processes/similar, we need to do this some other way. One option we are trying to attempt is overriding the FileApiService's UploadFile method to trigger the behaviour after calling the base class to behave as normal for the file upload, but we can't seem to get any override behaviour of the WCF method to work. Does anybody have information or an example of how this might be done, or some other option that we could pursue?

Like 0

Like

1 comments

Hello Harvey,

Overriding the base REST service seems to be impossible in our system. We attempted to do this but were unsuccessful. I suggest creating a business process that starts after a specified delay (for example, one hour) to perform the required actions after the file upload. 

Show all comments

We have a requirement where client would send data as csv file. This file will be later processed via BPM process and record will be loaded into the creatio object. How and where this file can be stored within Creatio Cloud ?  

Please note the file is not an attachment to any record but rather records which is to be loaded in Creatio Database.

Like 0

Like

2 comments

Hello,
 

For product sites that are hosted in the Creatio cloud, AWS S3 buckets are connected by default and are used to store files.
You can also use the option of storing files in the database as well, but please note that this will lead to increased memory consumption at the database level.
When developing functionality that covers file uploads, we recommend using the "API for file management" that is built into Creatio products.
You can find a detailed description and examples of how to use the "API for file management" in an article on Creatio Academy, as well as the File storage options for storing files in Creatio.
 

Thank you.

Serhii Parfentiev,

Before deploying this on Creatio Cloud I need to develop this on my local Creatio set up

How to Validation of S3 Configuration:

"I have configured Amazon S3 as file storage in Creatio local following the 'File storage options ' guide. 
How can I validate that this S3 configuration is working correctly (I don't see anything in log)?
"Any existing API i can use to see how this work

What  Tables and Objects Involved in File Upload:

"Which Creatio tables or objects are involved in file upload and storage when using external storage like Amazon S3? Specifically, what tables store metadata and file details for uploaded files when it is not associated with any entity like Accounts or Contacts?

 Need these to access file from BPM"

Show all comments

Hello

 

It is posible to save a file in creatio from a base64 string? I have a web service that allows me to request a document by an id to an external service and it responds with the document in a base64 string, so I would like to know if it is possible to convert that string into the file and save it in some record on the platform.

 

Thank you 

Like 0

Like

2 comments

Something like this should work:

var base64FileString = Get&lt;string&gt;("Base64File");
var accountId = Get&lt;Guid&gt;("AccountId");
 
var attachFileType = new Guid("529bc2f8-0ee0-df11-971b-001d60e938c6");
var fileName = "SomeFile.docx" // set proper file type in file name
 
var entity = UserConnection.EntitySchemaManager.GetInstanceByName("AccountFile");
var fileEntity = entity.CreateEntity(UserConnection);
fileEntity.SetDefColumnValues();
fileEntity.SetColumnValue("AccountId", accountId);
fileEntity.SetColumnValue("TypeId", attachFileType);
fileEntity.SetColumnValue("Name",fileName);
fileEntity.SetBytesValue("Data", Convert.FromBase64String(base64FileString));
fileEntity.Save();

Ryan

Ryan Farley,

Thank you very much 

Show all comments

Hello,

 

I'm trying to implement a file storage that saves files on a network share instead of the database. I followed the instructions here:  API for file management | Creatio Academy but I'm getting a Cannot be null Parameter name: service error. 

Any help will be appreciated. 

Thanks,

Jose

 

Like 0

Like

1 comments

Good day,

Based on the screenshots, an empty value appears to be passed to a method with the “service” argument. Unfortunately, there's not enough information available to pinpoint the exact cause of the error at this time.
 

To further investigate, it would be necessary to debug and examine what the service returns in the browser console, identify what service it is, and review the function call stack.
 

These issues typically fall under the scope of a development consultation for a deeper investigation. 

If needed, you may want to discuss this with your manager to arrange a consultation.

Thank you!

Show all comments

I am connecting a third-party API to Creatio, it delivers different types of data including this:
"user_id": [
60,
"Luismary Mendez"
]
In the parameters of the Creatio response I have set it as an Array Text and as an Object

 

But when I try to connect this variable to the process it does not display it in the list of possible result values.

The field is Vendedor:

Like 0

Like

5 comments

This is because the user_id is an array in the payload received from the web service, not just a single value. If you know the array will only contain a single set of values and the first value in the user_id array will always be the integer Id and the second value will always be the text name, you could flatten them out by mapping them as text and integer values:

  • Map ID as: user_id[0]
  • Map Name as: user_id[1]

Ryan

Ryan Farley,

What you're telling me is that I have to set the user_id as an object?

You could, but that doesn't pass to a subprocess (with an array inside an array). If you are able to flatten it out and if you know the array will only contain a single set of values and the first value in the user_id array will always be the integer Id and the second value will always be the text name, that will pass easily to a subprocess. Like this for the "user_id" first element in array, which is an int from what you've shared:

The second value in the user_id array, which is a string from what you've shared, would look like this:

This is assuming your JSON looks like this:

{
	"result": [
		{
			"id": "someid",
			"name": "somename",
			"user_id": [
				60,
				"Some name"
			]
		}
	]
}

You're basically changing it from an array with an int in index 0 and string in index 1 to flattened out properties pointing to the value in index 0 and index 1. This is, of course, assuming that the user_id array will only contain an int at index 0 and a string at index 1.

Ryan

Ryan Farley,

Thanks Ryan, I understood your explanation, I will apply it and let you know how it goes.

Carlos Soto,

Thanks Ryan. It's works

Show all comments

Hello.

I have a web services API that requires an Id and an hmac generated with the request parameters and an API Key to be placed in its authorization header.

Is there a way to obtain the call body to perform the HMAC?

In postman I have been able to make the call successfully with a pre-request which is the following:

 

const apiKey = pm.collectionVariables.get("apiKey");;
const webId = pm.collectionVariables.get("webId");
const crypto = require('crypto-js');
 
if(pm.request.method === 'POST') {
 
    const parsedBody = JSON.parse(pm.request.body.raw);
    const jsonParams = JSON.stringify(parsedBody);
 
    // Create HMAC
 
    const hmac = crypto.HmacSHA256(jsonParams, apiKey);
    const hmacb64 = crypto.enc.Base64.stringify(hmac);
 
    // Set computed HMAC as an environment variable (or you could add it directly to the headers)
    pm.environment.set('hmacb64', hmacb64);
 
    // Construct the Authorization header
    const authorizationHeader = "signmage " + webId + ":" + hmacb64;
    pm.environment.set('Authorization', authorizationHeader);
} else if(pm.request.method === 'GET') {
 
    const url = pm.request.url.getPathWithQuery();
 
    const hmac = crypto.HmacSHA256(url, apiKey);
    const hmacb64 = crypto.enc.Base64.stringify(hmac);
 
    // Set computed HMAC as an environment variable (or you could add it directly to the headers)
    pm.environment.set('hmacb64', hmacb64);
 
    // Construct the Authorization header
    const authorizationHeader = "signmage " + webId + ":" + hmacb64;
    pm.environment.set('Authorization', authorizationHeader);
}

 


But in Creatio I'm a little lost if it's possible to do something similar.

I would appreciate it if you could help me know if this is possible. Thank you.

Like 1

Like

1 comments

Hello Laura,

Thank you for your question.

I have contacted our R&D team regarding when this functionality will be implemented in our system. The HMAC-SHA256 signature is planned to be implemented with the 8.3 release. Currently, there is no built-in API to use HMAC.

Hope this helps.

Show all comments

I tried to send information through Postman. After verifying that the details are correct including the URL and keys. Postman's token is valid. The following error is received:

 I also tried to send DATA to on another object and get the same error. Is there a system malfunction?

Like 0

Like

1 comments

Hello,

 

Generating source code for all schemes and fully compiling the system usually helps to resolve this error. In this case, the OData entity will be rebuilt and you should not get this error. So your actions:
1. Generate the source code for all schemas
Gener

2.  Perform a full compilation of the site


Compilation

If this does not help you solve the issue, please create a separate ticket for the Creatio support team.
 

Thank you.

Show all comments

Hi Expert ,

    I am trying to use Creatio api with basic authentication . I am following below links :

    https://documenter.getpostman.com/view/10204500/SztHX5Qb#46f97170-d66d-…;

    

    NotWorking in PostMan : As per documention it's not working  in postman. Stored BPMCSRF value from Response Header Cookie of Token Request and call get api with BPMCSRF / ForceUseSession  headers key with it's value .Removed cookies from get request. Send the the get request it's giving a html response without any error details.

    

    Working in PostMan : In PostMan Send Token request then send get request (https://steuler.creatio.com/0/odata/Product?$top=1) without set any Header keys it's working fine. In this scenario i can see token request response header cookie values are sending bydefault by Postman in the get request.

    NotWorking in Consol Application : As per 2nd scenario i am trying to send a Get api request with token generate Response header cookies values but it's showing html error without any error details

    NotWorking in Consol Application : As per documentation Stored BPMCSRF value from Response Header Cookie of Token Request and call get api with BPMCSRF / ForceUseSession  headers key with it's value .But showing html error without any error details.

    i have attached my screen shots for reference.From my side any configuraration need to be changed Creation envionment for that my scenario  Can you give me any proper documents which i can follow and will be worked ?

    below is my console application code :

                // Create HttpClient

                using (HttpClient httpClient = new HttpClient())

                {

                    // Create HttpRequestMessage

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, @"https://steuler.creatio.com/0/odata/Product?$top=1");

                    // Set request headers

                    request.Headers.Add("Accept", "application/json");

                    request.Headers.Add("ForceUseSession", "true");

                    request.Headers.Add("BPMCSRF", "YtuvyS.WPYmW5BChY5anK.");

                    // Send the request

                    HttpResponseMessage response =  httpClient.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();

                    // Check response status

                    if (response.IsSuccessStatusCode)

                    {

                        string responseData =  response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                    }

                 }

 

Thanks and Regards

Surajit Kundu

Like 0

Like

2 comments

I don't see in your code the call to authenticate. I assume that you're previously calling /ServiceModel/AuthService.svc/Login somewhere to get the BPMCSRF value? See https://documenter.getpostman.com/view/10204500/SztHX5Qb#46f97170-d66d-…

Note, the BPMCSRF value doesn't last forever, so it does need to be a recently obtained value. 

This article shows the complete steps for executing requests via Postman which might help: https://academy.creatio.com/docs/8.x/dev/development-on-creatio-platfor…

Ryan

Ryan Farley,

Hi 

      Thanks for your reply . Below is my token generation code from where i have taken cookies value for my 2nd request .Before i have not attached that token generation part as these is working fine. In postman it's working fine using Cookies based authentication.In my Console application i am sending all the Cookies (BPMLOADER, .ASPXAUTH, BPMCSRF, and UserName) as a Header Key and value in further requests to Creatio services that use cookie-based authentication but it's showing Html Error ?

 static async Task<Dictionary<string, string>> TokenGenerateDictionary()

        {

            var headerCookies = new Dictionary<string, string>();                 

                using (var client = new HttpClient())

                {

                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    using (var request = new HttpRequestMessage(HttpMethod.Post, @"https://steuler.creatio.com/ServiceModel/AuthService.svc/Login"))

                    {

                        request.Content = new StringContent($"{{\"UserName\":\"ram\",\"UserPassword\":\"abcd\"}}", Encoding.UTF8, "application/json");

                        var response = client.SendAsync(request).Result;

                        var responseString = await response.Content.ReadAsStringAsync();

                        JObject responseJson = JObject.Parse(responseString);

                        int code = (int)responseJson["Code"];

                        if (code == 0 && response.IsSuccessStatusCode)

                        {

                            foreach (string setCookieHeader in response.Headers.GetValues("set-cookie"))

                            {

                                 string[] cookies = setCookieHeader.Split(';');

                                if (cookies.Length > 0)

                                {

                                    string[] keyValue = cookies[0].Trim().Split('=');

                                    if (keyValue.Length == 2)

                                    {

                                        string key = keyValue[0];

                                        string value = keyValue[1];

                                        if (!headerCookies.Keys.Contains(key))

                                            headerCookies.Add(key, value);

                                    }

                                }

                            }

                         }

                    }

                }

            return headerCookies;

        }



Request Get Operation send cookies in Header Key :

         var tokenHeaderCookiesData = TokenGenerateDictionary().ConfigureAwait(false).GetAwaiter().GetResult(); 

         string requestUri = @"https://steuler.creatio.com/0/odata/Product?$top=1";

         using (HttpClient httpClient = new HttpClient())

                {

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);

                    foreach (string key in tokenHeaderCookiesData.Keys)

                    {

                        //BPMLOADER, .ASPXAUTH, BPMCSRF, and UserName

                        if (key== "BPMLOADER" || key == ".ASPXAUTH" || key == "BPMCSRF" || key == "UserName")

                           request.Headers.Add(key, tokenHeaderCookiesData[key]);

                    }

                    HttpResponseMessage response =  httpClient.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();

                    string responseData =  response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                }

   



Html Error Response with status OK:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" culture="en-US">

<head><meta http-equiv="X-UA-Compatible" content="IE=Edge" /><meta name="fontiran.com:license" content="LAXSN" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>

    Creatio

</title>

    <style>

        .font-preload {

            position: absolute;

            opacity: 0;

        }

        .font-preload-open-sans {

            font-family: "Bpmonline Open Sans";

        }

        .font-preload-open-sans-light {

            font-family: "Bpmonline Open Sans Light";

        }

        .font-preload-open-sans-bold {

            font-family: "Bpmonline Open Sans Bold";

        }

    </style>

<script type="text/javascript" src="https://steuler.creatio.com//core/8dc3ccad339641a4ecd1ecb0b57f017d/Terr…"></script>

<script type="text/javascript" src="https://steuler.creatio.com/api/ClientScript/GenerateLoginScripts"></script>

<script type="text/javascript" src="https://steuler.creatio.com//core/057665f97324038f6c7c326b6734de6b/requ…" data-main="https://steuler.creatio.com//core/0fbfa51b1de27f89696f0f8d31da5f16/Terr…" async></script>

<script type="text/javascript"></script>

</head>

<body>

    <div class="font-preload">

        <span class="font-preload-open-sans">_</span>

        <span class="font-preload-open-sans-light">_</span>

        <span class="font-preload-open-sans-bold">_</span>

    </div>

    <form name="IndexForm" method="post" action="./NuiLogin.aspx?ReturnUrl=%2f0%2fodata%2fProduct%3f%24top%3d1&amp;%24top=1" id="IndexForm">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="+mvmSAOrSFVSNU1VvvnnAv5lt45aMHGRIkN033uMqlv/X2Fn2421RrzZayJqLBBTzwEnVTCtLeOrFnkbGP1c32c1p4dJwgJeute2MMWvNkRY1wHA" />

<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="0BFA92C5" />

    </form>

</body>

</html>

 

Thanks 

Surajit Kundu

Show all comments

I have a subprocess that loops the returned records from an API call and adds a new record in a data object. I want to modify the process to check if the record already exists and if so, modify the existing record with the data changes.

Like 0

Like

1 comments

First read the record using whatever Identifier you have on it from the source data. If the record exists the Id value will be a Guid and if it doesn't exist the Id of the record will be Guid.Empty.

So the condition for the update will look like: 

[Id from the Read] != Guid.Empty (this means the Read found the record)

The "else" will proceed to the Add, just make sure you populate some identifying value from the API call that you'll use when you read if the record exists next time.

Ryan

Show all comments