detect if Kofax launched custom module or User - kofax

When the custom module gets launched I can use
if (Environment.UserInteractive)
{
// Run as WinForms app
}
else
{
// Run as service
}
to switch between a background service and a WinForms app. But I can also run the .exe file without launching Kofax.
Is it possible to check if Kofax launched the module? My example code would look like
if (Environment.UserInteractive)
{
// Run as WinForms app
if (Application.LaunchedByKofax)
{
// Do something additional
}
}
else
{
// Run as service
}

The only context in which Kofax Capture launches your custom module is when a user tries to process a batch from Batch Manager, and that batch is currently in the queue for your custom module. If you are referring to something other than that, then you'll need to clarify your question.
When that happens, the path registered for your custom module is called with additional parameters, the most notable of which is -B###, where ### is the decimal batch ID. For more details on this see Kofax KB article 1713, which is old but still applicable for current versions.
Thus you can use a function like this to check for the expected parameters.
public bool LaunchedFromBatchManager()
{
var args = Environment.GetCommandLineArgs();
//args[0] will contain the path to your exe, subsquent items are the actual args
if (args.Count() > 1)
{
// When a user tries to process a batch from batch manager,
// it launches the module with -B###, where ### is the decimal batch ID
// see: http://knowledgebase.kofax.com/faqsearch/results.aspx?QAID=1713
if (args[1].StartsWith("-B"))
{
return true;
}
}
return false;
}

Related

Node.js package script that runs every time a file is changed

I'm developing a node.js package that generates some boilerplate code for me.
I was able to create this package and if I run every module individual it works fine and generates the code as expected.
My idea now is to import this package in another project and have it generate the code.
I have no idea to how to achieve this or even if it's possible.
The perfect solution would be that every time a file changed in a set of folders it would run the package and generate the files but if this isn't possible it would be ok as well to expose or command to manually generate this files.
I have created a script to run the generator script but it only works on the package itself and not when I import it in another project.
Thanks
I think you want the fs.watch() function. It invokes a callback when a file (or directory) changes.
import { watch } from 'fs';
function watchHandler (eventType, filename) {
console.log(`event type is: ${eventType}`) /* 'change' or 'rename' */
if (filename) {
console.log(`filename provided: ${filename}`)
} else {
console.log('filename not provided');
}
}
const options = { persistent: true }
const watcher = fs.watch('the/path/you/want', options, watchHandler)
...
watcher.close()
You can use this from within your nodejs app to invoke watchHandler() for each file involved in your code generation problem.

How can I automate the creation and SFTP transfer of a snapshot in Acumatica?

I would like to create a nightly snapshot of certain tables in my SAAS-hosted Acumatica instance and SFTP the resulting XML file to a given location. (I've created a custom Export Mode option for just the tables of interest.)
I would like to do this process through an Acumatica Automation Schedule, a custom Action that I can call through the API, or an API call to existing Acumatica Actions, or some combination of the above.
However, it doesn't appear that these options are available to me:
Automation Scheduling doesn't support snapshot creation (https://feedback.acumatica.com/ideas/ACU-I-570)
I tried adding the Action to create a snapshot to the web service endpoint, but it doesn't appear that I can pass the parameters I would need to manage the pop-ups
Attempting to create a custom Acumatica button, I'm also to struggling to figure out how to raise and manage the pop-ups.
Once I have the snapshot created, I presume I will need to be able to download it locally in order to SFTP it to my desired location; I haven't gotten far enough to know if I invoke the download snapshot button through the API where the resulting file will go.
June,
When I get stuck with stuff that I am unable to trigger with ReST or other integration techniques I generally turn to Selenium as the path of least resistance. I do want to point out I always err on the side of using selenium as a last resort.
I generally like to use the PowerShell selenium module for stuff like this.
Once you have your script working you can wire it into a standard Windows Scheduler real easy.
It may not be the most elegant way to do it but it will certainly get the job done.
if your interested you can get started with this
https://github.com/adamdriscoll/selenium-powershell/blob/master/README.md
Once you get familiar with it you use the chrome inspection tool to dig into the elements that you need to target. the dialog boxes you are after are often found as iframes within the page.
I can share some of my scripts to help you get started if you want to try this route.
I hope this helps.
Robert
I ended up creating a simple console application since it was more in line with our other applications and I have more familiarity with C# than with PowerShell. Robert, your project was invaluable to figuring out how to reference the trickier elements.
I expect to set up scheduled tasks that will call my application with the method name of each step, with appropriate delays between each -- creating the snapshot takes about 25 minutes, for example. There are separate methods to create the snapshot, download the snapshot, delete the snapshot, and next I'm working on SFTPing the downloaded snapshot to its end destination. I put in sleeps to allow time for the website to catch up; there are Waits and WaitForExpectedCondition methods available but I didn't get into them in this quick and dirty version.
Here's the guts of my code. (I added WebDriver and ChromeDriver to the application via Nuget.)
using System;
using System.Collections.Generic;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Threading;
namespace InfiniteExport
{
class Program
{
static string connectorInfo;
static void Main(string[] args)
{
string method = "";
if (args.Count() >= 1)
{
method = args[0].ToLower();
}
IWebDriver driver = new ChromeDriver();
try
{
switch (method)
{
case "createsnapshot":
Login(driver);
CreateSnapshot(driver);
break;
case "downloadsnapshot":
Login(driver);
DownloadSnapshot(driver);
break;
case "deletesnapshot":
Login(driver);
DeleteSnapshot(driver);
break;
default:
break;
}
}
catch (Exception e)
{
throw e;
}
finally
{
driver.Quit();
}
}
static void Login(IWebDriver driver)
{
//This login actually results in a 404 error because there's no redirect embedded in it, but the login itself is successful and creates the session used by the next method navigation
driver.Navigate().GoToUrl(InfiniteExport.Properties.Settings.Default.BaseAcumaticaURL + "/Frames/Login.aspx");
driver.FindElement(By.Id("form1")).Click();
driver.FindElement(By.Id("txtUser")).SendKeys(InfiniteExport.Properties.Settings.Default.AcumaticaUserName);
driver.FindElement(By.Id("txtPass")).SendKeys(InfiniteExport.Properties.Settings.Default.AcumaticaPassword);
driver.FindElement(By.Id("btnLogin")).Click();
driver.Manage().Window.Maximize();
Thread.Sleep(5000);
}
static void CreateSnapshot(IWebDriver driver)
{
driver.Navigate().GoToUrl(#InfiniteExport.Properties.Settings.Default.BaseAcumaticaURL + "/Main?ScreenId=SM203520&_CompanyID=2");
Thread.Sleep(2000);
driver.SwitchTo().Frame("main");
//Click the #$##%*! unnamed create snapshot button
driver.FindElement(By.CssSelector(".toolsBtn[data-cmd=exportSnapshotCommand]")).Click();
Thread.Sleep(2000);
//Switch to the modal popup to start clicking items on it (this is the "Warning not in maintenance mode" popup)
driver.SwitchTo().ActiveElement();
driver.FindElement(By.Id("messageBox_0")).Click();
Thread.Sleep(2000);
//Switch to the modal popup with the export options
driver.SwitchTo().ActiveElement();
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_frmExportSnapshot_edDescription")).SendKeys("InfiniteExport");
//Select the dropdown option for the InfiniteExport
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_frmExportSnapshot_edExportMode_text")).Click();
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_frmExportSnapshot_edExportMode_text")).SendKeys("InfiniteExport");
Thread.Sleep(2000);
driver.FindElement(By.ClassName("ddSelection")).Click();
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_frmExportSnapshot_chkPrepare")).Click();
//Select the dropdown option for XML
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_frmExportSnapshot_edPrepareMode")).Click();
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_frmExportSnapshot_edPrepareMode_text")).SendKeys("XML");
Thread.Sleep(2000);
driver.FindElement(By.ClassName("ddSelection")).Click();
Thread.Sleep(2000);
//Click the OK button to start the export
driver.FindElement(By.Id("ctl00_phF_pnlExportSnapshot_btnExportSnapshotOK")).Click();
//Wait long enough for the process to start, then quit and come back later to download
Thread.Sleep(10000);
}
static void DownloadSnapshot(IWebDriver driver)
{
driver.Navigate().GoToUrl(#InfiniteExport.Properties.Settings.Default.BaseAcumaticaURL + "/Main?ScreenId=SM203520&_CompanyID=2");
Thread.Sleep(2000);
driver.SwitchTo().Frame("main");
//Unless this is made fancier, it will download the active grid row, which is the most recent snapshot created
driver.FindElement(By.CssSelector(".toolsBtn[data-cmd=downloadSnapshotCommand]")).Click();
Thread.Sleep(10000);
}
static void DeleteSnapshot(IWebDriver driver)
{
driver.Navigate().GoToUrl(#InfiniteExport.Properties.Settings.Default.BaseAcumaticaURL + "/Main?ScreenId=SM203520&_CompanyID=2");
Thread.Sleep(2000);
driver.SwitchTo().Frame("main");
//Unless this is made fancier, it will delete the active grid row, which is the most recent snapshot created
driver.FindElement(By.CssSelector(".toolsBtn[data-cmd=Delete]")).Click();
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".toolsBtn[data-cmd=saveCompanyCommand]")).Click();
Thread.Sleep(10000);
}
}
}

Servicestack OrmLite: Capture PRINT statements from stored procedure

I'm currently writing a console app that kicks off a number of stored procedures in our (Sql Server) database. The app is primarily responsible for executing the procedures, logging events to a number of places, and then some arbitrary work after. We have a nice Data NuGet package out there that integrates with OrmLite / ServiceStack, so I'm trying to use OrmLite as our ORM here as well.
The app itself just takes inputs that include the name of the sproc, and I'm executing them based off that (string) name. The sprocs themselves just move data; the app doesn't need to know the database model (and can't; the models can change).
Since these sprocs do quite a bit of work, the sprocs themselves output logging via PRINT statements. It's my goal to include these PRINTed log messages in the logging of the console app.
Is it possible to capture PRINT messages from a DbConnection command? I can't find any way via the built-in commands to capture this; only errors. Do I have to use ExecuteReader() to get a hold of the DataReader and read them that way?
Any help is appreciated. Thanks!
Enable Debug Logging
If you configure ServiceStack with a debug enabled logger it will log the generated SQL + params to the configured logger.
So you could use the StringBuilderLogFactory to capture the debug logging into a string.
CaptureSqlFilter
OrmLite does have a feature where you can capture the SQL output of a command using the CaptureSqlFilter:
using (var captured = new CaptureSqlFilter())
using (var db = OpenDbConnection())
{
db.Where<Person>(new { Age = 27 });
captured.SqlStatements[0].PrintDump();
}
But this doesn't execute the statement, it only captures it.
Custom Exec Filter
You could potentially use a Custom Exec Filter to execute the command and call a custom function with:
public class CaptureOrmLiteExecFilter : OrmLiteExecFilter
{
public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
{
var holdProvider = OrmLiteConfig.DialectProvider;
var dbCmd = CreateCommand(dbConn);
try
{
return filter(dbCmd);
}
finally
{
MyLog(dbCmd);
DisposeCommand(dbCmd);
OrmLiteConfig.DialectProvider = holdProvider;
}
}
}
//Configure OrmLite to use above Exec filter
OrmLiteConfig.ExecFilter = new CaptureOrmLiteExecFilter();

Electron app installed but doesn't appear in start menu

I've created an app using Electron, and bundled it in an .exe file with electron-builder.
When I run the generated executable, the application starts with the default installation GIF used by electron-builder, as expected.
After the GIF finishes, the app restarts and works properly. It even appears in control panel's programs list.
However, if I look for it in the start menu applications, it isn't there (and searching it by its name only returns the aforementioned .exe installer).
Because of this, once the app is closed, the only way to open it back is running again the installer.
Why does this happen? Is there any way to make it appear with the other programs?
The electron-builder installer (and electron-windows-installer) use Squirrel for handling the installation. Squirrel launches your application on install with arguments that you need to handle. An example can be found on the windows installer github docs
Handling Squirrel Events
Squirrel will spawn your app with command line flags on first run, updates, and uninstalls. it is very important that your app handle these events as early as possible, and quit immediately after handling them. Squirrel will give your app a short amount of time (~15sec) to apply these operations and quit.
The electron-squirrel-startup module will handle the most common events for you, such as managing desktop shortcuts. Just add the following to the top of your main.js and you're good to go:
if (require('electron-squirrel-startup')) return;
You should handle these events in your app's main entry point with something such as:
const app = require('app');
// this should be placed at top of main.js to handle setup events quickly
if (handleSquirrelEvent()) {
// squirrel event handled and app will exit in 1000ms, so don't do anything else
return;
}
function handleSquirrelEvent() {
if (process.argv.length === 1) {
return false;
}
const ChildProcess = require('child_process');
const path = require('path');
const appFolder = path.resolve(process.execPath, '..');
const rootAtomFolder = path.resolve(appFolder, '..');
const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
const exeName = path.basename(process.execPath);
const spawn = function(command, args) {
let spawnedProcess, error;
try {
spawnedProcess = ChildProcess.spawn(command, args, {detached: true});
} catch (error) {}
return spawnedProcess;
};
const spawnUpdate = function(args) {
return spawn(updateDotExe, args);
};
const squirrelEvent = process.argv[1];
switch (squirrelEvent) {
case '--squirrel-install':
case '--squirrel-updated':
// Optionally do things such as:
// - Add your .exe to the PATH
// - Write to the registry for things like file associations and
// explorer context menus
// Install desktop and start menu shortcuts
spawnUpdate(['--createShortcut', exeName]);
setTimeout(app.quit, 1000);
return true;
case '--squirrel-uninstall':
// Undo anything you did in the --squirrel-install and
// --squirrel-updated handlers
// Remove desktop and start menu shortcuts
spawnUpdate(['--removeShortcut', exeName]);
setTimeout(app.quit, 1000);
return true;
case '--squirrel-obsolete':
// This is called on the outgoing version of your app before
// we update to the new version - it's the opposite of
// --squirrel-updated
app.quit();
return true;
}
};
Notice that the first time the installer launches your app, your app will see a --squirrel-firstrun flag. This allows you to do things like showing up a splash screen or presenting a settings UI. Another thing to be aware of is that, since the app is spawned by squirrel and squirrel acquires a file lock during installation, you won't be able to successfully check for app updates till a few seconds later when squirrel releases the lock.
In this example you can see it run Update.exe (a squirrel executable) with the argument --create-shortcut that adds start menu and desktop shortcuts.
It's 2021 and I am still having a very similar problem.
My app installs correctly and with the script above it also successfully adds a Desktop link to my app. BUT: There is no Shortcut being added to the Windows Start Menu.
With the script above this should also be added to the Start Menu, right?
One comment above says:
// Install desktop and start menu shortcuts
spawnUpdate(['--createShortcut', exeName]);
What am I missing? Any hint highly appreciated...
For me it helped to add icon and setupIcon to the package.json file, where the makers, are configured. Before my app didnt show up in the Start menu, and with the maker config as below, it does. I am not sure why though.
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "cellmonitor",
"icon": "favicon.ico",
"setupIcon": "favicon.ico"
}
}
]

Execute node command from UI

I am not very much familiar with nodejs but, I need some guidance in my task. Any help would be appreciated.
I have nodejs file which runs from command line.
filename arguments and that do some operation whatever arguments I have passed.
Now, I have html page and different options to select different operation. Based on selection, I can pass my parameters to any file. that can be any local node js file which calls my another nodejs file internally. Is that possible ? I am not sure about what would be my approach !
I always have to run different command from terminal to execute different task. so, my goal is to reduce that overhead. I can select options from UI and do operations through nodejs file.
I was bored so I decided to try to answer this even though I'm not totally sure it's what you're asking. If you mean you just need to run a node script from a node web app and you normally run that script from the terminal, just require your script and run it programmatically.
Let's pretend this script you run looks like this:
// myscript.js
var task = process.argv[2];
if (!task) {
console.log('Please provide a task.');
return;
}
switch (task.toLowerCase()) {
case 'task1':
console.log('Performed Task 1');
break;
case 'task2':
console.log('Performed Task 2');
break;
default:
console.log('Unrecognized task.');
break;
}
With that you'd normally do something like:
$ node myscript task1
Instead you could modify the script to look like this:
// Define our task logic as functions attached to exports.
// This allows our script to be required by other node apps.
exports.task1 = function () {
console.log('Performed Task 1');
};
exports.task2 = function () {
console.log('Performed Task 2');
};
// If process.argv has more than 2 items then we know
// this is running from the terminal and the third item
// is the task we want to run :)
if (process.argv.length > 2) {
var task = process.argv[2];
if (!task) {
console.error('Please provide a task.');
return;
}
// Check the 3rd command line argument. If it matches a
// task name, invoke the related task function.
if (exports.hasOwnProperty(task)) {
exports[task]();
} else {
console.error('Unrecognized task.');
}
}
Now you can run it from the terminal the same way:
$ node myscript task1
Or you can require it from an application, including a web application:
// app.js
var taskScript = require('./myscript.js');
taskScript.task1();
taskScript.task2();
Click the animated gif for a larger smoother version. Just remember that if a user invokes your task script from your web app via a button or something, the script will be running on the web server and not the user's local machine. That should be obvious but I thought I'd remind you anyway :)
EDIT
I already did the video so I'm not going to redo it, but I just discovered module.parent. The parent property is only populated if your script was loaded from another script via require. This is a better way to test if your script is being run directly from the terminal or not. The way I did it might have problems if you pass an argument in when you start your app.js file, such as --debug. It would try to run a task called "--debug" and then print out "Unrecognized task." to the console when you start your app.
I suggest changing this:
if (process.argv.length > 2) {
To this:
if (!module.parent) {
Reference: Can I know, in node.js, if my script is being run directly or being loaded by another script?

Resources