Which handle should I use to initialize my scanner app - asp.net-web-api

I wish to operate a scanner using a windows service hosting a web API.
The reason I am doing so is to be able to operate the scanner from javascript using ajax and I do not wish to use ActiveX.
So I built a Windows Service hosting a Web API.
I tried for the web API to start a scan application (had to bypass the UAC for this) but I run into a consistency issue (sometimes it worked and sometimes not).
So for now the controller of the web API has the code to start scanning built into it (instead of an external application). The problem is that I don`t have a handle to give the twain wrapper (it needs it for the windows message hook).
I tried to take the current process MainWindowHandle and even tried something silly as taking iexplore MainWindowHandle and I get an exception "Error initialising DSM".
As a twain library I use TwainDotNet
The code for doing is:
var p = Process.GetCurrentProcess();
_twain = new Twain(new WinFormsWindowMessageHook(p.MainWindowHandle));
Any idea on a good way to get a handle that will work? as I wrote above I ok with "stealing" another application handle if that will do the job (e.g. iexplore)
The exception is thrown from the TwainDotNet class DataSourceManager constructor in this code:
TwainResult result = Twain32Native.DsmParent(
ApplicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Parent,
Message.OpenDSM,
ref windowHandle);
if (result == TwainResult.Success)
{
...
}
else
{
throw new TwainException("Error initialising DSM: " + result, result);
}
Thanks

Well I found an answer to this one.
I used an ApplicationLoader class code from this URL.
The code I use to get the good handle is:
var processes = Process.GetProcessesByName("iexplore");
if (processes.Length == 0)
{
WriteToLog("ScanController.Run GetProcessesByName returned 0 processes. Something went wrong!!!");
return "ScanController.Run Failed: counlt not get handle to perform scan";
}
var p = processes[0];
var hProcess = ApplicationLoader.OpenProcess(ApplicationLoader.MAXIMUM_ALLOWED, false, (uint)p.Id);
Hope this will help someone.

Related

How to retrieve the XPC service of a file provider extension on macOS?

I have extended my example project from my previous question with an attempt to establish an XPC connection.
In a different project we have successfully implemented the file provider for iOS. The exposed service must be resolved by URLs it is responsible for. On iOS it is the only possibility and on macOS it appears like that, too. Because on macOS the system takes care of managing files there are no URLs except the one which can be resolved through NSFileProviderItemIdentifier.rootContainer.
In the AppDelegate.didFinishLaunching() method I try to retrieve the service like this (see linked code for full reference, I do not want to unnecessarily bloat this question page for now):
let fileManager = FileManager.default
let fileProviderManager = NSFileProviderManager(for: domain)!
fileProviderManager.getUserVisibleURL(for: NSFileProviderItemIdentifier.rootContainer) { url, error in
// [...]
fileManager.getFileProviderServicesForItem(at: url) { list, error in
// list always contains 0 items!
}
}
The delivered list always is empty. However the extension is creating a service source on initialization which creates an NSXPCListener which has an NSXPCListenerDelegate that exports the NSFileProviderReplicatedExtension object on new connections. What am I missing?
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
os_log("XPC listener delegate should accept new connection...")
newConnection.exportedObject = fileProviderExtension
newConnection.exportedInterface = NSXPCInterface(with: SomeProviderServiceInterface.self)
newConnection.remoteObjectInterface = NSXPCInterface(with: SomeProductServiceInterface.self)
newConnection.resume()
return true
}
Suspicious: serviceName of the FileProviderServiceSource never is queried. We are out of ideas why this is not working.
There is a protocol which your extension's principal class can implement, NSFileProviderServicing.
https://developer.apple.com/documentation/fileprovider/nsfileproviderservicing

Winforms Application Fails To Launch [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a winforms application that is installed on multiple computers. Most of the time it works perfectly but for a small subset of users the application fails to launch. The only resolution I have found for this issue is to reinstall the application on the users machine.
I have included screenshots below showing the application working after a successful launch and also a screenshot showing what the user sees when the application fails
Normal Launch:
Failed Launch:
When the application fails, the startup form does not get rendered at all. On the users desktop there is nothing visible at all and the program is not outside of any visible area.
If anyone could provide answers or insight into the following questions it would be much appreciated.
What could cause this problem?
Windows or program related?
How could this be fixed?
I have included code snippets from the startup form below
Starting code:
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.Run(new Timelord());
}
public Timelord()
{
this.InitializeComponent();
this.BringToFront();
this.Focus();
// Displays a date and gets the version of the program
lblDate.Text = DateTime.Now.ToShortDateString();
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (ApplicationDeployment.IsNetworkDeployed)
{
lblVersion.Text = string.Format("v{0}", ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(4));
}
// Loads the comboboxes for selection
this.loadComboUser();
this.loadComboCompany();
this.loadComboTick();
}
I think what is happening is that there is an error being thrown in your Timelord constructor under certain conditions. Since Timelord is the "startup" object for your application, a failure to create its instance properly would cause serious problems. Here is what I would recommend doing to identify those conditions, and to eliminate the issue with the form only being partially created.
I am assuming based on your comment about the program reading from a database that one or more of the following methods perform data access calls to a database
this.loadComboUser();
this.loadComboCompany();
this.loadComboTick();
You typically want to avoid method calls, ESPECIALLY data access calls in a constructor. There are many reasons for this that I won't list here, but this other stackoverflow article explains some of them.
Is it OK to put a database initialization call in a C# constructor?
To correct these issues, implement an eventhandler for the load event and move all of your Timelord constructor code into the Load event handler. The Form.Load event fires after the constructor is complete but before a form is displayed for the first time.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.load?view=netframework-4.7.2
Here is how I would recommend restructuring your Timelord object.
public Timelord()
{
this.InitializeComponent();
}
Private Sub Timelord_Load(sender As Object, e As EventArgs) Handles MyBase.Load
{
Try
{
this.BringToFront();
this.Focus();
// Displays a date and gets the version of the program
lblDate.Text = DateTime.Now.ToShortDateString();
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (ApplicationDeployment.IsNetworkDeployed)
{
lblVersion.Text = string.Format("v{0}", ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(4));
}
// Loads the comboboxes for selection
this.loadComboUser();
this.loadComboCompany();
this.loadComboTick();
}
Catch(Exception ex)
{
MessageBox.Show($"The following error occurred in the Timelord constructor {Environment.NewLine}{ex.Message}")
}
}
Making this change will allow the Timelord constructor to completely create the object, then the Load event will run and load any data into the UI. This way, if an error occurs, you will have at least completely created the Timelord Form and can catch the error.
What could cause this problem?
Your startup object (Timelord()) throwing an error in the constructor, therefore not properly creating object.
Windows or program related?
Program related
How could this be fixed?
Separating your Forms logic so that the only code in the constructor is your instantiation logic.
Implementing Try/Catch blocks to trap errors

Motorola MC65 - EMDK .NET 2.6 - E_SCN_READTIMEOUT using ScanWait()

I'm looking to integrate the Barcode2 class in the EDMK 2.6 library into our existing Barcode scanning interface.
I've wired the example code up to our interface method StartScan() and always get E_SCN_READTIMEOUT as the result even though the code seems to be responding to the scan. (the breakpoint at if (scan.Result == Results.SUCCESS) is hit in response to the scan
public void StartScan()
{
if (!barcode.IsScanPending)
{
ScanData scan = barcode.ScanWait(2000); // 2 second timeout
if (scan.Result == Results.SUCCESS)
{
if (scan.IsText)
{
textbox1.Text = scan.Text;
}
}
}
}
The result is always E_SCN_READTIMEOUT, I suspect this may be a conflict with DataWedge 3.4 running on the device, but the functionality of the scanner and triggers seem to be dependent on it.
Getting barcode scans to the clipboard using DataWedge is not an option for us, is there a way to get the library to function despite DataWedge(assuming that is causing the read timeouts)?
The DataWedge application did need to be disabled, (this can be done programmatically via the datawedge API from Motorola, Thanks Abdel for the hint here!).
https://docs.symbol.com/ReleaseNotes/Release%20Notes%20-%20DataWedge_3.3.htm
A little background on our Windows Mobile application for reference, we have a hardware singleton that contains interfaces for all hardware components and loads related types and assemblies via reflection. If we referenced types directly the code above worked.
The end solution ended up being to use the Symbol.Barcode library instead of Symbol.Barcode2.

How to Program xulrunner application to display output file or command line?

My question is in response to this article
https://developer.mozilla.org/En/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL
I have downloaded and configured the xulrunner the only problem I'm getting to run javascript given in the link to display it output. Using xulrunner i want to know how can i produce an output as a headerless command-line program not gui.
var httpRequest = Components.classes["#mozilla.org/xmlextr/xmlhttprequest;1"].createInstance();
// Disable alert popups on SSL error
httpRequest.mozBackgroundRequest = true;
httpRequest.open("GET", "https://developer.mozilla.org/", true);
httpRequest.onreadystatechange = function (aEvt) {
if (httpRequest.readyState == 4) {
// Print security state of request
dumpSecurityInfo(httpRequest.channel);
}
};
httpRequest.send(null);
In the above code taken from the same link i want to see the output of function on my command screen or even a writing the information to file would do.
Do i have to change something in *.xul file extension.? I'm new to using xulrunner some help would be very helpful for me.
To print something to the console you use the dump() function. If your code runs in the context of a window you will need to change browser.dom.window.dump.enabled preference to true. XPCOM components can simply call dump() without changing this preference.

Can you invoke a control rather than launch an app for coded ui tests?

I have code such that:
[CodedUITest]
public class CodedUITest1
{
[TestMethod]
public void CodedUITestMethod1( )
{
using(var dlg = new MyWinForm( ))
{
dlg.Show();
System.Threading.Thread.Sleep(2000);
this.UIMap.AssertMethod1( );
this.UIMap.RecordedMethod1( );
this.UIMap.AssertMethod2( );
}
}
}
The code was running fine when I manually launched the app(before invoking the test) without the using clause to directly create the control.
I'd like to just use a reference to create an instance of the control and go from there instead of relying on trying to determine a path to the executable and opening it. The app just gets stuck with a ContextSwitchDeadlock.
Is there a way to do coded-Ui tests without doing a process launch? (using the reference and creating the control in the test code) or is there something wrong with the way I'm trying to do it?
It might be possible if you invoke the coded ui test portions (this.UIMap...) on a separate thread. But the way you have it now, they are both on the same thread, so you are going to get deadlocked.

Resources