I've created a webservice that passes the received data from my api to a "Collection of Objects with attributes" parameter inside my business process.

I would like to know how can i convert that business process parameter to a JArray.



JArray jarray = Get("ProcessSchemaCadastros");

This is the line i have in my script task to get my data from business process parameter.

Like 0

Like

2 comments
Best reply

I found a way to pass my problem, instead of trying to convert into a JArray i used:

var entities = Get<ICompositeObjectList<ICompositeObject>>("WebService1.UsrWBCadastros_Out");

then i just worked with the data from 'entities'.

 

It's much easier to transfer a JSON from the web service to a text variable in a business process. Then parse the JSON in the business process.

I found a way to pass my problem, instead of trying to convert into a JArray i used:

var entities = Get<ICompositeObjectList<ICompositeObject>>("WebService1.UsrWBCadastros_Out");

then i just worked with the data from 'entities'.

 

Show all comments

Hi, 

 

I want to call a business process from a script task of another business process. I did this because I want to send email to a collection of contacts, so I will do a foreach loop in the script task, and call the second business proces that will send the emails. 

The problem is that the second business process, its call from the first one, and appears in the process log as running, but it doesnt do anything, neither send the mail nor finish running. 

The script task code:

var _sendMailId = new Guid("451f9ef3-2a11-4ca8-9107-02e23e56f9f3");

var _manager = UserConnection.ProcessSchemaManager;

var _schema = (ProcessSchema)_manager.GetInstanceByUId(_sendMailId);

var _moduleProcess = _schema.CreateProcess(UserConnection);

_moduleProcess.Execute(UserConnection);



return true;

First business process: Mutiple email sender

 

 

Second Business process: MBS Send Email

Process log:

 

 

Thank you.

 

Javier Collazo

 

Like 0

Like

2 comments
Best reply

The problem here was that the business process that was call form the parent business process, wasn't receiving the parameter. The solution to this problem you can find it in the following question:



https://community.bpmonline.com/questions/calling-business-process-para…

 

Best regards, 

Javier

Hello,



At first you should be confident about business process that sends email is working properly. So, try to start it manually. If it will work, then something is wrong with your script task. Perhaps, you have just missed some parameters that are required in "MBS send email process" 

At second, try to save the process once again and compile the system.



Best regards,

Alex

The problem here was that the business process that was call form the parent business process, wasn't receiving the parameter. The solution to this problem you can find it in the following question:



https://community.bpmonline.com/questions/calling-business-process-para…

 

Best regards, 

Javier

Show all comments

I'm running into some trouble when trying to populate a lookup column from a script task.  I invariably get the error "System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'UsrVMProductCode'."

This is the column in question:

And here is the relevant part of the script task:

var esq = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "UsrWaterplayVMProductCode");
 
var ColId = esq.AddColumn("Id");
var ColName = esq.AddColumn("Name");
 
var entities = esq.GetEntityCollection(UserConnection);
var productCodes = new Dictionary<string,string>();
foreach (var entity in entities) {
	productCodes[entity.GetColumnValue(ColName.Name).ToString()] = entity.GetColumnValue(ColId.Name).ToString();
}
 
foreach (var pd in resultObj.UpdatedParts) {
	if (pd.PartId != "") {
		var code = "";
		if (pd.VMProductCode != "") {
			code = productCodes[pd.VMProductCode];
		}
		var update = new Update(UserConnection, "Product")
			.Set("Name", Column.Parameter(pd.Description))
			.Set("Price", Column.Parameter(pd.Price))
			.Set("UsrProductionCost", Column.Parameter(pd.Cost))
			.Set("IsArchive", Column.Parameter(pd.Inactive));
		if (code != "") {
			update.Set("UsrVMProductCode", Column.Parameter(code));
		}
		update.Where("Code").IsEqual(Column.Parameter(pd.PartId));
		if (update.Execute() > 0) {
			resultUpdate += "Product " + pd.PartId + " updated.\\r\\n";
		}
	}
}

I have confirmed through debug logging that the code variable contains a GUID.  The script also worked fine before I tried to set UsrVMProductCode, while attempting to set another lookup column in this way (Currency) gave a similar error.  Is there something special I need to do to set a lookup value with the Insert/Update objects?

Like 0

Like

2 comments

The use of Update just creates SQL statements that execute on the database directly (instead of using the object model,, like ESQ does). For a lookup column, the actual column name would have "Id" at the end of it. For example, use "UsrVMProductCodeId" instead of just "UsrVMProductCode".

Ryan

Ryan Farley,

Thanks much, that did the trick.

Show all comments

I try to run the script task in a business process to create a printable. If the business process is started by user, it'll work just fine, but when the process is started by another process or an event it'll break with an exception:

System.NullReferenceException: Object reference not set to an instance of an object.

   at Terrasoft.Configuration.ReportService.ReportService.GetSchemaNameByTemplateId(Guid templateId)

   at Terrasoft.Configuration.ReportService.ReportService.GenerateMSWordReport(String urlTemplateId, String urlRecordUId, Boolean convertInPDF)

   at Terrasoft.Core.Process.ProcessInvoiceAutoSendCustom1Custom21Custom2MethodsWrapper.ScriptTask2Execute(ProcessExecutingContext context)

   at Terrasoft.Core.Process.ProcessFlowElement.Execute(ProcessExecutingContext context)

The script task is like this:

var PrintableId = Get<string>("PrintableId2");
var ObjectIdInvoice = Get<string>("ObjectIdInvoice1");
var ConvertToPdf = Get<bool>("ConvertToPdf");
var AddInvoiceId = Get<Guid>("AddInvoiceId");
var AttachmentType = Get<Guid>("AttachmentType");
 
var userConnection = Get<UserConnection>("UserConnection");
 
var reportService = new Terrasoft.Configuration.ReportService.ReportService();
Terrasoft.Configuration.ReportService.ReportData report = reportService.GenerateMSWordReport(
    PrintableId, ObjectIdInvoice, ConvertToPdf);
var entity = userConnection.EntitySchemaManager.GetInstanceByName("InvoiceFile");
var fileEntity = entity.CreateEntity(UserConnection);
fileEntity.SetDefColumnValues();
fileEntity.SetColumnValue("InvoiceId", AddInvoiceId);
fileEntity.SetColumnValue("TypeId", AttachmentType);
fileEntity.SetColumnValue("Name", "Invoice.pdf");
fileEntity.SetColumnValue("Data", report.Data);
fileEntity.Save();
return true;

I guess ReportService doesn't obtain UserConnection from Supervisor user, so it can't get instance of "InvoiceFile". Is that the case?

How to change the script to make ReportService work with Supervisor or maybe with UserConnection of another user?

Like 0

Like

3 comments

In a script task in an interpretive business process you need to get "user connection"  with the following syntax:

var userConnection = Get<UserConnection>("UserConnection");

Additionally, please note that if you want to work with process parameters in a script task, you need to write in the following manner:

var parameter1 = Get<Guid>("Parameter1");

Set("Parameter2", parameter1.ToString());

var parameter2 = Get<string>("Parameter2");



Also, from exception message it seems that desired template not exists in the system, so you should check it.

I have a similar requirement to send report automatically to users at a certain frequency. We use Creatio 7.18.5 and the report was built using the old ReportDesigner for 7.14 and was carried over to the new version when we upgraded. 

I tried to follow this article to create the report as part of our process - https://community.creatio.com/articles/generate-printable-and-send-it-attachment-email

When the process is manually run by the user, the report gets generated. But when scheduled to run by Supervisor using timer, it gives below error - 

Terrasoft.Core.InstanceActivationException: Error creating an instance of the "Terrasoft.Tools.DevExpressReport.IReportProvider" class ---&gt; Ninject.ActivationException: Error activating UserConnection using binding from UserConnection to method
Provider returned null.
Activation path:
  3) Injection of dependency UserConnection into parameter userConnection of constructor of type DevExpressConfReportLocalizationReader
  2) Injection of dependency IDevExpressReportLocalizationReader into parameter reportLocalizationReader of constructor of type ConfigurationDevExpressReportProvider
  1) Request for IReportProvider
 
Suggestions:
  1) Ensure that the provider handles creation requests properly.
 
   at Ninject.Activation.Context.ResolveInternal(Object scope)
   at Ninject.Activation.Context.Resolve()
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings)
   at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
   at Ninject.Activation.Context.ResolveInternal(Object scope)
   at Ninject.Activation.Context.Resolve()
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings)
   at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
   at Ninject.Activation.Context.ResolveInternal(Object scope)
   at Ninject.Activation.Context.Resolve()
   at Ninject.KernelBase.Resolve(IRequest request, Boolean handleMissingBindings)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
   at Terrasoft.Core.Factories.ClassFactory.GetInstance[T](Func`1 action)
   --- End of inner exception stack trace ---
   at Terrasoft.Core.Factories.ClassFactory.GetInstance[T](Func`1 action)
   at Terrasoft.Configuration.DevExpressReportGenerator.Generate(UserConnection userConnection, ReportGeneratorConfiguration configuration)
   at Terrasoft.Core.Process.TAIAutoSendOrderLogSummaryMethodsWrapper.ScriptTask1Execute(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessScriptTask.InternalExecute(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessFlowElement.ExecuteItem(ProcessExecutingContext context)
   at Terrasoft.Core.Process.ProcessFlowElement.Execute(ProcessExecutingContext context)

Below is the report generation part of the code -  

//ReportService reportService = new ReportService(userConnection);
//ReportData report = reportService.GenerateDevExpressReport(entitySchemaUId,reportSchemaUId,null,reportParamaters);
 
DevExpressReportGenerator reportGenerator = new DevExpressReportGenerator();
var configuration = new ReportGeneratorConfiguration {
				ReportTemplateId = !string.IsNullOrEmpty(reportSchemaUId) ? new Guid(reportSchemaUId) : Guid.Empty,
				EntitySchemaUId = !string.IsNullOrEmpty(entitySchemaUId) ? new Guid(entitySchemaUId) : Guid.Empty,
				RecordId = !string.IsNullOrEmpty(recordId) ? new Guid(recordId) : Guid.Empty,
				ReportParameters = !string.IsNullOrEmpty(reportParameters)
					? JsonConvert.DeserializeObject&lt;Dictionary&lt;string, object&gt;&gt;(reportParameters)
					: null
			};
ReportData report = reportGenerator.Generate(userConnection, configuration);

I understand it's an old version of the report but I would appreciate if anyone can provide any insights on what I'm missing.

Hello Nirupama, Can you check if the run elements in the background is disabled ? If that is enabled, then the process will not get the User Connection.

Show all comments

I'm trying to pass a Guid from a script task to a subprocess.

Here is the entire process: http://prntscr.com/mc2cmv&nbsp;

The code of the script task is:

 

var pipelineId = Entity.UsrPipelineId;
 
//pass pipelineId to GenerateUBOPositionSubProcess
 
return true;

What would I have to write? The subprocess has a parameter defined that is named PipelineId (http://prntscr.com/mc2ej9).

Like 0

Like

5 comments

You can set process parameter in the script:

Set("PipelineId", pipelineId);

That sets the parameter for the process that contains the script task, but not for a subprocess that is further down the line from the script task (see the first link I included), I thought? Or do processes and subprocesses share parameters?

Dear Jonas,

You can use this coder to pass the value:

UserConnection userConnection = Get<UserConnection>("UserConnection");

IProcessEngine processEngine = userConnection.ProcessEngine;

IProcessExecutor processExecutor = processEngine.ProcessExecutor;

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

int parameter1Value = 100;

nameValues["parameter1"] = parameter1Value.ToString();

processExecutor.Execute("UsrProcessCustom", nameValues);

return true;

Best regards,

Dean

Thank you. I will start testing this today. 

Now I need to know how to get data back from that process. Is that possible?

Dear Jonas,

You can try to add another element in your subprocess and use the same script to pass the values back to the parent process. 

Dean

Show all comments

Hi Community,

This code below gets the Guid of the current user in client side code

Terrasoft.SysValue.CURRENT_USER.value

How about in script task, using C# code what is its equivalent?

 

 

Like 0

Like

4 comments

In a script task you have access to UserConnection. This exposes a  CurrentUser property (which provides an object of type SysUserInfo). 

var currentUser = UserConnection.CurrentUser;
var userId = currentUser.Id;
var userName = currentUser.Name;

BTW If this was code in a source code schema/configuration service, you'd need to get the UserConnection via the AppConnection first:

var appConnection = HttpContext.Current.Application["AppConnection"] as AppConnection;
var currentUser = appConnection.SystemUserConnection.CurrentUser;

 

Ryan Farley,

Thanks Ryan,

Is there any documentation about CurrentUser. I want to know everything about its properties and attributes for future use.

Thanks.

Fulgen Ninofranco,

I don't know of any documentation, it is in Terrasoft.Core.dll, however, the SysUserInfo object inherits from the SysAdminUnit object. This object you can see in the configuration. Search for SysAdminUnit in the configuration and you'll see what is available in the SysUserInfo. The SysUserInfo object itself only adds 5 additional properties for TimeZone, PageRowsCounr, Culture, ClientIP, and DateTimeFormatCode.

Dear Fulgen,

Please use the example mentioned by Ryan, it covers the way you work with UserConnection in Script Task. 

var currentUser = UserConnection.CurrentUser;

For more information on all .Net classes used in the system please see this article:

https://academy.bpmonline.com/api/netcoreapi/7.13.0/index.html#GeneralS…

Also, as for examples of UserConnection usage in web services you can check the examples here:

https://academy.bpmonline.com/documents/technic-sdk/7-13/how-create-cus…

 Regards,

Anastasia

Show all comments

Hello community



I am working with a business process using the process element [Call Web Service].

The web service configuration and the call are working correctly.

The JSON response is similar to:

{

"$ totalResults": 2,

"$ startIndex": 1,

"$ itemsPerPage": 100,

"$ resources": [

     {

      "$ clave": "t6UJ9A000001",

      "$ Static_state": 200,

      "$ etag": "Yi4EmiUg3xw =",

       "Account": {

             "$ clave": "A6UJ9A0001RU",

             "$ uuid": "00000000-0000-0000-0000-000000000000",

           }

      },

      {

      "$ clave": "t6UJ9A00000B",

      "$ Static_state": 200,

"$ etag": "wMpPUtrfgdA =",

"Account": {

"$ clave": "A6UJ9A0001RX",

"$ uuid": "00000000-0000-0000-0000-000000000000",

}

}

]

}



My goal is to iterate the JSON and finally create tickets in BPM with the source information.

Using a pre-configured page I was able to determine that the parameter where the information is returned is [#WS Step.Response body #]

How can I take this value in a Script Task and process the JSON? or what is the correct procedure to do this?

Previously I should be able to take the value of the parameter [#WS Setp.Success #] to determine if the execution was successful

Thank you!

Good weekend

Like 0

Like

1 comments

get/set a parameter value in a business process script task

var parameter1 = Get<Guid>("Parameter1");

Set("Parameter2", parameter1.ToString());

var parameter2 = Get<string>("Parameter2");

get object of type UserConnection

var userConnection = Get<UserConnection>("UserConnection");

Show all comments

I'm creating a process that reads data and then needs to update a text column on that data by appending some new text to the existing string. I can read the data fine but the script task throws a null reference exception. Here is the simplified version of my script:

var programs = Get("ReadDataUserTask1.ResultEntityCollection");

foreach(var program in programs) {
    program.SetColumnValue("Campaign Flags", "Test");
}

return true;

The programs is null when I run the process.

Like 0

Like

7 comments

Dear Scott,

Try another approach to overcome the issue. Please read the collection of the Read Data in the following way: 

 var entities = Get<ICompositeObjectList<ICompositeObject>>("ReadDataUserTask1.ResultCompositeObjectList");

Afterwards proceed further with collection result.

Regards,

Anastasia

Anastasia Botezat,

using trying the above script, when I convert the list to string by doing:

entities.ToString());

I get  - Terrasoft.Common.CompositeObjectList`1[Terrasoft.Common.CompositeObject] (looks like the type and not the value)

Can you help?

Chani Karel,

 

There is no need to cast object to string since you can get the value from some column of the object using GetCompositeObjectColumnValue (in my case I was reading the "Full name" column value from the collection of contacts):

 

string name = GetCompositeObjectColumnValue&lt;string&gt;(contacts, "Name");

and then process the value according to your needs.

 

Best regards,

Oscar

Hi Chani Karel,

I think there are 2 things in your scripts:

1. You ReadDataUserTask1 result could be empty.

var programs = Get&lt;EntityCollection&gt;("ReadDataUserTask1.ResultEntityCollection");

Therefore, before the "foreach Loop", you really need to check if the programs is null or not. Otherwise, you might get the exception as you mentioned.

 

2. Please use the column code instead of column title to set value.

For example, in Contact there is column with code "JobTitle" and title "Full job title". If you need to set the value, you need to use the code "JobTitle".

 

regards,

 

Cheng Gong

Oscar Dylan,

using the tostring method was just to understand why I don't get the values as needed. 

What I need to do is this:

I get a list of 'contact in opportunity' by the read collection of records element. I need to get the contact as lookup  value and not as string (the Id and not name) in order to set parameters with the contacts and send email to them.

How do I do it?

Thank you.

Cheng Gong,

using the tostring method was just to understand why I don't get the values as needed. 

What I need to do is this:

I get a list of 'contact in opportunity' by the read collection of records element. I need to get the contact as lookup  value and not as string (the Id and not name) in order to set parameters with the contacts and send email to them.

How do I do it?

Thank you.

Chani Karel,

How did you end up solving this?

 

Kind regards,

Yosef

Show all comments

Hi Community,

How can I debug a script task from like setting some break point and tracing codes line by line.

Thanks

Like 0

Like

6 comments

See this

Dear Fulgen,

You can use the link provided in the previous comment by Grigory:

https://academy.bpmonline.com/documents/technic-sdk/7-12/working-server…

Since Script Task is the chunk of C# code, it can be treated as other C# code in the system.

The article provides steps to perform debugging, please use them to debug Script Task.

Regards,

Anastasia

Anastasia Botezat,

Hi Anastasia,

When I do download package to file system there is no .cs file under my business process folder, this business process should contain the script task of my business process for me to debug it in visual studio

Dear Fulgen,

I am sorry to hear that you experiences difficulties with this approach. I would like to offer you another approach to debug server code. I hope you will find it more suitable to work with:

https://academy.bpmonline.com/documents/technic-sdk/7-12/server-code-debugging

Regards,

Anastasia

Anastasia Botezat,

Hi Anastasia,

I already done this application setup below

I also made sure that the value of CompilerSourcesTempFolderPath directory is existing. But no schema source code was exported.

 

Dear Fulgen,

Please revert all that you do on the screenshot, this approach is deprecated. Afterwards, please change only one thing from the main article https://academy.bpmonline.com/documents/technic-sdk/7-12/visual-studio-… and this thing is setting:

<fileDesignMode enabled="true" /> in the main Web.config file and <add key="UseStaticFileContent" value="false" />



After that compile the application, and within the compilation following folder will be populated with all of the .cs files that you need:

your_path_to_bpmonline\Terrasoft.WebApp\Terrasoft.Configuration\Autogenerated\Src

Taking the file that you need into the new visual studio library project, you can attach the project to the IIS bpm'online process and debug the file as it described in the old article:

https://academy.bpmonline.com/documents/technic-sdk/7-12/server-code-de…

but skipping the part of the configuration. This will be the simplest approach: To take configuring steps from the new article but debugging from the old one.

Also, you may need to compile the system twice, before and after connecting to the IIS process in order to .cs files be exactly the same, in another case if files will be different, the breakpoints in visual studio will be gray and will not work.

Moreover, try to copy the file to a new project and place breakpoints in them, and try to drag and drop the original file from Terrasoft.WebApp\Terrasoft.Configuration\Autogenerated\Src to the main window of visual studio and place breakpoints in them too, after the attaching to the process and compiling the system, one of the approaches will definitely work for you.

 

Show all comments

Hello community,

I am trying to perform the following command from a Script Task element:

DELETE FROM [dbo].[UsrListDocuments] WHERE [Opportunity] = @P1 AND [Product] = @P2

Currently, the C# code is similar to this:

var opportunityId = Get("Read opportunity product.Opportunity");
var productId = Get("Read opportunity product.Product");
var delete = new Delete(userConnection)
        .From("UsrListDocuments")
        .Where("Opportunity").IsEqual(opportunityId)
        .Where("Product").IsEqual(productId);
        
return true;

Is this accurate? What would be the best practice in this case? The code is not working properly that´s why I am looking for your assistance.

Thanks.

Like 0

Like

2 comments

Hello,

As far as I understood your business goal, you are trying to fetch some parameters via [Read Data] element in your script task and pass it further to the Delete query.



Firstly, you need to get parameters in the [Script Task] from the [Read Data] element.

For the interpreted process the algorithm is the next:

1) Create a business process parameters and map it to the needed Read Data element. You can learn more about business parameters in our guide - https://academy.bpmonline.com/documents/technic-bpms/7-12/how-add-param…

In your example it will be something like:

[#Read opportunity product.First item of resulting collection.Opportunity#] and [#Read opportunity product.First item of resulting collection.Product#]

2) Use business-parameters in your Script-task.

var opportunityId = Get<Guid>("ProcessParam1");

var productId = Get<Guid>("ProcessParam2");

Then you need to get the userConnection in order to pass it in the Delete query:

var userConnection = Get<UserConnection>("UserConnection"); 

After that you can create a delete query:

var delete = new Delete(userConnection)

        .From("UsrListDocuments")

        .Where("Opportunity").IsEqual(opportunityId)

        .Where("Product").IsEqual(productId);

        

And execute it:

 delete.execute();

Tetiana Markova,

Thanks, Thetiana. It worked.

Show all comments