As part of the Sitecore workflow, how can I get the command name that executed the action? For example,
I have 3 states: Accept, Draft, Review and the Draft and Review both have a custom Email Action that should look at a different dictionary item depending on command that executed (Save or Submit in the drafting state and Approve or Reject in the review state). I would like to use the current workflow state and the command to determine which dictionary item to pull, how can I do that? Here is the function that I'm using.
public void Process(WorkflowPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
var processorItem = args.ProcessorItem;
if (processorItem == null)
{
return;
}
var currentItem = args.DataItem;
var innerItem = processorItem.InnerItem;
var fullPath = innerItem.Paths.FullPath;
var recipient = currentItem.Fields["Primary Email"].Value;
var candidateName = currentItem.Fields["Candidate Name"].Value;
var formName = currentItem.Name;
if (string.IsNullOrEmpty(recipient)) return;
var from = GetText(innerItem, "from", args);
var mailServer = GetText(innerItem, "mail server", args);
var currentWorkflowState = currentItem.Fields[FieldIDs.WorkflowState].Value;
var subject = string.Format(Translate.Text("cb-candidate-submission-subject"), formName);
var message = string.Format(Translate.Text("cb-candidate-submission-body"), candidateName, formName);
Error.Assert(#from.Length > 0, "The 'From' field is not specified in the mail action item: " + fullPath);
Error.Assert(subject.Length > 0,
"The 'Subject' field is not specified in the mail action item: " + fullPath);
Error.Assert(mailServer.Length > 0,
"The 'Mail server' field is not specified in the mail action item: " + fullPath);
var mailMessage = new MailMessage();
mailMessage.To.Add(recipient);
mailMessage.From = new MailAddress(#from);
mailMessage.Subject = subject;
mailMessage.Body = message;
var client = new SmtpClient(mailServer) { EnableSsl = false };
try
{
client.Send(mailMessage);
}
catch (Exception ex)
{
Log.Error("EmailExAction Threw An Exception", ex, this);
}
}
WorkflowPipeleneArgs have public properties: ID NextStateId and WorkflowState PreviousState, Item CommandItem. You can use them to define item state.
WorkflowPipelineArgs have CommandItem , this Item have current state and current command details.
var currentCommandName = arg.CommandItem.Name;
Related
I'm trying to edit a script that was intended to send an email if column D is checked (true) but instead of sending an email, I now want it to send a chat. I've created a webhook for the chat group, and it is sort of working, but it's sending a message on EVERY edit made to the sheet.
I'm just a high school teacher way out of my depth here. If anyone can help me figure out how to fix the script, I'd be quite grateful.
When I associate my function with the on edit trigger it sends a chat for every action. If I use the on open trigger, it does nothing.
Screenshot of code
function myFunction() {
var WebWhooklink = "link to my group chat goes here"
var message = { text: "Student has returned"};
var payload = JSON.stringify(message);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var response = UrlFetchApp.fetch(WebWhooklink, options ).getContentText();
}
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Electronic Hall Pass" ) { //checks that we're on Sheet1 or not
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks that the cell being edited is in column A
var nextCell = r.offset(0, 1);
if( nextCell.getValue() === '' ) //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
}
function onEdit2(e) {
if(e.value != "TRUE" ) return;
e.source.getActiveSheet().getRange(e.range.rowStart,e.range.columnStart+2).setValue(new Date());
}
You may try something like this that checks if the edit was made in Column D (the fourth column):
function onEdit(e){
if(e.range.getColumn()==4){
--> Put your function here
}
}
Thanks so much Martin! That fixed it!
function sendMailEdit(e){
if (e.range.columnStart != 4 || e.value != "TRUE") return;
let sName = e.source.getActiveSheet().getRange(e.range.rowStart,1).getValue();
var WebWhooklink = "webhook link to chat goes here"
var message = { text: "Student has returned"};
var payload = JSON.stringify(message);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var response = UrlFetchApp.fetch(WebWhooklink, options ).getContentText();
}
I'm trying to use the Google.Cloud.RecaptchaEnterprise library to validate captcha requests for the new enterprise key my client has obtained.
string _siteKey = ConfigurationManager.AppSettings["GoogleCaptcha.CheckboxCaptcha.SiteKey"];
string _apiKey = ConfigurationManager.AppSettings["GoogleCaptcha.ApiKey"];
string _projectId = ConfigurationManager.AppSettings["GoogleCaptcha.ProjectId"];
string recaptchaAction = "CreateAccountAssessment";
try {
var appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
string credential_path = appPath + "googlecredentials.json";
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);
RecaptchaEnterpriseServiceClient client =
RecaptchaEnterpriseServiceClient.Create();
CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest()
{
Assessment = new Assessment()
{
Event = new Event()
{
SiteKey = _siteKey,
Token = formResponse,
ExpectedAction = "Create_Account"
},
Name = recaptchaAction,
},
Parent = _projectId
};
Assessment response = client.CreateAssessment(createAssessmentRequest);
if (response.TokenProperties.Valid == false)
{
Sitecore.Diagnostics.Log.Error("The CreateAssessment() call failed " +
"because the token was invalid for the following reason: " +
response.TokenProperties.InvalidReason.ToString(), this);
return "Invalid captcha.";
}
else
{
if (response.Event.ExpectedAction == recaptchaAction)
{
Sitecore.Diagnostics.Log.Error("The reCAPTCHA score for this token is: " +
response.RiskAnalysis.Score.ToString(), this);
return "";
}
else
{
Sitecore.Diagnostics.Log.Error("The action attribute in your reCAPTCHA " +
"tag does not match the action you are expecting to score", this);
return "Invalid captcha.";
}
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("Error validating captcha on " + _url + "; " + ex.Message, this);
return "Unable to connect to captcha service.";
}
As far as I can tell all my properties are correct, but it throws an error on Assessment response = client.CreateAssessment(createAssessmentRequest);:
Status(StatusCode="InvalidArgument", Detail="Request contains an invalid argument.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1621287236.280000000","description":"Error received from peer ipv6:[2607:f8b0:4006:81a::200a]:443","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\surface\call.cc","file_line":1062,"grpc_message":"Request contains an invalid argument.","grpc_status":3}")
I strongly suspect the problem (or at least a problem) is the Parent property of the request.
From the documentation:
The name of the project in which the assessment will be created, in the format "projects/{project}".
... whereas I suspect your project ID is just the ID, rather than the resource name starting with "projects/".
I would recommend using the generated resource name classes as far as possible, with the corresponding properties. So in this case, you'd have:
CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest
{
Assessment = new Assessment
{
Event = new Event
{
SiteKey = _siteKey,
Token = formResponse,
ExpectedAction = "Create_Account"
},
Name = recaptchaAction,
},
ParentAsProjectName = new ProjectName(_projectId)
};
I have a piece of code that was scrounged together from another code that is known working. What it does is searches a column using textfinder for a value, in this case, yesterday's date, if nothing is found, it should send an email.
function findAndSendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FormResponses');
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('AlertDate');
var search = ss2.getRange("B2").getValue(); //cell has yesterday's date
var lastRow = ss.getLastRow();
var range = ss.getRange(1,4,lastRow); //define range for column D, column D contains dates
//find all occurrences of search key in column D and push range to array
var ranges = range.createTextFinder(search).findAll();
if (ranges!==null) {
var message = '';
}else {
var message = 'Test';
}
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EmailGroup").getRange("A1");
var emailAddress = emailRange.getValues();
var subject = 'Subject';
var link = "blahblahblah"
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
}
}
As you see, it should search column D, then, if it finds something, the message variable will be blank, else if it finds nothing, it will send an email to the email addresses chosen. I'm not sure how the results from a textfinder work with this and I think the way it is written is incorrect. Any help is appreciated, unfortunately, I cannot share the document in question as my company doesn't allow sharing outside of the domain. Thank you!
Try this:
You will need to update the sheet names I moved them to end of the line comments
function findAndSendMail() {
var ss=SpreadsheetApp.getActive()
var sh1=ss.getSheetByName('Sheet1');//FormResponses
var sh2=ss.getSheetByName('Sheet2');//AlertDate
var d1=new Date(sh2.getRange("B2").getValue()); //cell has yesterday's date
var d2=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).valueOf();
var rg1 = sh1.getRange(1,4,sh1.getLastRow(),1);
var vA=rg1.getValues().map(function(r){
var dt=new Date(r[0]);
var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
return dtv;
});
if(vA.indexOf(d2)==-1) {
var message='test';
var emailAddress = ss.getSheetByName("Sheet3").getRange("A1").getValue();//EmailGroup
var subject = 'Subject';
var link = "blahblahblah"
}
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
//SpreadsheetApp.getUi().alert('I found something');//just for testing
}
}
This version sends an email if yesterday is not found.
In answer to you last question:
function findAndSendMail() {
var ss=SpreadsheetApp.getActive()
var sh1=ss.getSheetByName('Sheet1');//FormResponses
var sh2=ss.getSheetByName('Sheet2');//AlertDate
var d1=new Date(sh2.getRange("B2").getValue()); //cell has yesterday's date
if(isDate(d1)) {
var d2=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).valueOf();
var rg1 = sh1.getRange(1,4,sh1.getLastRow(),1);
var vA=rg1.getValues().map(function(r){
var dt=new Date(r[0]);
var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
return dtv;
});
if(vA.indexOf(d2)==-1) {
var message='test';
var emailAddress = ss.getSheetByName("Sheet3").getRange("A1").getValue();//EmailGroup
var subject = 'Subject';
var link = "blahblahblah"
}
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
//SpreadsheetApp.getUi().alert('I found something');//just for testing
}
}else{
SpreadsheetApp.getUi().alert('Data is sheet2!B2 is not a date')
return;
}
}
function isDate(date){
return(Object.prototype.toString.call(date) === '[object Date]');
}
I have an app that allows users to log in via facebook, once user enters their credentials - My api request saves the user onto the database and auto-generates a user token(This is unique to each user). In order to display user specific details once user logs in - the token needs to be referenced. I am trying to get this token to the PCL project but it returns null just for the token. When I tried passing another string like name, it passes the correct value. Any help will be much appreciated.Thanks
FacebookRender in droid:
public class FacebookRender : PageRenderer
{
public FacebookRender()
{
CustomerService customerService = new CustomerService();
String error;
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "",
scope: "",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += async (sender, eventArgs) =>
{
try
{
if (eventArgs.IsAuthenticated)
{
await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey");
var accessToken = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["first_name"].ToString().Replace("\"", "");
var surname = obj["last_name"].ToString().Replace("\"", "");
var gender = obj["gender"].ToString().Replace("\"", "");
//var email = obj["email"].ToString().Replace("\"", "");
Customer.Customers cust = new Customer.Customers();
cust.Credentials = new Customer.Credentials();
cust.Name = name;
cust.Surname = surname;
cust.Email = "";
cust.MobilePhone = "";
cust.DOB = DateTime.Now;
cust.Number = "";
cust.City = "";
cust.Region = "";
cust.Country = "";
cust.DeviceToken = "sample";
cust.Credentials.SecretKey = "";
await customerService.AddCustomer(cust);
App.SaveToken(cust.Credentials.Token); - **//This is where I am passing the token**
App.NavigateToProfile(string.Format(name + surname));
}
else
{
App.NavigateToProfile("Invalid Login");
}
}
catch(Exception ex)
{
error = ex.Message;
}
};
activity.StartActivity(auth.GetUI(activity));
}
App.cs
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
public static void NavigateToProfile(string message)
{
App.Current.MainPage = (new Profile(message));
}
static string _Token;
public static string Token
{
get { return _Token; }
}
public static void SaveToken(string token)
{
_Token = token;
}
AboutPage.cs - I am passing the token in a label just to see if it's passing
public partial class About : ContentPage
{
private Label _lbltoken;
public About()
{
//InitializeComponent();
Appearing += (object s, EventArgs a) => {
_lbltoken.Text = App.Token;
};
string tk = App.Token;
_lbltoken = new Label()
{
FontSize = 20,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Text = tk,
};
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.StartAndExpand,
Children = { _lbltoken },
};
Content = stack;
}
}
You can use the MessagingCenter.
Messages may be sent as a result like a button click, a system event or some other incident. Subscribers might be listening in order to change the appearance of the user interface, save data or trigger some other operation.
More Info
I don't really now if its good idea use static fields in App class. Xamarin access all fields with service locator, App.Current.[property] I will suggest you try to change these fields to public
string _Token;
public string Token
{
get { return _Token; }
}
public void SaveToken(string token)
{
_Token = token;
}
and use it with App.Current.SaveToken(token) or App.Current.Token
The query could not be run because the criteria for field '' contained an invalid arithmetic expression
Hi,
I faced some issue when i try to pass a value in Server Script and it keep come out with this error " doesnt support operator sbl-dat-00479". When i try to remove one of my value which is PRS Account No and it successfully come out. My value for PRS Account No = P-35971. Below is my server script.
function Print()
{
try
{
TheApplication().TraceOn("C:\\spool\\PRS SOA.txt", "Allocation", "All");
var Account = "";
var Year = "";
var Period = "";
var LPeriod = "";
var ContactID = "";
var Bookmark = "";
var ReportId = "";
var ReportName = "Customer Portal PRS Statement of Account";
//Active Field
this.BusComp().ActivateField("PRSAccountNo");
this.BusComp().ActivateField("Year2");
this.BusComp().ActivateField("Period2");
this.BusComp().ActivateField("LPeriod");
this.BusComp().ActivateField("CONTACT_ID");
//Get Account Row Id
Account = this.BusComp().GetFieldValue("PRSAccountNo");
Year = this.BusComp().GetFieldValue("Year2");
Period = this.BusComp().GetFieldValue("Period2");
LPeriod = this.BusComp().GetFieldValue("LPeriod");
ContactID = this.BusComp().GetFieldValue("CONTACT_ID");
//Construct Bookmark Query
Bookmark = "'cwa CustPortal PRS SOA Account'.Search = \"([PRS Account No] = '"+ Account +"') AND ([Year] = '"+ Year +"') AND ([Period] = '"+ LPeriod +"') AND ([CONTACT_ID] = '"+ ContactID +"')\"";
TheApplication().Trace("Bookmark: " + Bookmark);
//Retrieve Report Row Id
var boReport = TheApplication().GetBusObject("cwa CustPortal Report Administration");
var bcReport = boReport.GetBusComp("Report Standard Templates");
with(bcReport)
{
ActivateField("Report Name");
SetViewMode(AllView);
ClearToQuery();
SetSearchSpec("Report Name", ReportName);
ExecuteQuery(ForwardOnly);
if(FirstRecord())
{
ReportId = GetFieldValue("Id");
}
}
//Generate BIP Report
var GenReport = TheApplication().GetService("Workflow Process Manager");
var GenInput = TheApplication().NewPropertySet();
var GenOutput = TheApplication().NewPropertySet();
GenInput.SetProperty("ProcessName", "cwa CustPortal Generate BIP Report Workflow");
GenInput.SetProperty("Report Id", ReportId);
GenInput.SetProperty("Bookmark", Bookmark);
GenReport.InvokeMethod("RunProcess", GenInput, GenOutput);
var ErrMsg = GenOutput.GetProperty("Error Message");
if(ErrMsg == "")
{
//BIP Report successful generated, redirect to view report page
TheApplication().GotoView("cwa CustPortal PRS SOA Report View");
}
else
{
Popup(ErrMsg);
return(CancelOperation);
}
TheApplication().TraceOff();
}
catch(e)
{
Popup(e);
}
finally
{
}
}
Code looks ok, would be data issue or calc field logic error.
I think "Year2", "Period2" are Calculated fields & could be returning the special character ("/") leading to render the searchspec incorrectly.