locked
Error "The object has been closed. (Exception from HRESULT:0x80000013) RRS feed

  • Question

  • Hello I am receiving an error on my windows 10 Honeywell 75 e scanner.

    I launch the app, tap the scan button on the screen, the scanner scans and returns the data without any issue. But, if I press the power button on the scanner, screen turns off, then I press the power button on the scanner again, screen turns back on, my app is still running, but when I tap the scan button in my app, it does not work this time, I get an error Error "The object has been closed. (Exception from HRESULT:0x80000013), then, I will have to close and launch the app again to be able to scan again.

    If I don’t turn off and turn the screen back on, the error does not occur. Error occurs only when I turn off and turn the screen back on.

    I am including a copy of my code for your reference.

    Please help.

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Storage;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.Devices.PointOfService;
    using System.Threading.Tasks;
    using Windows.Storage.Streams;
    using System.Text;
    using Newtonsoft.Json.Linq;
    using Windows.ApplicationModel;
    using Windows.Security.ExchangeActiveSyncProvisioning;
    using Windows.System;
    using System.Diagnostics;
    using System.Runtime.Serialization;
    using Windows.Data.Json;
    using Newtonsoft.Json;
    
    
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
    
    namespace App1
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            //DecodeAssembly oDecodeAssembly;
            //DeviceHardwareAssembly oDeviceHardware;
            CommonClass cl = new CommonClass();
            public MainPage()
            {
                
                this.InitializeComponent();
                this.NavigationCacheMode = NavigationCacheMode.Required;
                //ClaimBarcodeScanner();
                Timer = new DispatcherTimer();
                Timer.Tick += TimerOnTick;
                Timer.Interval = new TimeSpan(0, 0, 0, 0, 50); ;
                Timer.Start();
    
            }
    
    
    
            public Uri baseAddress;
    
    
            private void TimerOnTick(object sender, object o)
            {
                myProgressBar.Value += 2;
                if (myProgressBar.Value == 200)
                {
                    myProgressBar.Value = 0;
    
                }
            }
    
    
            private void ResetTheScenarioState()
            {
                if (claimedScanner != null)
                {
                    // Detach the event handlers
                    claimedScanner.DataReceived -= claimedScanner_DataReceived;
                    claimedScanner.ReleaseDeviceRequested -= claimedScanner_ReleaseDeviceRequested;
                    // Release the Barcode Scanner and set to null
                    claimedScanner.Dispose();
                    claimedScanner = null;
                }
                if (scanner != null)
                {
                   
                    scanner = null;
                }
                
                //claimedScanner = null;
    
    
    
            }
    
    
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                // TODO: Prepare page for display here.
                ResetTheScenarioState();
                // TODO: If your application contains multiple pages, ensure that you are
                // handling the hardware Back button by registering for the
                // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
                // If you are using the NavigationHelper provided by some templates,
                // this event is handled for you.
            }
    
            protected override void OnNavigatedFrom(NavigationEventArgs e)
            {
                ResetTheScenarioState();
            }
    
    
    
            private  void image_Tapped(object sender, TappedRoutedEventArgs e)
            {
                this.Frame.Navigate(typeof(BadgeKeypad));
            }
    
            DispatcherTimer Timer;
            private const string ProfileFileName = "HoneywellDecoderSettingsV2.exm";
    
            private async void WriteProfieFiletoDevice()
            {
                try
                {
                    StorageFolder _folder = await KnownFolders.DocumentsLibrary.CreateFolderAsync("Profile", CreationCollisionOption.OpenIfExists);
                    var uri = new System.Uri("ms-appx:///Assets/" + ProfileFileName);
                    StorageFile profileFile = await StorageFile.GetFileFromApplicationUriAsync(uri);
                    String profileContent = await FileIO.ReadTextAsync(profileFile);
                    StorageFile myFile = await _folder.CreateFileAsync(ProfileFileName, CreationCollisionOption.OpenIfExists);
                    await FileIO.WriteTextAsync(myFile, profileContent);
                }
                catch (Exception ex)
                {
    
    
                }
            }
    
            private async void Page_Loaded(object sender, RoutedEventArgs e)
            {
    
                if (claimedScanner == null)
                {
    
                    ClaimBarcodeScanner();
                }
             
            }
    
            private void btnExit_Click(object sender, RoutedEventArgs e)
            {
                Application.Current.Exit();
    
            }
    
          
            BarcodeScanner scanner = null;
            ClaimedBarcodeScanner claimedScanner = null;
            private async void ClaimBarcodeScanner()
            {
                try
                {
                    scanner = await BarcodeScanner.GetDefaultAsync(); // get the default instance of the scanner
                                                                      //fakeScanner = new FakeScanner(scanner.DeviceId);
                    claimedScanner = await scanner.ClaimScannerAsync();//Attempts to get an exclusive access to the scanner.
                    // It is always a good idea to have a release device requested event handler.
                    // If this event is not handled, then another app can claim ownership of the barcode scanner.
                    claimedScanner.ReleaseDeviceRequested += claimedScanner_ReleaseDeviceRequested;
                    claimedScanner.DataReceived += claimedScanner_DataReceived;
                    claimedScanner.IsDecodeDataEnabled = true; // provide decoded label data}
                    await claimedScanner.EnableAsync(); //Gets the barcode scanner into a ready state.
                    await claimedScanner.SetActiveSymbologiesAsync(new[] { BarcodeSymbologies.Ean13, BarcodeSymbologies.Ean8, BarcodeSymbologies.Code39, BarcodeSymbologies.Code128, BarcodeSymbologies.Aztec, BarcodeSymbologies.Pdf417, BarcodeSymbologies.Gs1128, BarcodeSymbologies.ItalianPost25 });
                    
                    
                    
                }
                catch (Exception ex)
                {
    
    
                }
            }
            private async void Scan()
            {
            }
    
    
            async void claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    // alsways retain the device
                    e.RetainDevice();
    
                  //  UpdateOutput("Event ReleaseDeviceRequest received. Retaining the Barcode Scanner.");
                });
            }
    
            private async   void btnScan_Click(object sender, RoutedEventArgs e)
            {
                try
                {
    
                        if (await CreateDefaultScannerObject())
                        {
                            // after successful creation, claim the scanner for exclusive use and enable it so that data reveived events are received.
                            if (await ClaimScanner())
                            {
                                if (scanner.Capabilities.IsSoftwareTriggerSupported)
                                {
                                	//claimedScanner.IsDecodeDataEnabled = true;
                                    await claimedScanner.StartSoftwareTriggerAsync();
    
                                }
                            }
                        }
                    
                }
                catch (Exception ex)
                {
                }
    
            }
             string GetDataString(IBuffer data)
            {
                try
                {
                    StringBuilder result = new StringBuilder();
                    if (data == null)
                    {
                        result.Append("No data");
                    }
                    else
                    {
                        // Just to show that we have the raw data, we'll print the value of the bytes.
                        // Arbitrarily limit the number of bytes printed to 20 so the UI isn't overloaded.
                        const uint MAX_BYTES_TO_PRINT = 20;
                        uint bytesToPrint = Math.Min(data.Length, MAX_BYTES_TO_PRINT);
                        DataReader reader = DataReader.FromBuffer(data);
                        byte[] dataBytes = new byte[bytesToPrint];
                        reader.ReadBytes(dataBytes);
                        for (uint byteIndex = 0; byteIndex < bytesToPrint; ++byteIndex)
                        {
                            result.AppendFormat("{0:X2} ", dataBytes[byteIndex]);
                        }
                        if (bytesToPrint < data.Length)
                        {
                            result.Append("...");
                        }
                    }
                    return result.ToString();
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            private async Task<bool> CreateDefaultScannerObject()
            {
                try
                {
                    if (scanner == null)
                    {
                         scanner = await BarcodeScanner.GetDefaultAsync();
    
                        if (scanner != null)
                        {
                          
                        }
                        else
                        {
                           return false;
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
    
                    return false;
                }
            }
    
            /// <summary>
            /// This method claims the barcode scanner 
            /// </summary>
            /// <returns>true if claim is successful. Otherwise returns false</returns>
            private async Task<bool> ClaimScanner()
            {
                try
                {
                    if (claimedScanner == null)
                    {
                        // claim the barcode scanner
                        claimedScanner = await scanner.ClaimScannerAsync();
                        // enable the claimed barcode scanner
                        if (claimedScanner != null)
                        {
    
    
                        }
                        else
                        {
    
                            return false;
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
    
                    return false;
                }
            }
    
            /// <summary>
            /// This method claims the barcode scanner and enables it 
            /// </summary>
            /// <returns>true if enable is successful</returns>
            private async Task<bool> EnableScanner()
            {
                try
                {
                    // enable the claimed barcode scanner
                    if (claimedScanner == null)
                    {
                        return false;
                    }
                    else
                    {
                        await claimedScanner.EnableAsync();
    
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    return false;
    
                }
            }
    
    
        
    
            string GetDataLabelString(IBuffer data, uint scanDataType)
            {
                try
                {
                    string result = null;
                    // Only certain data types contain encoded text.
                    //   To keep this simple, we'll just decode a few of them.
                    if (data == null)
                    {
                        result = "No data";
                    }
                    else
                    {
                        switch (BarcodeSymbologies.GetName(scanDataType))
                        {
                            case "Upca":
                            case "UpcaAdd2":
                            case "UpcaAdd5":
                            case "Upce":
                            case "UpceAdd2":
                            case "UpceAdd5":
                            case "Ean8":
                            case "TfStd":
                            case "Code39":
                            case "Code128":
                            case "Gs1128":
                            case "Ean13":
                            case "Aztec":
                            case "Pdf417":
                            case "Int25":
                                // The UPC, EAN8, and 2 of 5 families encode the digits 0..9
                                // which are then sent to the app in a UTF8 string (like "01234")
                                // This is not an exhaustive list of symbologies that can be converted to a string
                                DataReader reader = DataReader.FromBuffer(data);
                                result = reader.ReadString(data.Length);
                                break;
                            default:
                                // Some other symbologies (typically 2-D symbologies) contain binary data that
                                //  should not be converted to text.
                                result = string.Format("Decoded data unavailable. Raw label data: {0}", GetDataString(data));
                                break;
                        }
                    }
                    return result;
                }
                catch (Exception ex)
                {
    
                    return null;
                }
            }
    
            /// <summary>
            /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param>
            /// 
            public string DataBad = "0";
            private  async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
            {
               
                try
                {
                    // need to update the UI data on the dispatcher thread.
                    // update the UI with the data received from the scan.
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        // read the data from the buffer and convert to string.
                        StatusBlock.Text = GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
                        DataBad = GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
                        mycontrol.Play();
                        Scan();
                    });
                    //string label;
                    //UInt32 symCode = args.Report.ScanDataType;
                    //using (var datareader = Windows.Storage.Streams.DataReader.FromBuffer(args.Report.ScanDataLabel))
                    //{ label = datareader.ReadString(args.Report.ScanDataLabel.Length);
                    //    DataBad = label;
                    //    Scan();
    
                    //}
                 //   UpdateUI_scandata(BarcodeSymbologies.GetName(args.Report.ScanDataType), DataBad);
    
                }
                catch (Exception ex)
                {
    
                }
            }
            private async void UpdateUI_scandata(string symCode, string data)
            { // The following is essentailly what we would call a delegate in a WIN6.1 or 6.5 application 
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //(symCode + ", " + data); 
                    // List of scanned bar codes 
                    
                //Audio_Player.Play(); // play beep on bar code scan using the medai element control 
                }); }
    
            private void myProgressBar_Loaded(object sender, RoutedEventArgs e)
            {
               
            }
        }
    }
    
    
    
    

    Wednesday, April 18, 2018 3:06 PM

All replies

  • Hi RobbieDotNet,

    Is your app running in the scanner rather than running in a desktop or a phone, surface?

    I saw that there are many try/catch blocks handling exceptions. Do you know in which block does the exception came out? You could output some extra message like method name in the blocks so that we could know where is the problem. This would be better for troubleshooting the problem.


    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, April 19, 2018 2:50 AM
  • This is no longer an issue, we found a solution for this. Sorry for the late response and thanks for your help.
    Friday, May 18, 2018 3:28 PM
  • I encounter the similar error. 
    Could you let me know about the issue? It might be very helpful for me.
    Thanks in advance.
    Friday, August 10, 2018 3:41 PM