Algorytm C# - Przykład 1: zmiana statusu dokumentów i wysyłka e-mail
Podsumowanie:W tym przykładzie używane są trzy dodatkowe klasy dostępne w nAxiom (ActionRunner, WebServiceRunner, SqlHelper). Akcja wyszuka wszystkie zgłoszenia, które nie są w statusie Completed a ich termin wykonania przypada w okresie najbliższych 7 dni. Wyszukane zgłoszenia zostaną przeniesione do odpowiedniego statusu. Jeśli akcja zmiany statusu zostanie wykonana poprawnie, zostanie wykonana akcja wysyłki e-mail w celu poinformowania odpowiednich osób.
Zamiast wywoływania akcji zmiany statusu przez żądanie REST API, można zdefiniować akcję zmiany statusu i wykonać ją w kodzie akcji C#.
using System;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using CSharpScript.ActionRunner;
using CSharpScript.SqlRunner;
using CSharpScript.WebServiceRunner;
using CSharpScript.WebServiceRunner.Models;
//gets the JSON data from the model.
var json = JsonConvert.DeserializeObject<Dictionary<string, object>>(Model);
//defines the URL and authentication credentials for the API call.
string _UrlChangeStatus = $"{TenantBaseUrl}/publicapi/Document/ChangeStatus";
string _AuthUrl = $"{TenantBaseUrl}/connect/token";
string _UserName = "jan.nowak";
string _Password = "sTr0nGp@ssw0rd";
string _Scope = "public-api";
string _ClientSecret = "sTr0nGs3cR3t";
string _ClientId = "demo-client";
// gets the ID of the business document, form, and transition for the tickets.
int ticketBusinessDocumentId = (int) await SqlHelper.ExecuteSqlScalar("SELECT Id FROM core.BusinessDocuments WHERE Code='Ticket'");
int ticketFormId = (int) await SqlHelper.ExecuteSqlScalar("SELECT Id FROM core.Forms WHERE Code='Ticket-form'");
int ticketTransitionId = (int) await SqlHelper.ExecuteSqlScalar("SELECT Id FROM core.BusinessTransitions WHERE InternalName = 'MyTransitionInternalName'");
// gets a list of tickets that need to be changed to a different status.
var ticketsToChangeStatus = await SqlHelper.ExecuteSqlQueryRowsToDictionary($"SELECT Id FROM dbo.Ticket WHERE StatusName <> 'Completed' AND DATEDIFF(DAY, GETDATE(), DeadlineDate) < 7 ");
// iterates through the list of tickets and changes their status.
foreach (var ticket in ticketsToChangeStatus)
{
// creates a new RestRequestModel object.
var modelChangeTicketStatus = new RestRequestModel(){
Method = HttpMethod.Post,
AuthType = ApiConnector.Enums.AuthType.OAuth2Password,
AuthUrl = _AuthUrl,
Url = _UrlChangeStatus + $"?documentDefinitionId={ticketBusinessDocumentId}&recordId={ticket["Id"]}&transitionId={ticketTransitionId}&formId={ticketFormId}" ,
UserName = _UserName,
Password = _Password,
ClientId = _ClientId,
ClientSecret = _ClientSecret,
Body = "{}"
};
// makes the API call to change the status of the ticket.
var changeTicketStatusResponse = await RestManager.Instance.ExecuteRequestAsync(modelChangeTicketStatus);
// checks if the API call was successful.
if(changeTicketStatusResponse.IsSuccess == false)
{
// throws an exception if the API call was not successful.
throw new Exception($"Something went wrong: {JsonConvert.SerializeObject(changeTicketStatusResponse.RawResult)}<br>Please, contact with the IT department.<br><a href='mailto: it.support@naxiom.com' style='text-align: center;'>Report an error</a>");
}
// executes a SQL query to get addtional parameters for the email action from the database.
var sqlResult = await SqlHelper.ExecuteSqlQueryRowsToDictionary($"SELECT {ticket["Id"]} AS [TicketId], '[C#] Example Action' AS [EmailTitle]");
// creates a new dictionary to pass to the EmailAction.
var mailActionModel = new Dictionary<string, object>
{
{ "RecordId", null },
{ "Model", JsonConvert.SerializeObject(sqlResult.FirstOrDefault()) },
{ "UserId", UserId },
{ "BusinessDocumentId", null }
};
// runs the EmailAction and gets the result.
var mailSendingResult = await EmailAction.Instance.RunActionAsync({&BaseApp.Actions.BaseModule.Example_Email}, JsonConvert.SerializeObject(mailActionModel));
// checks if the EmailAction was successful.
if (mailSendingResult.IsValid == false)
{
// This code throws an exception if the EmailAction was not successful.
throw new Exception($"Something went wrong: {JsonConvert.SerializeObject(mailSendingResult.ResponseMessages)}<br>PLease, contact with the IT department.<br><a href='mailto: it.support@naxiom.com' style='text-align: center;'>Report an error</a>");
}
}