Kentico 11 Scheduled Tasks will not run in Custom Classes - scheduled-tasks

I have built 2 custom scheduled tasks under my 'Site1' on an instance of Kentico 11. There are several scheduled tasks running under 'Site1'. Most run code from Kentico's CMS libraries such as CMS.Membership.DeleteNonActivatedUser.
My 2 Custom Scheduled tasks reside in the App_Code folder.
using CMS;
using CMS.EventLog;
using CMS.Scheduler;
using System;
[assembly: CMS.AssemblyDiscoverable]
[assembly: RegisterCustomClass("CustomTask1", typeof(namespaceName.CustomTask1))]
[assembly: RegisterCustomClass("CustomTask2", typeof(namespaceName.CustomTask2))]
namespace namespaceName
{
public class CustomTask1 : ITask
{
public string Execute(TaskInfo task)
{
try
{
EventLogProvider.LogEvent(EventType.INFORMATION, "CustomTask1", "Task Begin", "Task is working.");
}
catch (Exception ex)
{
EventLogProvider.LogEvent(EventType.ERROR, "CustomTask1", "Task Error", "Task threw exception: " + ex.Message);
}
return null;
}
}
public class CustomTask2 : ITask
{
public string Execute(TaskInfo task)
{
try
{
EventLogProvider.LogEvent(EventType.INFORMATION, "CustomTask2", "Task Begin", "Task is working.");
}
catch (Exception ex)
{
EventLogProvider.LogEvent(EventType.ERROR, "CustomTask2", "Task Error", "Task threw exception: " + ex.Message);
}
return null;
}
}
}
My CustomTask1 and CustomTask2 appear in the Class dropdown list in the Kentico Task Scheduler. I've set both Tasks up to run every day at 6:00 AM. and the Enabled checkbox is checked. none of the checkboxes below are checked. When I click the green triangle on the task list page I get the popup message that says it's running. But nothing is logged in the event logs and neither the last run datetime nor the run counter change.
Does anybody have any idea what is causing this? I have multiple custom scheduled tasks running in a different instance of Kentico and they are working fine, but I cannot get this instance to run my custom tasks.
Any ideas?

You shouldn't need this in version 11:
[assembly: CMS.AssemblyDiscoverable]
If you look into the Event Log after your site restarts, can you see the AppStart event that is loading the modules when the system restarts? If not your app may not be registering that custom code. At that point, it may be worth building that code locally and seeing if there are any errors.

Related

Apache Shiro; SecurityUtils.getSubject() for a schedule user?

I want to implement the following scenario:
I have a EJB scheduler, which should run every 1 minute.
My issue is the following:
I need a login for the user, who execute the schedule. This should be a system user. There will be no login via GUI.
How can I login this user and execute further task?
Currently I´m trying in my class:
#Singleton
#LocalBean
#Startup
public class Scheduler {
public void startSchedule() {
Subject currentUserShiro = SecurityUtils..getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("test#domain.com", "test1234");
currentUserShiro.login(token);
In one of my function, I check e.g. for the permission:
SecurityUtils.getSubject().isPermitted("billingInvoice:create")
I´m getting currently the following issue:
No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
Any idea?
Code update:
private void addScheduleToList(ScheduleExecution scheduleExecution) throws UnknownHostException {
synchronized (this) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-web.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = new Subject.Builder().buildSubject();
Runnable myRunnable = null;
subject.execute(myRunnable = new Runnable() {
#Override
public void run() {
// Add tasks
executeAction(scheduleExecution);
}
});
//////
schedulingService.addTaskToExecutor(taskId, myRunnable, 0);
}
}
I´m gettig now not anymore the issue message which I got initialy, but it seems I´m getting PermissionException, because the user has not the permission? If I check the Subject object, this object is not authenticated. This Subject object needs full permission. How can I do this?
SecurityUtils.getSubject().isPermitted("billingInvoice:create") == false
You have a couple of options.
Move your permission checking to your web-based methods, this moves the permission checkout outside of your scheduled task.
(this isn't always possible and since you are asking the question, I'm assuming you want the 2nd option)
You need to execute your task in the context of a user. Create a new Subject using a SubjectBuilder and then call the execute with a runnable from your task.
See https://shiro.apache.org/subject.html specifically the "Thread Association" section.

Breakpoints in NUnit and stopping Debugging - How to kill a Test?

My apologies, it is an odd use case but please bear with me.
I have a simple TestFixture (as shown below) that outside of calling a PrimeService to check whether or not a number is prime, logs to a file whenever a routine is hit (ie. OneTimeSetup, Setup, OneTimeTearDown etc.)
Can someone please explain to me why If I run the following scenario, the TestFixture runs in it's entirety?
I place a breakpoint in my Test right before my Assert.
I start a "Debug Tests" process in VS (2019)
When the test pauses (and it will on the first test naturally), I press the "Stop Debugging" button (shift F5)
If I go and open my log file, I will see that all 3 tests ran, as did the TearDowns and final Teardown.
My apologies, I just want to understand what is going on under the hood, and whether or not there is a way to kill a paused Test run.
Thanks.
[TestFixture]
public class PrimeService_IsPrimeShould
{
private NerdAnalysis.PrimeService _primeService;
private System.IO.StreamWriter file;
[OneTimeSetUp]
public void OneTimeSetup()
{
file = new System.IO.StreamWriter(#"C:\Users\Fozzy Bear\source\repos\NunitTutorial\MyFile.txt");
file.WriteLine("One time SetUp");
}
[SetUp]
public void Setup()
{
_primeService = new NerdAnalysis.PrimeService();
file.WriteLine("Setup");
}
[TestCase(-1)]
[TestCase(0)]
[TestCase(1)]
public void IsPrime_lessthan2_pass(int value)
{
file.WriteLine("Running test for value " + value);
var result = _primeService.IsPrime(value);
Assert.IsFalse(result, "${ value} should not be prime");
var breakLine = "break";
Assert.Pass();
}
[OneTimeTearDown]
public void FinalTearDown() {
file.WriteLine("Final Teardown");
file.Close();
file.Dispose();
}
[TearDown]
public void TearDown()
{
file.WriteLine("Tear down");
}
from http://msdn.microsoft.com/en-us/library/406kfbs1.aspx
Stop Debugging terminates the process you are debugging if the program
was launched from Visual Studio. If you attached to the process,
instead of launching it from Visual Studio, the process continues
running. If you want to terminate attached processes, you can
terminate a single process from the Processes window or terminate all
attached process with the Terminate All command.

Purging workflow after couple minutes

I have a Workflow step which if meet issues throw WorkflowException with a message and stacktrace, in effect - blocks whole workflow launcher with the payload. Finally, the workflow is indefinitely in the RUNNING state and does not handle any updates for blocked payload. This situation requires admin action to manually terminate the workflow.
There is how the simple workflow looks:
#Service
#Component
#Properties({
#Property(name = Constants.SERVICE_DESCRIPTION, value = "Workflow"),
#Property(name = "process.label", value = "Workflow Step") })
public class WorkflowStep implements WorkflowProcess {
#Override
public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap metaDataMap)throws WorkflowException {
try {
... doing some stuff ...
} catch (Exception e) {
throw new WorkflowException(e.getMessage(), e);
}
}
}
I want to check after i.e 2 minutes if the workflow is COMPLETED if not - terminate them to unblock the payload and after upload the next asset into this path - again handle by the workflow.
Any idea how to solve it without using CRON Scheduler?
If you catch the exception, why don't you terminate the workflow right then instead of throwing a WorkflowException?
You could log whatever you want, handle the error and then terminate...
BR,
Oliver

How can I force a build process to fail through a Unity editor script?

I want to force the build process to fail if some validation conditions are not met.
I've tried using an IPreprocessBuildWithReport with no success:
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
public class BuildProcessor : IPreprocessBuildWithReport
{
public int callbackOrder => 0;
public void OnPreprocessBuild(BuildReport report)
{
// Attempt 1
// Does not compile because the 'BuildSummary.result' is read only
report.summary.result = BuildResult.Failed;
// Attempt 2
// Causes a log in the Unity editor, but the build still succeeds
throw new BuildFailedException("Forced fail");
}
}
Is there any way to programmatically force the build process to fail?
I'm using Unity 2018.3.8f1.
As of 2019.2.14f1, the correct way to stop the build is to throw a BuildFailedException.
Other exception types do not interrupt the build.
Derived exception types do not interrupt the build.
Logging errors most certainly do not interrupt the build.
This is how Unity handles exceptions in PostProcessPlayer:
try
{
postprocessor.PostProcess(args, out props);
}
catch (System.Exception e)
{
// Rethrow exceptions during build postprocessing as BuildFailedException, so we don't pretend the build was fine.
throw new UnityEditor.Build.BuildFailedException(e);
}
Just for clarity, this will NOT stop the build.:
// This is not precisely a BuildFailedException. So the build will go on and succeed.
throw new CustomBuildFailedException();
...
public class CustomBuildFailedException: BuildException() {}
You can use OnValidate() which seems to be exactly what you're looking for.
Let's say you want to make sure a reference to a UI Text component is not null before building, in the script that should have the text reference, you add
private void OnValidate()
{
if (text == null)
{
Debug.LogError("Text reference is null!");
}
}
Having Debug.LogError calls during the build process actually cause the build to fail.

Eclipse (JDT) - performFinish method in wizard

I need to do something with wizards in Eclipse so I checked JDT how they have implemented wizards and found this weird code I don't understand.
It ignores the wizard scheduling rule (returned from getSchedulingRule) in case the code is called from already executing Job (it uses the scheduling rule of that Job). So if wizard needs the scheduling rule of entire workspace but the current thread is already executing any job, than the scheduling rule of this job is used instead, which can cause problems when the new runnable is executed in workspace. I added some comments to code so it is more clear.
Could any Eclipse expert explain why the try block is implemented as is (not just using getSchedulingRule)?
NewElementWizard
/**
* Returns the scheduling rule for creating the element.
* #return returns the scheduling rule
*/
protected ISchedulingRule getSchedulingRule() {
return ResourcesPlugin.getWorkspace().getRoot(); // look all by default
}
/*
* #see Wizard#performFinish
*/
#Override
public boolean performFinish() {
IWorkspaceRunnable op= new IWorkspaceRunnable() {
#Override
public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
try {
finishPage(monitor);
} catch (InterruptedException e) {
throw new OperationCanceledException(e.getMessage());
}
}
};
try {
//TODO: i need explanation of this block. Wizard should be used
// from UI thread, so the code Job.getJobManager().currentJob()
// means that there is possible Job currently executed by UI thread.
// Ok now if there is a job, use its scheduling rule ignoring getSchedulingRule.
// This could be maybe to force that this new runnable isn't executed until this thread finishes
// its current Job. Okb but if the current Job rule isn't so powerfull as this wizard needs, what than?
// It will cause error when executing op, because the runnable will not have enough access
// cause ignoring getSchedulingRule...
ISchedulingRule rule= null;
Job job= Job.getJobManager().currentJob();
if (job != null)
rule= job.getRule();
IRunnableWithProgress runnable= null;
if (rule != null)
runnable= new WorkbenchRunnableAdapter(op, rule, true);
else
runnable= new WorkbenchRunnableAdapter(op, getSchedulingRule());
getContainer().run(canRunForked(), true, runnable);
} catch (InvocationTargetException e) {
handleFinishException(getShell(), e);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
I'm not sure I can explain all of this but a key thing to note is that
Job.getJobManager().currentJob();
only returns the current job in the current thread. Since performFinish is normally run in the UI thread this would not be an ordinary background job. UIJob jobs run in the UI thread. It looks to me like this code is trying to pick up the rule from some UI job that the wizard or associated code has already started.
The true arguments on the call:
new WorkbenchRunnableAdapter(op, rule, true)
will cause WorkbenchRunnableAdapter to call
Job.getJobManager().transferRule(fRule, thread);
if the thread changes. I think this means the code is trying to keep the same rule in use throughout the execution of the runnable and whatever job was previously running.