CoreScanner errors on client - c#

I have a C# application that uses the CoreScanner.dll and SNAPI API. Everything works fine on my development computer but once I install the application on a client PC it gives a few errors.
Retrieving the COM class factory for component with CLSID {} failed due to the following error: 80080005 or Creating an instance of the COM component with CLSID {} from the IClassFactory failed due to the following error: 80010108.
And if I dont get either of those errors, I can back Object reference not set to an instance of an object when I call one of the scanner methods.
try
{
try
{
cCoreScanner = (CCoreScannerClass)Activator.CreateInstance(typeof(CCoreScannerClass));
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - Scanner Created");
}
}
short[] scannertTypes = new short[1];
scannertTypes[0] = 1;
short numberOfScannerTypes = 1;
int[] connectedScannerList = new int[255];
try
{
cCoreScanner.Open(0, scannertTypes, numberOfScannerTypes, out status);
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - Scanner Open " + status.ToString());
}
}
try
{
cCoreScanner.GetScanners(out numberOfScannerTypes, connectedScannerList, out outXML, out status);
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - Get Scanners " + status.ToString());
}
}
try
{
xmlDoc = new XmlDocument();
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - XML Create");
}
}
try
{
xmlDoc.LoadXml(outXML);
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - XML Load");
}
}
try
{
scannerID = xmlDoc.DocumentElement.GetElementsByTagName("scannerID").Item(0).InnerText;
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - Get ScannerID");
}
}
try
{
cCoreScanner.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(onBarcodeScan);
inXML = "<inArgs>" +
"<scannerID>" + scannerID + "</scannerID>" +
"</inArgs>";
cCoreScanner.ExecCommand(2014, inXML, out outXML, out status);
opCode = 1001;
inXML = "<inArgs>" +
"<cmdArgs>" +
"<arg-int>1</arg-int>" + // Number of events you want to subscribe
"<arg-int>1</arg-int>" + // Comma separated event IDs
"</cmdArgs>" +
"</inArgs>";
cCoreScanner.ExecCommand(opCode, ref inXML, out outXML, out status);
}
catch (Exception e)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(e, "Setup Scanner - Splash Screen - Enable Scanner, Subscribe to barcode event");
}
}
}
catch (Exception ex)
{
using (LogManager lm = new LogManager())
{
lm.WriteErrorTextLog(ex, "Setup Scanner - Splash Screen");
}
}
I'm not sure where I am going wrong. I have the DLL registered, the SNAPI driver is installed on the client, and I've used the 123Scan utility to set the scanner up for SNAPI input. The client is a Win 7 64 bit, but I've also been testing on a Win XP and getting the same results. Developing on Win 7 32 bit, only difference is my computer as the SDK on it while the others don't.
Update: I finally found the CoreScanner driver on the Motorola website, however the 80010108 error will still happen, but if you restart the application, everything loads fine. Not 100% sure why its failing still but at least it works until the application closes.
Update 2: It seems only to fail after the application is re-installed. After that it will close / open just fine with no errors. Still have no clue has to why it doesn't work the 1st time but at least it works after that.

Related

Unable to connect Bluetooth device using c#

I'm using 32 feet library to develop Bluetooth communication WPF app, and able to pair the device but not working to connect it and ended up with an exception like below.
Note: I've tried to connect the devices like my mobile and my PC, but both are giving the same errors as explained below.
I've seen somewhere about this issue and they mentioned like, this issue may be because of 32 feet library is not compatible with the Bluetooth device that I've in my PC.
But actually, I've tested this in some other PC's which are running with Windows 7 OS - 64 bit and getting the same error message.
Anyone help me out. Thank you.
Error Message: The requested address is not valid in its context ECD09F51114A:0000110100001000800000805f9b34fb
My code sample:
Guid uId = new Guid("0000110E-0000-1000-8000-00805f9b34fb");
bool receiverStarted = false;
private List<BluetoothDeviceInfo> deviceList;
private List<string> deviceNames;
private BluetoothDeviceInfo deviceInfo;
private string myPin = "1234";
private BluetoothClient sender;
private void BtnScan_Click(object sender, RoutedEventArgs e)
{
ScanAvailableDevices();
}
private void ScanAvailableDevices()
{
lstAvailableDevices.ItemsSource = null;
lstAvailableDevices.Items.Clear();
deviceList.Clear();
deviceNames.Clear();
Thread senderThread = new Thread(new ThreadStart(Scan));
senderThread.Start();
}
private void Scan()
{
UpdateStatus("Starting scan...");
sender = new BluetoothClient();
availableDevices = sender.DiscoverDevicesInRange();
UpdateStatus("Scan completed.");
UpdateStatus(availableDevices.Length.ToString() + " device(s) discovered");
foreach(BluetoothDeviceInfo device in availableDevices)
{
deviceList.Add(device);
deviceNames.Add(device.DeviceName);
}
UpdateAvailableDevices();
}
private void UpdateAvailableDevices()
{
Func<int> devicesDelegate = delegate ()
{
lstAvailableDevices.ItemsSource = deviceNames;
return 0;
};
Dispatcher.BeginInvoke((Action)(() =>
{
devicesDelegate.Invoke();
}));
}
private void PairDevice()
{
deviceInfo = deviceList[lstAvailableDevices.SelectedIndex];
if (CanPair())
{
UpdateStatus("Device paired..");
UpdateStatus("Starting to connect the device");
Thread senderThread = new Thread(new ThreadStart(SenderConnectThread));
senderThread.Start();
}
}
private bool CanPair()
{
if(!deviceInfo.Authenticated)
{
if(!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress,myPin))
{
return false;
}
}
return true;
}
private void LstAvailableDevices_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
deviceInfo = deviceList[lstAvailableDevices.SelectedIndex];
UpdateStatus(deviceInfo.DeviceName + " was selected, attempting connect");
if (CanPair())
{
UpdateStatus("Device paired..");
UpdateStatus("Starting connect thread");
Thread senderThread = new Thread(new ThreadStart(ClientConnectThread));
senderThread.Start();
}
else
{
UpdateStatus("Pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient sender = new BluetoothClient();
BluetoothAddress address = deviceInfo.DeviceAddress;
//sender.SetPin(deviceInfo.DeviceAddress, myPin);
var endPoint = new BluetoothEndPoint(address, uId);
sender.Connect(endPoint);
//Another way that I've tried
BluetoothClient client = new BluetoothClient();
UpdateStatus("Attempting connect");
//client.Connect(deviceInfo.DeviceAddress, uId);
client.BeginConnect(deviceInfo.DeviceAddress, uId, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient senderE = (BluetoothClient)result.AsyncState;
senderE.EndConnect(result);
Stream stream = senderE.GetStream();
while (true)
{
while (!ready) ;
byte[] message = Encoding.ASCII.GetBytes(txtSenderMessage.Text);
stream.Write(message, 0, message.Length);
}
}
There are libraries in UWP where you can easily make a connection between your desktop and other devices , you can easily handle the Bluetooth Adapter.
There are multiple downloads for 32 feet
Try these
Downloading
https://github.com/inthehand/32feet
Downloads are available here on the Downloads tab. Packages are also available at NuGet:-
InTheHand.Devices.Bluetooth - Modern (v4.x) - Preview NuGet version
32feet.NET - Legacy (v3.x) NuGet version
32feet.NET.Phone - Windows Phone NuGet version
InTheHand.Devices.Enumeration (Windows 8 / Windows Phone Device Pickers) NuGet version
Folks, I'm able to pair and connect it using the same application running in different PC and acting it as a server. Earlier I've tried this without having the same application running in the target PC and thus it's giving the error that I mentioned above.
Thanks guys for your time and support.

IOException : The port `\\.\COM3' does not exist

I am trying to Open a SerialPort in unity. It is working in editor and mono build. But when I build the game with iL2CPP scripting backend. It is throwing an exception with message The port \\.\COM3 does not exist.
Is this something related to Unity IL2CPP build?
Unity player settings:
Scripting Runtime Version: .Net 4.x Equivalent
API compatibility Level: .NET 4.x
public void OpenSerialPort()
{
try
{
string ComPort = #"\\.\COM3"; //I even tried "COM3"
int BaudRate = 9600;
// Initialise the serial port
SerialPort = new SerialPort(ComPort, BaudRate);
SerialPort.ReadTimeout = ReadTimeout;
SerialPort.WriteTimeout = WriteTimeout;
SerialPort.DtrEnable = true;
SerialPort.RtsEnable = true;
// Open the serial port
SerialPort.Open();
Debug.LogError("SerialPort successfully opened!");
}
catch (UnauthorizedAccessException ex)
{
// Failed to open com port or start serial thread
Debug.LogError("UnauthorizedAccessException: " + ex.Message.ToString());
}
catch (ArgumentOutOfRangeException ex)
{
// Failed to open com port or start serial thread
Debug.LogError("ArgumentOutOfRangeException: " + ex.Message.ToString());
}
catch (ArgumentException ex)
{
// Failed to open com port or start serial thread
Debug.LogError("ArgumentException : " + ex.Message.ToString());
}
catch (InvalidOperationException ex)
{
// Failed to open com port or start serial thread
Debug.LogError("ArgumentException : " + ex.Message.ToString());
}
catch (IOException ex)
{
// Failed to open com port or start serial thread
Debug.LogError("IOException : " + ex.Message.ToString());
}
}

ClickOnce + Restart = Opens Browser?

I'm deploying a ClickOnce Application and want to restart the application after it was updated. Therefore I wrote following code:
private async void updateCheck()
{
using (var releaser = await _asyncLock.LockAsync())
{
UpdateCheckInfo info = null;
bool updateAvailable = false;
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
ad.UpdateCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Ad_UpdateCompleted);
try
{
updateAvailable = ad.CheckForUpdate(false);
info = ad.CheckForDetailedUpdate();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
return;
}
catch (InvalidDeploymentException ide)
{
MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
return;
}
catch (InvalidOperationException ioe)
{
MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
return;
}
if (/*info.UpdateAvailable*/ updateAvailable)
{
Boolean doUpdate = true;
if (!info.IsUpdateRequired)
{
MessageBoxResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButton.OKCancel);
if (!(MessageBoxResult.OK == dr))
{
doUpdate = false;
}
}
else
{
// Display a message that the app MUST reboot. Display the minimum required version.
MessageBox.Show("This application has detected a mandatory update from your current " +
"version to version " + info.MinimumRequiredVersion.ToString() +
". The application will now install the update and restart.",
"Update Available", MessageBoxButton.OK,
MessageBoxImage.Information);
}
if (doUpdate)
{
try
{
//ad.Update();
ad.UpdateAsync();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
return;
}
}
}
}
}
}
private void Ad_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("The application has been upgraded, and will now restart.");
String ApplicationEntryPoint = ApplicationDeployment.CurrentDeployment.UpdatedApplicationFullName;
Process.Start(ApplicationEntryPoint);
Application.Current.Shutdown();
}
}
Unfortunate in UpdatedApplicationFullName a URL to the Website where the deployment packages are stored. So Process.Start(ApplicationEntryPoint) opens a Browser Window and tries to download the package once again.
The behaviour I want is that the Process.Start(...) opens the new updated application.
Has anyone an idea what I'm doing wrong?
Thanks.

C# .net WebBrowser does not display page (Browser is not up to date)

i'm trying to do a mini-bot for Ogame.
I run my WebBrowser class which says it is IE9 (WebBrowser.Version).
When I execute this:
wb.Navigate(www.ogame.com.us);
And it says:
"Your browser is not up to date."
However when I launch the page on Internet Explorer it DO displays the site.
Is it IE9 the WebBrowser embedded in VisualStudio '12 with the .NET framework 4.5? Because I don't get it.
Any solutions?
Thanks in advance.
Your application needs to emulate a different version of IE.
This is done via the registry.
internal class Helper
{
public static void SetBrowserEmulation(
string programName, IE browserVersion)
{
if (string.IsNullOrEmpty(programName))
{
programName = AppDomain.CurrentDomain.FriendlyName;
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Internet Explorer\\Main" +
"\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
if (regKey != null)
{
try
{
regKey.SetValue(programName, browserVersion,
RegistryValueKind.DWord);
}
catch (Exception ex)
{
throw new Exception("Error writing to the registry", ex);
}
}
else
{
try
{
regKey = Registry.CurrentUser.OpenSubKey("Software" +
"\\Microsoft\\Internet Explorer\\Main" +
"\\FeatureControl", true);
regKey.CreateSubKey("FEATURE_BROWSER_EMULATION");
regKey.SetValue(programName, browserVersion,
RegistryValueKind.DWord);
}
catch (Exception ex)
{
throw new Exception("Error accessing the registry", ex);
}
}
}
}
}
internal enum IE
{
IE7 = 7000,
IE8 = 8000,
IE8StandardsMode = 8888,
IE9 = 9000,
IE9StandardsMode = 9999,
IE10 = 10000,
IE10StandardsMode = 10001
}
Calling this method.
Helper.SetBrowserEmulation(AppDomain.CurrentDomain.FriendlyName, IE.IE10);
You need restart your program.

C# Serial Port communication issue

I have a problem with a small C# application.
The application has to connect through a serial port to a bar code scanner which reads a Data Matrix code. The Data Matrix code represents an array of bytes which is a zip archive. I read a lot about the way SerialPort.DataReceived work but I can't find an elegant solution to my problem. And the application should work with different bar code scanners so i can't make it scanner specific. Here is some of my code:
using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using Ionic.Zip;
namespace SIUI_PE
{
public partial class Form1 : Form
{
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
return;
}
_serialPort.Handshake = Handshake.None;
_serialPort.ReadBufferSize = 10000;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
_serialPort.Open();
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[10000];
_serialPort.Read(data, 0, 10000);
File.WriteAllBytes(Directory.GetCurrentDirectory() + "/temp/fis.zip", data);
try
{
using (ZipFile zip = ZipFile.Read(Directory.GetCurrentDirectory() + "/temp/fis.zip"))
{
foreach (ZipEntry ZE in zip)
{
ZE.Extract(Directory.GetCurrentDirectory() + "/temp");
}
}
File.Delete(Directory.GetCurrentDirectory() + "/temp/fis.zip");
}
catch (Exception ex1)
{
MessageBox.Show("Corrupt Archive: " + ex1.ToString());
}
}
}
}
So my question is: How can I know that I read all the bytes the scanner sent?
The code I've got for reading barcode data, which has been working flawlessly in production for several years looks like this:
Note, my app has to read standard UPC barcodes as well as GS1 DataBar, so there's a bit of code you may not need...
The key line in this is:
string ScanData = ScannerPort.ReadExisting();
which is found in the DoScan section, and simply reads the scan data as a string. It bypasses the need to know how many bytes are sent, and makes the rest of the code easier to deal with.
// This snippet is in the Form_Load event, and it initializes teh scanner
InitializeScanner();
ScannerPort.ReadExisting();
System.Threading.Thread.Sleep(1000);
// ens snippet from Form_Load.
this.ScannerPort.DataReceived += new SerialDataReceivedEventHandler(ScannerPort_DataReceived);
delegate void DoScanCallback(); // used for updating the form UI
void DoScan()
{
if (this.txtCouponCount.InvokeRequired)
{
DoScanCallback d = new DoScanCallback(DoScan);
this.Invoke(d);
return;
}
System.Threading.Thread.Sleep(100);
string ScanData = ScannerPort.ReadExisting();
if (isInScanMode)
{
try
{
HandleScanData(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan");
}
}
}
void ScannerPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// this call to sleep allows the scanner to receive the entire scan.
// without this sleep, we've found that we get only a partial scan.
try
{
DoScan();
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to handle scan event in ScannerPort_DataReceived." + System.Environment.NewLine + ex.ToString());
}
}
void Port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(e.EventType.ToString());
}
private void HandleScanData(string ScanData)
{
//MessageBox.Show(ScanData + System.Environment.NewLine + ScanData.Length.ToString());
//Determine which type of barcode has been scanned, and handle appropriately.
if (ScanData.StartsWith("A") && ScanData.Length == 14)
{
try
{
ProcessUpcCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process UPC coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else if (ScanData.StartsWith("8110"))
{
try
{
ProcessDataBarCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process DataBar coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan" + System.Environment.NewLine + ScanData);
}
}
private void InitializeScanner()
{
try
{
ScannerPort.PortName = Properties.Settings.Default.ScannerPort;
ScannerPort.ReadBufferSize = Properties.Settings.Default.ScannerReadBufferSize;
ScannerPort.Open();
ScannerPort.BaudRate = Properties.Settings.Default.ScannerBaudRate;
ScannerPort.DataBits = Properties.Settings.Default.ScannerDataBit;
ScannerPort.StopBits = Properties.Settings.Default.ScannerStopBit;
ScannerPort.Parity = Properties.Settings.Default.ScannerParity;
ScannerPort.ReadTimeout = Properties.Settings.Default.ScannerReadTimeout;
ScannerPort.DtrEnable = Properties.Settings.Default.ScannerDtrEnable;
ScannerPort.RtsEnable = Properties.Settings.Default.ScannerRtsEnable;
}
catch (Exception ex)
{
MessageBox.Show("Unable to initialize scanner. The error message received will be shown next. You should close this program and try again. If the problem persists, please contact support.", "Error initializing scanner");
MessageBox.Show(ex.Message);
Application.Exit();
}
}
As stated in the doc for SerialPort.DataReceived, "Use the BytesToRead property to determine how much data is left to be read in the buffer."
here is the doc for SerialPort.BytesToRead
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx

Categories