none
UWP QR-Code Scanner Exception RRS feed

  • Frage

  • Hallo Leute,

    ich habe gerade erst mit UWP angefangen und bekomme bei meinem Code dauernd Exceptions. Es wäre super, wenn mir jemand einen Tipp geben könnte, wie ich die Probleme lösen könnte, denn ich bin echt am Ende. Entschuldigt den schlechten Code :-).

    ' Die Vorlage "Leere Seite" ist unter http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 dokumentiert.
    
    Imports System.Threading
    Imports Windows.Devices.Enumeration
    'Imports Windows.Devices.Sensors
    Imports Windows.Media
    Imports Windows.Media.Capture
    Imports Windows.System.Display
    Imports Windows.UI.Core
    Imports Windows.UI.Popups
    Imports ZXing
    Imports System.Windows
    Imports Windows.Graphics.Imaging
    Imports Windows.Media.MediaProperties
    ''' <summary>
    ''' Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
    ''' </summary>
    Public NotInheritable Class MainPage
        Inherits Page
        Private ReadOnly _displayRequest As DisplayRequest = New DisplayRequest()
        Private ReadOnly _systemMediaControls As SystemMediaTransportControls = SystemMediaTransportControls.GetForCurrentView()
        '  Private ReadOnly _displayInformation As DisplayInformation = DisplayInformation.GetForCurrentView
        Private _mediaCapture As MediaCapture
        Dim stateTimer As Timer
        Private _isInitialized As Boolean
        Private _isPreviewing As Boolean
        Private _isRecording As Boolean
        'Private _deviceOrientation As SimpleOrientation = SimpleOrientation.NotRotated
        'Private _displayOrientation As DisplayOrientations = DisplayOrientations.Portrait
        Private _mirroringPreview As Boolean
        Private Shared ReadOnly RotationKey As Guid = New Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1")
        Private _externalCamera As Boolean
        Dim localSettings As Windows.Storage.ApplicationDataContainer = Windows.Storage.ApplicationData.Current.LocalSettings
        Dim scanner As BarcodeReader
        Dim Timercallback As New TimerCallback(Async Sub() Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Async Sub() Await scanforbarcode()))
        Public Sub New()
            Me.InitializeComponent()
            NavigationCacheMode = NavigationCacheMode.Enabled
            AddHandler Application.Current.Suspending, AddressOf Application_Suspending
            AddHandler Application.Current.Resuming, AddressOf Application_Resuming
        End Sub
        Private Async Sub Application_Suspending(sender As Object, e As SuspendingEventArgs)
            If Frame.CurrentSourcePageType Is GetType(MainPage) Then
                Dim deferral = e.SuspendingOperation.GetDeferral()
                Await CleanupCameraAsync()
                CleanupUi()
                deferral.Complete()
            End If
        End Sub
    
        Private Async Sub Application_Resuming(sender As Object, o As Object)
            If Frame.CurrentSourcePageType Is GetType(MainPage) Then
                Await InitializeCameraAsync()
            End If
        End Sub
        Private Sub MainPage_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
            CheckForSettings()
    
        End Sub
    
        Private Sub MainPage_Loading(sender As FrameworkElement, args As Object) Handles Me.Loading
    
    
        End Sub
    
    
        Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
            Frame.Navigate(GetType(SettingsPage))
        End Sub
        Private Async Sub HasToSetSettings()
            Dim Message1 As New MessageDialog("Sie starten die App zum ersten Mal. Sie werden nun zu den Einstellungen weitergeleitet!", "Weiterleiten?")
            Message1.Commands.Add(New UICommand("Einstellungen", Nothing, 0))
            Message1.Commands.Add(New UICommand("App beenden", Nothing, 1))
            Message1.DefaultCommandIndex = 0
            Message1.CancelCommandIndex = 1
            Dim result = Await Message1.ShowAsync()
            If Convert.ToInt32(result.Id) = 0 Then
                Frame.Navigate(GetType(SettingsPage))
            Else
                Application.Current.Exit()
            End If
        End Sub
        Private Sub CheckForSettings()
            If localSettings.Values.ContainsKey("CAM") = False OrElse localSettings.Values.ContainsKey("Password") = False _
                OrElse localSettings.Values.ContainsKey("Username") = False OrElse localSettings.Values.ContainsKey("ServiceURL") = False Then
                HasToSetSettings()
            End If
        End Sub
        Private Async Function StartPreviewAsync() As Task
            _displayRequest.RequestActive()
            PreviewControl.Source = _mediaCapture
            PreviewControl.FlowDirection = If(_mirroringPreview, FlowDirection.RightToLeft, FlowDirection.LeftToRight)
            Await _mediaCapture.StartPreviewAsync()
            _isPreviewing = True
            If _isPreviewing Then
                Await SetPreviewRotationAsync()
                scanner = New BarcodeReader
                AddHandler scanner.ResultFound, AddressOf scannerresultfound
                stateTimer = New Timer(Timercallback, New AutoResetEvent(False), 1500, 250)
            End If
        End Function
        Private Async Function StopPreviewAsync() As Task
            If stateTimer IsNot Nothing Then
                stateTimer.Dispose()
            End If
            RemoveHandler scanner.ResultFound, AddressOf scannerresultfound
            scanner = Nothing
            _isPreviewing = False
            Await _mediaCapture.StopPreviewAsync()
            Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub()
                                                                         PreviewControl.Source = Nothing
                                                                         _displayRequest.RequestRelease()
                                                                     End Sub)
        End Function
        Private Async Function InitializeCameraAsync() As Task
    
            If _mediaCapture Is Nothing Then
                If localSettings.Values.ContainsKey("CAM") = False Then
                    Return
                End If
                If localSettings.Values.ContainsKey("CAM") = False Or localSettings.Values("CAM").ToString = "" Or localSettings.Values("CAM").ToString = "NOCAM" Then
                    Return
                End If
    
    
                Dim cameraDevice = Await DeviceInformation.CreateFromIdAsync(localSettings.Values("CAM").ToString)
                _mediaCapture = New MediaCapture()
                Dim settings = New MediaCaptureInitializationSettings With {.VideoDeviceId = localSettings.Values("CAM").ToString}
                Try
                    Await _mediaCapture.InitializeAsync(settings)
                    _isInitialized = True
                Catch ex As UnauthorizedAccessException
    
                End Try
    
                If _isInitialized Then
                    If cameraDevice.EnclosureLocation Is Nothing OrElse cameraDevice.EnclosureLocation.Panel = Windows.Devices.Enumeration.Panel.Unknown Then
                        _externalCamera = True
                    Else
                        _externalCamera = False
                        _mirroringPreview = (cameraDevice.EnclosureLocation.Panel = Windows.Devices.Enumeration.Panel.Front)
                    End If
    
                    Await StartPreviewAsync()
                End If
            End If
        End Function
        Private Async Function SetPreviewRotationAsync() As Task
            If _externalCamera Then
                Return
            End If
    
            ' Calculate which way and how far to rotate the preview
            Dim rotationDegrees As Integer = 90 '= ConvertDisplayOrientationToDegrees(_displayOrientation)
            If _mirroringPreview Then
                rotationDegrees = (360 - rotationDegrees) Mod 360
            End If
    
            ' Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
            Dim props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview)
            props.Properties.Add(RotationKey, rotationDegrees)
            Await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, Nothing)
        End Function
        'Private Shared Function ConvertDeviceOrientationToDegrees(orientation As SimpleOrientation) As Integer
        '    Select Case orientation
        '        Case SimpleOrientation.Rotated90DegreesCounterclockwise
        '            Return 90
        '        Case SimpleOrientation.Rotated180DegreesCounterclockwise
        '            Return 180
        '        Case SimpleOrientation.Rotated270DegreesCounterclockwise
        '            Return 270
        '        Case Else
        '            Return 0
        '    End Select
        'End Function
        'Private Shared Function ConvertDisplayOrientationToDegrees(orientation As DisplayOrientations) As Integer
        '    Select Case orientation
        '        Case DisplayOrientations.Portrait
        '            Return 90
        '        Case DisplayOrientations.LandscapeFlipped
        '            Return 180
        '        Case DisplayOrientations.PortraitFlipped
        '            Return 270
        '        Case Else
        '            Return 0
        '    End Select
        'End Function
        'Private Async Sub DisplayInformation_OrientationChanged(sender As DisplayInformation, args As Object)
        '    _displayOrientation = sender.CurrentOrientation
        '    If _isPreviewing Then
        '        Await SetPreviewRotationAsync()
        '    End If
        'End Sub
        Protected Overrides Async Sub OnNavigatedTo(e As NavigationEventArgs)
            If Pivot1.SelectedIndex = 0 Then
                Await InitializeCameraAsync()
            End If
        End Sub
        Protected Overrides Async Sub OnNavigatingFrom(e As NavigatingCancelEventArgs)
            If Pivot1.SelectedIndex = 0 Then
                Await CleanupCameraAsync()
                CleanupUi()
            End If
        End Sub
        Private Async Function CleanupCameraAsync() As Task
            If _isInitialized Then
                If _isPreviewing Then
                    Await StopPreviewAsync()
                End If
                _isInitialized = False
            End If
    
            If _mediaCapture IsNot Nothing Then
                _mediaCapture.Dispose()
                _mediaCapture = Nothing
            End If
        End Function
        Private Sub CleanupUi()
            UnregisterEventHandlers()
            '  DisplayInformation.AutoRotationPreferences = DisplayOrientations.None
        End Sub
        Private Sub UnregisterEventHandlers()
            '   RemoveHandler _displayInformation.OrientationChanged, AddressOf DisplayInformation_OrientationChanged
        End Sub
        Private Async Function scanforbarcode() As Task
            Try
                Dim Frame As VideoFrame
                Dim previewProperties = TryCast(_mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview), VideoEncodingProperties)
                Dim VideoFrame As New VideoFrame(BitmapPixelFormat.Bgra8, Convert.ToInt32(previewProperties.Width), Convert.ToInt32(previewProperties.Height))
                Frame = Await _mediaCapture.GetPreviewFrameAsync(VideoFrame)
                If Frame Is Nothing Then
                    Exit Function
                End If
    
                Dim previewFrame As SoftwareBitmap = Frame.SoftwareBitmap
                Dim sbSource = Frame.SoftwareBitmap
                Dim BMP As New WriteableBitmap(Convert.ToInt32(previewProperties.Width), Convert.ToInt32(previewProperties.Height))
                sbSource.CopyToBuffer(BMP.PixelBuffer)
                image.Source = BMP
                scanner.Decode(BMP)
            Catch ex As Exception
                Debug.WriteLine("MESSAGE FROM SCANFORBARCODE():" & ex.Message)
            End Try
        End Function
        Private Sub scannerresultfound(ByVal result As Result)
            Debug.WriteLine("RESULT: " & result.Text)
            If result.Text = "call:settings" Then
                Frame.Navigate(GetType(SettingsPage))
            End If
        End Sub
        Private Async Sub Pivot1_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles Pivot1.SelectionChanged
            If Pivot1.SelectedIndex = 0 Then
                Await InitializeCameraAsync()
            Else
                Await CleanupCameraAsync()
                CleanupUi()
            End If
        End Sub
    End Class
    

    Hier noch die Exceptions:

    Ausnahme ausgelöst: "System.OutOfMemoryException" in mscorlib.ni.dll
    MESSAGE FROM SCANFORBARCODE():Insufficient memory to continue the execution of the program.
    Ausnahme ausgelöst: "<Unbekannt>" in Unbekanntes Modul.
    Das Programm "[5192] Event_APP.exe" wurde mit Code -1 (0xffffffff) beendet.


    Ausnahme ausgelöst: "System.Exception" in mscorlib.ni.dll
    MESSAGE FROM SCANFORBARCODE():The request is invalid in the current state. (Exception from HRESULT: 0xC00D36B2)


    Ausnahme ausgelöst: "System.NullReferenceException" in Event_APP.exe
    MESSAGE FROM SCANFORBARCODE():Object reference not set to an instance of an object.

    Vielen Dank,

    Bodenseecoder

    Montag, 8. Februar 2016 11:02

Antworten

  • Wenn du so tust als ob du dein Problem vernünftig beschrieben hast, dann tue ich mal so als ob ich da vernünftig drauf antworte :-)

    Setz mal einen Breakpoint und debugge das durch. Dann weist du zumindest wo der Fehler wirklich entsteht.

    • Als Antwort markiert Bodenseecoder Montag, 8. Februar 2016 12:04
    Montag, 8. Februar 2016 11:17

Alle Antworten

  • Wenn du so tust als ob du dein Problem vernünftig beschrieben hast, dann tue ich mal so als ob ich da vernünftig drauf antworte :-)

    Setz mal einen Breakpoint und debugge das durch. Dann weist du zumindest wo der Fehler wirklich entsteht.

    • Als Antwort markiert Bodenseecoder Montag, 8. Februar 2016 12:04
    Montag, 8. Februar 2016 11:17
  • Wenn du so tust als ob du dein Problem vernünftig beschrieben hast, dann tue ich mal so als ob ich da vernünftig drauf antworte :-)

    YMMD :)


    Gruß, Stefan
    Microsoft MVP - Visual Developer ASP/ASP.NET
    http://www.asp-solutions.de/ - Consulting, Development
    http://www.aspnetzone.de/ - ASP.NET Zone, die ASP.NET Community


    Montag, 8. Februar 2016 11:48
    Moderator