Error HRESULT: 0x80070021 when connecting to scanner - c#

I have the following code for scanning a document using WIA with a Kodak ScanMate i1120
public static Device InitScanner(string DeviceID)
{
var deviceManager = new DeviceManager();
// Create an empty variable to store the scanner instance
DeviceInfo firstScannerAvailable = null;
// Loop through the list of devices
for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++)
{
if (deviceManager.DeviceInfos[i].DeviceID == DeviceID)
{
firstScannerAvailable = deviceManager.DeviceInfos[i];
var device = firstScannerAvailable.Connect();
return _ConnectedScanner;
}
}
return _ConnectedScanner;
}
public void ScanDocument()
{
string _DeviceID = GetDeviceID(Properties.Settings.Default.DefaultDevice);
InitScanner(_DeviceID);
if (_ConnectedScanner == null)
{
MessageBox.Show("Scanner is not turned on or connected");
Lcontinue = false;
return;
}
else
{
try
{
_item = _ConnectedScanner.Items[1] as Item;
SelectDeviceDocumentHandling(_ConnectedScanner, DeviceDocumentHandling.Feeder);
//MessageBox.Show(GetDeviceProperty(_ConnectedScanner, 3078).ToString());
_MyImage = (ImageFile)_ConnectedScanner.Items[1].Transfer();
DocCount++;
}
catch (Exception ex)
{
switch (ex.HResult)
{
case -2145320959:
Lcontinue = false;
MessageBox.Show(ex.Message + Environment.NewLine + "Unknown Error");
return;
case -2145320957:
if (DocCount == 0)
{
Lcontinue = false;
//_WaitForOperator = false;
MessageBox.Show(ex.Message + Environment.NewLine + "There is no paper in the ADF");
return;
}
else
{
Lcontinue = false;
//WaitForOperator = false;
//DocCount = 0;
}
break;
case -2145320954:
if (DocCount == 0)
{
Lcontinue = false;
//_WaitForOperator = false;
MessageBox.Show(ex.Message + Environment.NewLine + "The device is busy, Please retry");
return;
}
else
{
Lcontinue = false;
DocCount = 0;
}
break;
default:
Lcontinue = false;
MessageBox.Show("Error No : " + ex.HResult + Environment.NewLine + Environment.NewLine + ex.ToString());
return;
}
}
}
}
I have two scanners on the system, a Kyocera and the Kodak, but I only want to use the Kodak for this app.
When I try to scan with the Kodak I get error
HRESULT: 0x80070021
System.IO.FileLoadException: `The process cannot access the file because another process has locked a portion of the file.
the error happens on the following line
var device = firstScannerAvailable.Connect();
I have no other scanning applications open so I am unable to figure out what is locking the file.
Can someone see what would be causing the file lock?

Related

Form without movement when filling in DataGridView

I use a DataGridView as a console for an application, I need to fill it out every second, I use the following code for this:
public class dgView
{
public static DataGridView DataConsole;
public static void addLinha(int tipo_acao, string acao, string extra, int tipo_extra)
{
// INSERE LINHA NO CONSOLE
try
{
if (DataConsole == null) return;
var idLinha = DataConsole.Rows.Add();
using (var linha = DataConsole.Rows[idLinha])
{
//await Task.Delay(300);
if (tipo_acao == 0)
{
linha.DefaultCellStyle.ForeColor = Color.Teal;
linha.Cells[3].Style.ForeColor = Color.Gray;
}
else if (tipo_acao == 1)
{
linha.DefaultCellStyle.ForeColor = Color.Yellow;
linha.Cells[3].Style.ForeColor = Color.Orange;
}
else
{
linha.DefaultCellStyle.ForeColor = Color.Red;
linha.Cells[3].Style.ForeColor = Color.Magenta;
}
linha.Cells["dg_data"].Value = DateTime.Now;
linha.Cells["dg_mapa"].Value = "" + Config.Mapa + "";
linha.Cells["dg_acao"].Value = "" + Config.rm.GetString("" + acao + "") + "";
if (tipo_extra == 0)
{
linha.Cells["dg_extra"].Value = "" + extra + "";
}
else
{
linha.Cells["dg_extra"].Value = "" + Config.rm.GetString(extra) + "";
}
DataConsole.CurrentCell = DataConsole.Rows[idLinha].Cells[0];
//DataConsole.Refresh();
}
}
catch (Exception ex)
{
throw;
}
}
}
However, the form freezes and I can't move it to any part of the screen, would there be any way to solve this? Remembering that the DataGridView is not, and cannot be populated through the DataSource property, but by a constant verification in the system.
Example:
public static void Abrir(string metodoChamador)
{
try
{
Abrir:
dgView.addLinha(2, "config_Abrir", "config_Validando", 1);
Thread.Sleep(5000);
Atalho:
string AtalhoExiste = "" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk";
if (!File.Exists(AtalhoExiste))
{
dgView.addLinha(2, "config_FaltaIcone", "", 0);
Thread.Sleep(5000);
goto Atalho;
}
else
{
ProcessStartInfo info = new ProcessStartInfo(#"" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk");
Process whatever = Process.Start(info);
whatever.Dispose();
Thread.Sleep(5000);
IntPtr WinHandle = Win32.FindWindow(null, Config.Atalho);
if (WinHandle == (IntPtr)0)
{
goto Abrir;
}
}
}
catch (Exception ex)
{
throw;
}
}
It's hard to tell if you have other potential problems in the code. Basically anywhere you have Thread.Sleep(), your GUI is going to freeze.
Here's a possible refactoring of your Abrir() method, using async\await and Task.Delay() as suggested by JQSOFT:
public async static void Abrir(string metodoChamador)
{
try
{
IntPtr WinHandle = IntPtr.Zero;
do
{
dgView.addLinha(2, "config_Abrir", "config_Validando", 1);
await Task.Delay(5000);
string AtalhoExiste = "" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk";
while (!File.Exists(AtalhoExiste))
{
dgView.addLinha(2, "config_FaltaIcone", "", 0);
await Task.Delay(5000);
}
ProcessStartInfo info = new ProcessStartInfo(#"" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk");
Process whatever = Process.Start(info);
whatever.Dispose();
await Task.Delay(5000);
WinHandle = Win32.FindWindow(null, Config.Atalho);
}
while (WinHandle.Equals(IntPtr.Zero));
}
catch (Exception ex)
{
throw;
}
}
If you have Thread.Sleep() in other locations, they would need to be refactored.
If you have any other infinite loops using goto, those may need to be refactored as well.

How to fix VS2013: Error: type or namespace 'Windows' could not be found?

I want to create a service for Wifi Direct. If I try to add Reference, I don't see core->windows option in VS2013. I have updated the winSDK.
How do I add the Windows.Devices.WifiDirect api ?
you can use
public sealed class WiFiDirectDevice : IDisposable
this is a sample code to handle connections
Windows.Devices.WiFiDirect.WiFiDirectDevice wfdDevice;
private async System.Threading.Tasks.Task<String> Connect(string deviceId)
{
string result = "";
try
{
// No device Id specified.
if (String.IsNullOrEmpty(deviceId)) { return "Please specify a Wi- Fi Direct device Id."; }
// Connect to the selected Wi-Fi Direct device.
wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(deviceId);
if (wfdDevice == null)
{
result = "Connection to " + deviceId + " failed.";
}
// Register for connection status change notification.
wfdDevice.ConnectionStatusChanged += new TypedEventHandler<Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(OnConnectionChanged);
// Get the EndpointPair information.
var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs();
if (EndpointPairCollection.Count > 0)
{
var endpointPair = EndpointPairCollection[0];
result = "Local IP address " + endpointPair.LocalHostName.ToString() +
" connected to remote IP address " + endpointPair.RemoteHostName.ToString();
}
else
{
result = "Connection to " + deviceId + " failed.";
}
}
catch (Exception err)
{
// Handle error.
result = "Error occurred: " + err.Message;
}
return result;
}
private void OnConnectionChanged(object sender, object arg)
{
Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus status =
(Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus)arg;
if (status == Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus.Connected)
{
// Connection successful.
}
else
{
// Disconnected.
Disconnect();
}
}
private void Disconnect()
{
if (wfdDevice != null)
{
wfdDevice.Dispose();
}
}

AdColony's OnVideoFinished not call in Android

I have a problem with AdColony-UnitySDK.
When AdColony's video is finish playing, OnVideoFinished() method don't be called.
In this case, the following sources work well in iOS. And also, the server receive the success callback both device. So, only Android device that is not work.
Here is the source code, where AdColony is implemented:
public void initializeAdColony(){
try {
//Delegates
AdColony.OnVideoFinished += (adshown)=>{
if (adshown) {
AdColonyLog("OnVideoFinished", "Completed");
GameBGM.Instance.PlayWaiting();
CallAdColonySuccessCallback("Success", v4vcSuccess,v4vcFail);
} else {
AdColonyLog("OnVideoFinished", "Failed");
CallAdColonyFailureCallback("Fail", v4vcSuccess,v4vcFail);
}
};
AdColony.OnV4VCResult += (videoSuccessCallbacks,name,amount)=>{
if(videoSuccessCallbacks)
{
AdColonyLog("OnV4VCResult","V4VC SUCCESS: name = " + name + ", amount = " + amount);
returnReward = name;
}
else
{
AdColonyLog("OnV4VCResult","V4VC FAILED!");
CallAdColonyFailureCallback("Fail", v4vcSuccess,v4vcFail);
}
};
//customID
AdColony.SetCustomID(LoginInfo.Instance.id);
//configure
AdColony.Configure(
CurrentBundleVersion.version,
AdColonyData.appID(),
AdColonyData.zoneIDs[AdColonyData.Zone1],
AdColonyData.zoneIDs[AdColonyData.Zone2],
AdColonyData.zoneIDs[AdColonyData.Zone3],
AdColonyData.zoneIDs[AdColonyData.Zone4],
AdColonyData.zoneIDs[AdColonyData.Zone5]
);
//FinishInit
AdColonyIsInit = true;
AdColonyLog("Initiallize", "Complete");
} catch (Exception e){
//Error
AdColonyLog("Initiallize", e.Message);
}
}
And here is the method where AdColony's video show:
public void ShowAdColonyVideo(System.Action successCallback, System.Action failureCallback){
//InitAdColony
if (!AdColonyIsInit) {
initializeAdColony();
}
//Setup CallbackAction;
shownVideo = false;
v4vcSuccess = successCallback;
v4vcFail = failureCallback;
//Check
foreach (string key in AdColonyData.services) {
AdColonyLog("LoadKey", key + ":"+ AdColonyData.zoneIDs[key]);
if (shownVideo) {
break;
}
if (AdColony.IsV4VCAvailable (AdColonyData.zoneIDs [key])) {
AdColonyLog ("ShowAdColonyVideo", "Video available");
GameBGM.Instance.StopMusic ();
shownVideo = true;
AdColony.ShowV4VC (false, AdColonyData.zoneIDs [key]);
break;
} else {
AdColonyLog ("ShowAdColonyVideo", "Video unavailable");
}
}
if (!shownVideo) {
failureCallback ();
}
}
Do you please suggest me how to solve this issue? Thank you.
This is a known issue at AdColony and we will be releasing a fix in a pending release.
We will update this post once it has been released at:
https://github.com/AdColony/AdColony-Unity-SDK

BackgroundTransferRequest connect external power error

I use BackgroundTransferRequest class to download mp3 files in my wp8 app. Some of my files are over 100mb, so because of that I set transferRequest.TransferPreferences = TransferPreferences.None;. However, transferstatus method still returns me external power message.
If you look at line 12 in code you can see that i set TransferPreferences as None
Here is my code to download mp3 file:
private void download_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (transferFileName != null)
{
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
transferRequest.TransferPreferences = TransferPreferences.None;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
// TBD - update when exceptions are finalized
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception e2)
{
MessageBox.Show("Unable to add background transfer request."+e2.ToString());
}
transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
}
else
MessageBox.Show("select an mp3 file to download");
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
RemoveTransferRequest(transfer.RequestId);
processresult.Text = "";
download.Visibility = Visibility.Visible;
lnk = new linkname();
URLListBox.ItemsSource = lnk.obj();
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
string filename = transfer.Tag;
if (isoStore.FileExists(filename))
{
isoStore.DeleteFile(filename);
}
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
}
}
else
{
RemoveTransferRequest(transfer.RequestId);
if (transfer.TransferError != null)
{
MessageBox.Show(transfer.TransferError.ToString());
}
}
break;
case TransferStatus.WaitingForExternalPower:
WaitingForExternalPower = true;
processresult.Text = "Waiting For External Power";
break;
case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
WaitingForExternalPowerDueToBatterySaverMode = true;
processresult.Text = "Waiting For External Power Due To Battery Saver Mode";
break;
case TransferStatus.WaitingForNonVoiceBlockingNetwork:
WaitingForNonVoiceBlockingNetwork = true;
processresult.Text = "Waiting For Non Voice Blocking Network";
break;
case TransferStatus.WaitingForWiFi:
WaitingForWiFi = true;
processresult.Text = "Waiting For WiFi";
break;
}
}
private void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
From the Documentation
If the file to be transferred is larger than 100 MB, set the TransferPreferences property of the transfer to None. If you do not, the system will automatically change the transfer settings to this value, meaning that the transfer will only proceed when the phone is connected to external power and has a Wi-Fi connection.

From C# to Android via Socket. Can't find my mistake

The problem - I can't get this functions working. I see in LogCat that socket is connected to c# server, but I don't see received data. What I'm doing wrong?
Here is c# function with MessageBoxes for checking:
private void receiveConnection(){
Socket myHandler = null;
bool isConnected = false;
while (true)
{
if (!isConnected)
{
myHandler = wSocket.Accept();
isConnected = true;
MessageBox.Show("We have client!");
}
if (sendDataToAndroid)
{
try
{
sendDataToAndroid = false;
NetworkStream stream = new NetworkStream(myHandler);
StreamWriter sw = new StreamWriter(stream);
string myMsg = "";
myMsg += temp_F.Length + " ";
temp_F[0] = 3.151F;
temp_F[1] = 1.415F;
temp_F[2] = 5.572F;
temp_F[3] = 6.320F;
for (int i = 0; i < temp_F.Length; i++)
{
myMsg += temp_F[i] + " ";
}
byte[] msg = Encoding.ASCII.GetBytes(myMsg);
MessageBox.Show("Data to send: " + myMsg);
try
{
myHandler.Send(msg);
MessageBox.Show("Data has been sent!");
}
catch (Exception e) {
MessageBox.Show("Error while sending data!");
}
}
catch (Exception e)
{
isConnected = false;
myHandler.Close();
myHandler = null;
MessageBox.Show("Error while sending data...");
}
}
}
}
And here is Android function which is always trying to receive data:
public class SendThread implements Runnable {
public void run()
{
Socket socket = null;
BufferedReader in = null;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
}
}
// Get from the server
try {
Log.d("Connection: ", "connected");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = line.split(" ");
int currTempSize = Integer.parseInt(tokens[0]);
currentTemp = new double[currTempSize];
for (int i = 0; i < currTempSize; i++)
currentTemp[i] = (Double) nf.parse(tokens[i+1]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currTempSize; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
}
}
catch (Exception e) {
socket = null;
in = null;
Log.d("Connection: ", "lost.");
}
}
}
}
Your Java code reads a line at a time but you never sent a line terminator from C#.
You could append one to myMsg manually, or you could use the sw.WriteLine() method on your StreamWriter (which don't otherwise seem to be using). After calling sw.WriteLine() you will probably have to call sw.Flush().

Categories