Wednesday 12 April 2023

UiPath Custom Rules Engine Activity Tutorial - Part 2

 

UiPath Custom Rules Engine Activity Tutorial - Part 2

In this tutorial, you create a UiPath workflow application for a fictitious online lender. It determines whether a customer is eligible for a loan according to specific criteria (rules). The criteria include the amount of the loan, the annual income of the borrower, and the duration of the loan.

To make the workflow, we will not follow the typical rule development workflow (so many if-else conditions ..) We will use the custom rules engine. By doing so, you discover the steps required to develop, deploy, and maintain a rule-based application.

Prerequisites:

·         UiPath Studio <= 2022.4.6

·         UiPath Robot <= 2022.4.6

·         Orchestrator (will use staging)

·         Data Service

·         Insights

·         Internet Access to download the package

Rules

Initially, we have the following policy (business rules) to apply for a loan ( 8 rules). Please note the priority for each one.



If you don’t want to follow along you can download the code from the last section, Source.

Procedures

1.      Create two entities that represent the business object models in data service (Borrower and Loan) as per the images below or import the attached schema file in the last section to generate the entities.:





2. Create a UiPath Studio Project (C#, Windows)



3. Import package UiPathTeam.RulesEngine.Activities

4.Import the business entities(borrower and loan) I’ll use OnlineBanking.Models as namespace.



5. From Activities Panel >> UiPathTeam.RulesEngine.Activities >> Drag Rules Activity Panel >> In Select Type Dialog Choose (OnlineBanking.Models.Loan)



6. After clicking ok in step 5, you will see the rule policy activity as in this image (Rule Policy), where you need to fill in the following:

Rule File Path: click on the ellipse icon and choose any location the dialog will create the file if it’s not exists.

Rule SetName: click on RuleSet Browser to create a group

Target Object: I created a variable of type OnlineBanking.Models.Loan to pass it to the rules engine

Result Object: same as TargetObject value



7. Click Edit Rules to start adding the rules, after adding all rules, you should get this view:

“Please note I’m using the Halt keyword in Rule 8 to end the execution if loan amount > 1M”



Your .rules file should contains the XAML representation of your code:


<RuleDefinitions xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
        <RuleDefinitions.RuleSets>
               <RuleSet Description="{p3:Null}" Name="Loan-1-0" ChainingBehavior="Full" 
xmlns:p3="http://schemas.microsoft.com/winfx/2006/xaml">
                       <RuleSet.Rules>
                               <Rule Priority="1" ReevaluationBehavior="Never" 
Description="{p3:Null}" Active="True" Name="Rule 8">
                                      <Rule.Condition>
                                              <RuleExpressionCondition Name="{p3:Null}">
                                                      <RuleExpressionCondition.Expression>
                                                             <ns0:CodeBinaryOperatorExpression Operator="GreaterThan"
 xmlns:ns0="clr-namespace:System.CodeDom;Assembly=System, Version=4.0.0.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089">
                                                                     <ns0:CodeBinaryOperatorExpression.Right>
                                                                             <ns0:CodePrimitiveExpression>
                                                                                    <ns0:CodePrimitiveExpression.Value>
                                                                                    <ns1:Int32 xmlns:ns1="clr-namespace:System;Assembly=mscorlib, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">1000000</ns1:Int32>
                                                                                    </ns0:CodePrimitiveExpression.Value>
                                                                             </ns0:CodePrimitiveExpression>
                                                                     </ns0:CodeBinaryOperatorExpression.Right> 



In workflow I used custom logs activity to measure the processing time for each loan request.
I’ll use Insights’ s dashboard as a reporting for processing time so we can compare the 
performance of the custom activity (Rules Engine) with any other way like if-else activities.

Custom Log Filed:

·         RulesEngineTransacionTimeMilliseconds

·         RulesEngineEntityId

·         RulesEngineEntityIsApproved
                                          


Testing

To test our policy I’ll do the following:

1.      Read all Loan records as sets (100 records per set) with condition IsProcessing = false

2.      Loop over each set and apply rules policy to get the result

3.      Update loan entity so we don’t read the record again.

4.      To fill data service with test data, run the GenerateTestData workflow, where it will create random data based on the DataSize argument value (there are 8 names in the workflow and the DataSize argument adjust the number of loans per name)

5.      Publish the package (Online.Banking) to your Orchestrator

6.      Grant your Robot account a read and write permission on data service

7.      Create a process to fill data; set Entry point to GenerateTestData and display name to Online.Banking.GenerateData

8.      Create a process to test the rules engine; set Entry point to Main and display name to Online.Banking.Loan

after setting the configuration you should get this view in your orchestrator



Performance:

This graph (from Insights) shows the average processing time per loan in Milliseconds using a 48,523 Records.



Source:

https://github.com/ajamaeen/UiPath-Rules-Engin-Samples

Schema file for Data Service Entities :https://github.com/ajamaeen/UiPath-Rules-Engin-Samples/blob/main/Docs/Schema.json

NuGet Package: https://github.com/ajamaeen/UiPath-Rules-Engin-Samples/releases/tag/UiPathRulesEngine

UiPath Custom Rules Engine Activity Intro - Part 1

UiPath Custom Rules Engine Activity Intro - Part 1

Intro to Rules Engine:

Almost all workflows require an enormous number of business rules. For example, car reservations made at least 20 days in advance receive a 12% discount unless the cost of the car is less than $100.

While expressing rules using the conditional flow activities (if,if-else, while …) is certainly possible, it's not always the best choice. Instead, the right approach for handling complex groups of rules can sometimes be to use a rules engine.

Encoding business rules into code using conditional activities makes the rules harder to find, read, and modify. Over the years, the software industry has invented tools for working with business rules. Called rules engines, inference engines, and logic machines. A rules engine specializes in making business rules easier to implement, process, isolate, and modify.

To make using a rules engine possible in UiPath workflows, we have created a wrapper activity on top of Windows Workflow Foundation that can be accessed through the policy activity. Using this activity, a developer can define a group of rules called a rule set. Each rule has the form IF <condition> THEN <action> ELSE <action>. 

Solution Architecture:

The image below is a high-level view of the proposed solution, more details in the upcoming sections.


Solution Architecture




Terms (Conditions, Rules, and Rule sets):

We will use three important terms in this article: Conditionsrules, and rule sets.

In a workflow, conditions are chunks of logic that return true or false.

Several workflow activities utilize conditions to guide their behavior. These activities include the While activity, If, If Else activity, and the Do While. The While activity, for instance, loops until its Condition property returns false.

Rules are conditions with a set of actions to perform. Rules use a declarative if-then-else style, where the "if" is a condition to evaluate. If the condition evaluates to true, the runtime performs the "then" actions, otherwise, the "else" actions.

Rule Set is a collection of one or more rules. As an example, we might have three rules we use to calculate the discount on the price of a car rental (shown here in pseudo-code).

if the driver’s age is greater than 55

then discount = discount + 10%

if the length of rent is greater than 5 days

then discount = discount + 10%

if the driver is married and has no accidents history

then discount = 12%

Before we can evaluate these three rules, we need to group them inside a Rule Set. We can assign each rule a priority to control the order of evaluation. workflow can revisit rules if later rules change the data used inside previous rules. We can store rules in an external XML file and feed external rules to the workflow runtime when creating a new workflow.

This graph shows in detail each term and how it’s related to each other.


Rules Set

Policy Activity

Policies are everywhere in our life. Universities define policies for student admissions, insurance companies define policies for underwriting qualifications, banks define policies for loans …
Business policy can become very complex and is full of declarative knowledge.

The custom rules engine activity (Policy Activity) provides a user interface for the user to update, create, and modify rule sets and rules. The features and execution semantics described in policy activity give us more flexibility when compared to procedural code. We can dynamically customize rules to meet the needs of a specific customer or business scenario.

UiPath policy activity is just a wrapper on top of the Microsoft workflow foundation (Rules Engine) built using UiPath template for visual studio 2019, and it uses the execute method of a RuleSet to process the rule collection.

The experience of the custom policy activity is shown in Figure 3



Figure 3 - UiPath Policy Activity


The .rules File

Rules engine uses a file with an extension of .rules to store data. it’s XAML representation of objects from the System.CodeDom namespace. The CodeDom (Code Document Object Model) namespace contains classes that construct source code in a language agnostic fashion.

At compile time, this .rules file becomes an embedded resource in workflow package.

Adding a Policy Activity

To use policy activity, follow these steps:

1.      Install package UiPathTeam.RulesEngine.Activities

2.      Drag the rules policy activity from the toolbox onto the workflow designer.

3.      In the select types dialog select the type of object you want to apply rules on

4.      Select the ellipses in the Rules File Path field to launch an open file dialog where you can either create a new rules file (.rule) or choose an existing one.

The main goal of .rule file is to have many rules policy activities referencing one rules file.

1.      RuleSet Name combobox list all available RuleSets in the selected file (step 4)

2.      In the target object enter the object which to apply the rules on

3.      In the result object enter the result object after applying the rules (you can use same target object)

4.      RuleSet Browser button launches a dialog to add versions to rule sets (Figure 4)

5.      Edit Rules button launches the Rule Set Editor for the selected rule set in RuleSet name combobox (Figure 5) In the rule set editor the Condition, Then actions, and Else actions are entered in as text and parsed into the associated object model representation; rules are built against the members on the workflow.

6.      Selecting a given rule shows its Condition, Then actions, Else actions, and a set of additional properties.

7.      Selecting OK serializes the RuleSet to the .rules file associated with the workflow



Figure 4 - RuleSet Browser



Figure 5 - Rule Set Editor

Rule Set Editor

Is the heart of the policy activity where you can add rules, enable rules, disable rules, update rule’s priority, specify chaining of the rule and set the type of reevaluation for the rule.

Rules Evaluation

Each rule in a RuleSet has a priority value with a default of 0. The rules in a RuleSet can be considered a sorted collection, ordered by the priority values. The WF Rules evaluator evaluates rules individually and executes the rule's actions based on the results of the rule's condition evaluation.

The evaluation mechanism can be conceptually described with the following procedure:

1.      Start with the list of active rules.

2.      Find the highest priority rule.

3.      Evaluate the rule and execute its Then/Else actions as appropriate.

4.      If the actions of a rule update a field/property that is used by a previous rule in the list (one with a higher priority), reevaluate that previous rule and execute its actions as appropriate. Note that only those rules with a specific dependency are reevaluated.

5.      Continue the process until all rules in the RuleSet have been evaluated.

Rules Dependencies

When an action produces a side effect that matches a dependency from a previously executed rule, the rules engine can go back and re-evaluate the previous rule. In rules engine terminology, this feature is called forward chaining.

Chaining is based on the identified dependencies among rules; more specifically, the dependencies among the actions of a rule and the conditions of other rules. These dependencies can be identified or declared in one of three ways:

·         Implicit

·         Attribute-based

·         Explicit

For detailed explanation about rules chaining consult this document https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa480193(v=msdn.10)

Implicit dependencies are identified automatically by the engine. When a RuleSet is first executed, each rule is analyzed to assess the fields/properties that it reads in its condition and writes to in its actions. This is done by walking the expression in the condition and the statements in the actions.

Attribute-based for method calls within a rule, it becomes more difficult to deterministically evaluate the reads/writes that occur. To address this problem, WF provides three attributes that can be applied to a method to indicate its actions:

·         RuleRead

·         RuleWrite

·         RuleInvoke

Attributing a method with the RuleRead attribute indicates that it reads the indicated property. Similarly, the RuleWrite attribute can be used to indicate that a method updates a given field or property.

Explicit the final mechanism for indicating field/property dependencies is through the use of the Update statement. The Update statement takes as its argument either a string that represents the path to a field or property or an expression that represents a field/property access. For example, either of the following two statements could be typed into the RuleSet editor to create an Update statement on the Name property of a Customer instance on the workflow: Update("this/customer/Name") or Update(this.customer.Name)

Forward chaining is a very powerful notion that allows atomic rules to be assembled into RuleSets without the definition of, or necessarily even the knowledge of, the dependencies among the rules.

However, in some scenarios, the rule writer may want the ability to provide more control over the chaining behavior, specifically the ability to limit the chaining that takes place. This enables the rule modeler to:

·         Limit the repetitive execution of rules, which may give incorrect results.

·         Increase performance.

·         Prevent runaway loops.

This level of control is facilitated in WF rules by these two properties:

·         A Chaining Behavior property on the RuleSet.

·         A Reevaluation Behavior property on each rule.

Both of these values can be set in the RuleSet Editor.

The Chaining Behavior property on the RuleSet has three possible values:

·         Full Chaining

·         Explicit Chaining

·         Sequential

The Full Chaining option is the default and provides the behavior described up to this point. The Explicit Chaining option turns off the implicit and attribute-based chaining and prescribes that chaining should only occur for explicit Update statements. This gives the rule writer complete control over what rules cause reevaluation. Typically, this would be used to either avoid cyclic dependencies that cause excessive (or even runaway) rule re-execution, or to boost performance by eliminating superfluous rule reevaluation not required to provide functional completeness of the RuleSet.

The final option is Sequential. This option will cause the engine to evaluate the rules in strictly linear fashion. Each rule would be evaluated once and only once and in the order of priority. Rules with a higher priority could impact rules with lower priorities, but the inverse would not be true since no chaining would occur. Therefore, this option would be used with explicit priority assignments unless no dependencies existed among the rules.

The Reevaluation Behavior on the rule has two possible values:

·         Always

·         Never

Always is the default and provides the behavior previously discussed, namely that the rule will always be reevaluated based on chaining due to the actions of other rules. Never, as the name implies, turns off this reevaluation. The rule will be evaluated once but will not be reevaluated if it has previously executed any actions. In other words, if the rule has previously been evaluated and consequently executed its Then or Else actions, it will not be reevaluated.

Halt Function

As a final control, a Halt function can be added as a rule action (simply type "Halt" into the Then or Else action boxes in the editor). This will immediately stop RuleSet execution and return control to the calling code. The usefulness of this function is not necessarily limited to chaining control scenarios, of course. A RuleSet with a specific functional goal, for example, may use a Halt function to short-circuit execution once the goal has been reached.

Kindly check part2 of this series for a sample scenario the includes all mentioned features.

https://uipath.atlassian.net/wiki/spaces/FAN/pages/edit-v2/87032353715?draftShareId=129bed9a-4b48-4f9f-a85f-54a6aee3362d

Conclusion:

A custom policy activity provides can integrate rules support into UiPath workflows.

RPA developers can easily incorporate rules at any point in their workflow and they are able to make the determination of whether to model their logic in the workflow model, rules, or code.

References

For more information kindly consult this document

https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa480193(v=msdn.10)

Complete source code:

https://github.com/ajamaeen/UiPathTeam.RulesEngine

Sample Tutorial : UiPath Custom Rules Engine Activity Tutorial -Part 2


Sunday 30 January 2022

Common UiPath Issues and how to solve them


Probelm (Logs are not visible in Orchestrator)
UiPath Robot's log don't being sent to Orchestrator even though it's availales in executions folder (%localappdata%\UiPath\Logs).

Description:
 The way logs being sent to orchestrator :
  • Logs will be sent to execution folder (%localappdata%\UiPath\Logs) always. 
  • If Orchestrator is unavailable, logs are stored in a local database (LiteDb) in this path C:\Windows\{SysWOW64 or SysWOW32}\config\systemprofile\AppData\Local\UiPath\Logs\execution_log_data. 
  • Sometimes the LiteDb used as cache regardless of connectivity between Orchestrator and Robot
  •  Robot's service send logs from LiteDb  to Orchestrator but that sometimes don't happen and cause the issue
Solution:
  • Check Orchestrator Database to see if there is available disk space.
  •  If the logs file is too big robot fails to delete them from LiteDb  which led Robot to not sending logs to Orchestrator 
  •  Sometimes the database file LiteDb get corrupted (Don't know why) which led Robot to not sending logs to Orchestrator (you notice the file is corrupted if file size don't increase) 
 To solve the issue: 
  • Delete the folder C:\Windows\{SysWOW64 or SysWOW32}\config\systemprofile\AppData\Local\UiPath\Logs\execution_log_data 
  • Restart the service 
  • Cache gets cleared and robots start sending logs to Orchestrator

The LiteDb  is encrypted and you can't open it


Friday 10 December 2021

UiPath Authorizing External Applications Using OAuth 2.0 With Asp.net MVC Core & Consuming Data Service Web API

OAuth 2.0 is a security standard where you give one application permission to access your data in another application. The steps to grant permission, or consent, are often referred to as authorization or even delegated authorization. You authorize one application to access your data, or use features in another application on your behalf, without giving them your password.

Registering an external application, meaning an application that is external to your UiPath platform, is a way to share your UiPath resources without having to also share your credentials. Instead, using the OAuth framework, you can delegate your UiPath authorization to external applications.

You can register third-party applications so that they can obtain authorization through the Cloud Portal to gain access to your UiPath resources. Once registered, these applications can make API calls to UiPath applications to access the resources you include in the registration scope.

For more details click here https://docs.uipath.com/automation-cloud/docs/about-external-applications .

In this blog I’ll show in detail how to build an ASP.NET MVC core Web App that integrated with UiPath platform using OAuth and how to consume UiPath Data Service Web API.

I’ve divided the blog into four sections:

·         Registerexternal application in UiPath cloud portal.

·         Creating ASP.NET Core App.

·         Set up ASP.NET Core OAuth 2.0 middleware.

·         Consume Data Service Web API from the application you created in section 1. 


Register external application in UiPath cloud portal

 To register an external application so that it can use OAuth 2.0 to access your UiPath resources follow the following steps:

In Automation Cloud, go to Admin > External Applications and click Add Application :

·         Name: OAuth Demo

·         Redirect URL:  http://localhost:5200/authorization-code/callback

·         Scopes (Figure 2)

o    DataService.Schema.Read

o    DataService.Data.Read

o    DataService.Data.Write 




Add External Application




 After registering the App, you will receive a notification message with App ID & App Secret:

App Secret

xxx

App ID: 

yyyy

 Please store the IDs in a safe place, we will use them to setup OAuth in ASP.NET MVC core app in next step.


CreatingASP.NET Core App

Open visual studio and create a new project:

·         Template: Asp.net Core Web App

·         Language: C#

·         Target Framework: .Net 5.0

·         Authentication Type: None

·         Configure Https: No



 

After creating the project:

·         Add [Authorize] attribute to IndexModel to prevent anonymous access.

·         Change the port (to match the Redirect URL in registering application section) in launchSettings.json >> iisExpress >> applicationUrl >> 5200

·         Add _LoginPartial.cshtml view to display logged in username.

·         Add Section to configuration file appsettings.json to include (AppSecret, AppID, OrgName…) 

In the next step we will configure the OAuth middleware to integrate with UiPath platform.



Set upASP.NET OAuth 2.0 Authentication Middleware

ASP.NET Core comes with OAuth authentication middleware, that makes it easy to use a third-party OAuth 2.0 server for login.

For this tutorial, you will use UiPath OAuth service to protect our app. The ASP.NET OAuth Middleware will be connected to UiPath and use it as an Identity Provider.

First you’ll need to open up Startup.cs and add this line right above app.UseAuthorization() in the Configure method: 


app.UseAuthentication();

 Then create a method ConfigureUiPathAuth as below 

private void ConfigureUiPathAuth(IServiceCollection services)
{

}


Now In order to complete the setup we need some information from OAuth endpoint like (AuthorizationEndpoint,Scope,TokenEndpoint and UserInformationEndpoint)

To get these information you should access URL:  https://cloud.uipath.com/identity_/.well-known/openid-configuration which displays the configuration information based on OAuth protocol:




So we need the following information to complete the setup:

·         AuthorizationEndpoint = https://cloud.uipath.com/identity_/connect/authorize

·         TokenEndpoint = https://cloud.uipath.com/identity_/connect/token

·         serInformationEndpoint = https://cloud.uipath.com/identity_/connect/userinfo

·         Claims = country, name, sub, last_name, first_name, email

·         ClientId = xxx

·         ClientSecret = yyy

·         Scopes = "DataService.Schema.Read DataService.Data.Read DataService.Data.Write" also we must use this scope “openid” otherwise you will not be able to get the access token based on OAuth protocol.


So, after filling all required information the final version of ConfigureUiPathAuth looks like this:  


private void ConfigureUiPathAuth(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                // If an authentication cookie is present, use it to get authentication information
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                // If authentication is required, and no cookie is present, use Okta (configured below) to sign in
                options.DefaultChallengeScheme = "UiPath";
            })
           .AddCookie() // cookie authentication middleware first
           .AddOAuth("UiPath", options =>
           {
               // Oauth authentication middleware is second
 
               // When a user needs to sign in, they will be redirected to the authorize endpoint
               options.AuthorizationEndpoint = $"https://cloud.uipath.com/identity_/connect/authorize";
 
               // scopes when redirecting to the authorization endpoint
               options.Scope.Add("DataService.Schema.Read DataService.Data.Read DataService.Data.Write");
               options.Scope.Add("openid");
 
               //After the user signs in, an authorization code will be sent to a callback
               // in this app. The OAuth middleware will intercept it
               options.CallbackPath = new PathString("/authorization-code/callback");
 
               // The OAuth middleware will send the ClientId, ClientSecret, and the
               // authorization code to the token endpoint, and get an access token in return
               options.ClientId = Configuration["AppID"];
               options.ClientSecret = Configuration["AppSecret"];
               options.TokenEndpoint = $"https://cloud.uipath.com/identity_/connect/token";
 
               //Below we call the userinfo endpoint to get information about the user
               options.UserInformationEndpoint = "https://cloud.uipath.com/identity_/connect/userinfo";
 
               //Describe how to map the user info we receive to user claims
               options.ClaimActions.MapJsonKey(ClaimTypes.Country, "country");
               options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
               options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
               options.ClaimActions.MapJsonKey(ClaimTypes.Surname, "last_name");
               options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "first_name");
               options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
 
               options.SaveTokens = true;
 
 
               options.Events = new OAuthEvents
               {
                   OnCreatingTicket = async context =>
                   {
                       //Get user info from the userinfo endpoint and use it to populate user claims
                       var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                       request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                       request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                       var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                       response.EnsureSuccessStatusCode();
                       var data = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());
                       context.RunClaimActions(data);
                   }
               };
           });
        }


Don’t forget to call ConfigureUiPathAuth Inside ConfigureServices as below



Before we run the application we should add below code into function Configure to fix a common issue related to Https (Correlation failed. Unknown location …) especially if you are using self-signed certificate or no certificate. 

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // To Fix the error Exception: Correlation failed. Unknown location
            app.UseCookiePolicy(new CookiePolicyOptions()
            {
                MinimumSameSitePolicy = SameSiteMode.Lax
            });

           ……



Now run the application by pressing  (F5)  , you will be redirected to UiPath login page then enter your login info after that browser will redirect you back to the home page (http://localhost:5200) , you should see this screen:



By completing the above steps, you have integrated with UiPath Platform, and you can login using your organization credentials. 

Next, I’ll show you how to consume data service API (Insert & Query).


Consume Data Service Web API from External Application

We need the following to proceed with the demo:



     ·         Create a ChoiceSet called DemoType with tow values (Oauth , API)  

                        


·         Create an entity called OAuthDemo with two fields:

o    Name of type string and make it required

o    Type of type DemoType and make it required



·         Create an entity called OAuthDemo with two fields:

o    Name of type string and make it required

o    Type of type DemoType and make it required

Assign DataReader & DataWriter roles to target user otherwise you will receive Unauthorized error when calling the API 


As per UiPath documentation https://docs.uipath.com/data-service/reference/add-entity-endpoint  

·         The endpoint to create a new record in OAuthDemo entity: https://cloud.uipath.com/{OrgName}/{TenantName}/dataservice_/api/EntityService/ OAuthDemo/insert

·         The endpoint to query all records in OAuthDemo entity: https://cloud.uipath.com/{ OrgName}/{TenantName}/dataservice_/api/EntityService/ OAuthDemo/query


To get the access token for the logged in user use this code:  

await HttpContext.GetTokenAsync("access_token")


In Demo project I have created a page called (http://localhost:5200/createentity) to post a record & display number of records (check code repo) as below image:



Download the entire source code of this article (Github)

Before running your code just double check to update the following configuration file values:



Notes:

1.      From 2021.10 onwards it works the same on-prem as well as in the Cloud