ZXing.Net.Mobile Sample.WindowsUniversal Sample Not Scanning - win-universal-app

Testing this to incorporate into Win 10 UWP app to scan 1D barcodes (format 39 & 128). I have updated latest through nuget 2.0.4.46. Referenced post at http://www.yortondotnet.com/2015/07/mobile-barcode-scanning-with-zxingnet.html regarding some options setting prior to scan() with no luck. The scanner (camera) opens but never recognizes a barcode scan successfully - or failure for that matter. It seems nothing is happening whatsoever. I have included straight, pertinent sample code with some options modifications for review. I have gotten Scandit API to work and was going to try Manateeworks but both are really costly and not an option. I am developing on Surface Pro 3 (Win 10) and that build will also be target machines when complete.
public sealed partial class MainPage : Page
{
UIElement customOverlayElement = null;
MobileBarcodeScanner scanner;
public MainPage()
{
this.InitializeComponent();
//Create a new instance of our scanner
scanner = new MobileBarcodeScanner(this.Dispatcher);
scanner.Dispatcher = this.Dispatcher;
}
private void buttonScanDefault_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.Scan(options).ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
}
private void buttonScanContinuously_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.ScanContinuously(options, async (result) =>
{
var msg = "Found Barcode: " + result.Text;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await MessageBox(msg);
});
});
}
async void HandleScanResult(ZXing.Result result)
{
string msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
msg = "Found Barcode: " + result.Text;
else
msg = "Scanning Canceled!";
await MessageBox(msg);
}
}

Simon,
I have the exact same problem. I tested your code with the latest nuget 2.1.47, the problem still exists.
You need to download the latest from Github and add the following projects (or DLLs) to your project:
ZXing.Net (project: zxing.portable.csproj)
ZXing.Net.Mobile.Core
ZXing.Net.Mobile.WindowsUniversal
I have tested your code and it works fine. I hope this help.
Cheers,
Sam

I think that the problem in the hardware you are testing with. Surface Pro 3 (Win 10) does not have an auto focus camera. I've never succeed to scan with ZXing using my Surface Pro 3, while the same application is working fine with my other windows 10 device.

Related

Why crash happens when using a FileOpenPicker in my UWP app?

Recently I am writing an app on My PC and lumia 640, everything seems good when it runs under Debug mode in VS 2015, but when I use it on my phone and tap a button to open a FileOpenPicker to choose picture from PicturesLibrary, it just crash...
When I try connecting my phone and use VS to find the problem, it never shows up any more...Also, when I run my app on my PC, whether under Debug mode or not, the problem also never happens.
The Listener of the button looks like this:
private async void OnSnap(object sender, RoutedEventArgs e)
{
try
{
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fileOpenPicker.FileTypeFilter.Add(".jpg");
fileOpenPicker.FileTypeFilter.Add(".png");
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
var inputFile = await fileOpenPicker.PickSingleFileAsync();
if (inputFile == null)
{
// The user cancelled the picking operation
return;
}
else
{
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(inputFile);
Frame frame = Window.Current.Content as Frame;
frame.Navigate(typeof(PictureChoosePage), await inputFile.OpenAsync(FileAccessMode.Read));
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
var msgDialog = new MessageDialog(exception.Message) { Title = "Unkown Error" };
msgDialog.Commands.Add(new Windows.UI.Popups.UICommand("OK", uiCommand => {
Frame frame = Window.Current.Content as Frame;
frame.Navigate(typeof(MainPage));
}));
msgDialog.Commands.Add(new Windows.UI.Popups.UICommand("Cancel", uiCommand => { }));
await msgDialog.ShowAsync();
return;
}
}
One more thing to mention is that when my App crash, the bottom bar of the FileOpenPicker shows up...like this:
The required permissions should have been declared, and if there is a UnathorizedAccessException thrown, it should be caught by my code...So I'm thinking if this is the bug of the OS since the windows 10 mobile on my lumia 640 is 10.0.14295.1000, just a preview version.

How to switch to Front Camera in Windows Phone 8.1 (WinRT/Jupiter)

I can't seem to find the property for the MediaCapture class that allows me to detect the front camera and switch to it if available. Here is my current setup of the device, it all works as expected on Windows (front cam) and Phone (rear cam). None of the Microsoft samples show the front camera being used in Universal or WP 8.1 (WinRT/Jupiter).
mediaCaptureManager = new MediaCapture();
await mediaCaptureManager.InitializeAsync();
if (mediaCaptureManager.MediaCaptureSettings.VideoDeviceId != "" && mediaCaptureManager.MediaCaptureSettings.AudioDeviceId != "")
{
StartStopRecordingButton.IsEnabled = true;
TakePhotoButton.IsEnabled = true;
ShowStatusMessage("device initialized successfully!");
mediaCaptureManager.VideoDeviceController.PrimaryUse = CaptureUse.Video;
mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
mediaCaptureManager.SetRecordRotation(VideoRotation.Clockwise90Degrees);
mediaCaptureManager.RecordLimitationExceeded += RecordLimitationExceeded;
mediaCaptureManager.Failed += Failed;
}
There is a sample on the Microsoft github page that is relevant, although they target Windows 10. Still, the APIs should work on 8/8.1.
UniversalCameraSample: This one does capture photos, and supports portrait and landscape orientations. Here is the relevant part:
private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
// If there is no device mounted on the desired panel, return the first device found
return desiredDevice ?? allVideoDevices.FirstOrDefault();
}
And you can use it like so:
// Attempt to get the front camera if one is available, but use any camera device if not
var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Front);
if (cameraDevice == null)
{
Debug.WriteLine("No camera device found!");
return;
}
// Create MediaCapture and its settings
_mediaCapture = new MediaCapture();
var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
// Initialize MediaCapture
try
{
await _mediaCapture.InitializeAsync(settings);
_isInitialized = true;
}
catch (UnauthorizedAccessException)
{
Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString());
}
Have a closer look at the sample to see how to get all the details. Or, to have a walkthrough, you can watch the camera session from the recent //build/ conference, which includes a little bit of a walkthrough through some camera samples.
Here is how to get the device's available cameras and set the front one for the stream:
mediaCaptureManager = new MediaCapture();
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
var deviceInfo = devices[0]; //grab first result
foreach (var device in devices)
{
if (device.Name.ToLowerInvariant().Contains("front"))
{
deviceInfo = frontCamera = device;
hasFrontCamera = true;
}
if (device.Name.ToLowerInvariant().Contains("back"))
{
rearCamera = device;
}
}
var mediaSettings = new MediaCaptureInitializationSettings
{
MediaCategory = MediaCategory.Communications,
StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo,
VideoDeviceId = deviceInfo.Id
};
await mediaCaptureManager.InitializeAsync(mediaSettings);
You'll need to consider rotation because front and rear cameras on different devices have different rotations, but this will initialize your MediaCapture properly

MediaCapture.CapturePhotoToStreamAsync() and MediaCapture.CapturePhotoToStorageFileAsync() throw Argument exception

I'm trying to create an app that can use the camera for Windows Phone 8.1, using the Windows RT/XAML development model.
When I try to call either of the capture methods off of the MediaCapture class I get an ArgumentException with the message "The parameter is incorrect." Here is my code
private async Task Initialize()
{
if (!DesignMode.DesignModeEnabled)
{
await _mediaCaptureMgr.InitializeAsync();
ViewFinder.Source = _mediaCaptureMgr;
await _mediaCaptureMgr.StartPreviewAsync();
}
}
private async void ViewFinder_OnTapped(object sender, TappedRoutedEventArgs e)
{
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var stream = new InMemoryRandomAccessStream();
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
_bitmap = new WriteableBitmap((int) ViewFinder.ActualWidth, (int) ViewFinder.ActualHeight);
stream.Seek(0);
await _bitmap.SetSourceAsync(stream);
PreviewImage.Source = _bitmap;
PreviewElements.Visibility = Visibility.Visible;
ViewFinder.Visibility = Visibility.Collapsed;
Buttons.Visibility = Visibility.Visible;
Message.Visibility = Visibility.Collapsed;
stream.Seek(0);
var buffer = new global::Windows.Storage.Streams.Buffer((uint) stream.Size);
stream.ReadAsync(buffer, (uint) stream.Size, InputStreamOptions.None);
DataContext = buffer.ToArray();
if (PhotoCaptured != null)
PhotoCaptured(this, null);
}
The initialize method is called on page load, and the viewfinder_ontapped is called when they tap the CaptureElement I have in the xaml. The error is thrown on
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
What's really bizarre is that I downloaded the latest source for the winrt xaml toolkit http://winrtxamltoolkit.codeplex.com/ and tried their sample camera app, which uses similar code. It throws the same error on MediaCapture.CapturePhotoToStorageFileAsync(). Can anyone help me identify why?

Got a SIGSEGV while setting the Text of my TextField from a ABPeoplePickerModule

In my App the User needs to type in some Address Information.
I provide an Addressbook Button for that since Version 1.0.
That worked fine in my previous tests, but now I get a SIGSEGV when I try to set my UITextField.Text property. This error occurs everytime when I try to Pick an Address from the PeoplePicker in MonoTouches Debug mode, when I try that on my iPhone the eror occurs randomly between setting the TextFields and pushing the next ViewController.
Is There anything wrong in my Code or is it a bug?
//AB Button Event
addressBook.TouchUpInside += delegate {
//Create new Picker
ABPeoplePickerNavigationController PP = new ABPeoplePickerNavigationController();
//Cancel Event
PP.Cancelled += delegate {
NavigationController.DismissViewController(true, null);
};
//Select Event
PP.SelectPerson += delegate(object sender, ABPeoplePickerSelectPersonEventArgs e) {
//Detailed Person View
ABPersonViewController pv = new ABPersonViewController();
//Action when clicked on a Property
pv.PerformDefaultAction += delegate(object person, ABPersonViewPerformDefaultActionEventArgs ev) {
//If the Property was an Address
if(ev.Property.ToString() == "Address"){
string lands = "", orts = "", plzs = "";
try{
//Read the Detailed Address Data from the clicked property
ABMultiValue<PersonAddress> addresses = ev.Person.GetAllAddresses();
PersonAddress[] values = addresses.GetValues();
lands = values[ev.Identifier.Value].Country.ToString();
orts = values[ev.Identifier.Value].City.ToString();
plzs = values[ev.Identifier.Value].Zip.ToString();
}catch{
Console.WriteLine("Fehlerhafte Addresse");
}
//Set the Textfield with the new information
//iPhone Simulator in Debugmode crashes here everytime
land.Text = lands;
ort.Text = orts;
plz.Text = plzs;
//Close the Module
NavigationController.DismissViewController(true, null);
}
};
//Set selected Person for the person View
pv.DisplayedPerson = e.Person;
//Open Person View with navigation from the PeoplePicker Controller
PP.PushViewController(pv, true);
};
//Open PeoplePicker Controller Module
NavigationController.PresentViewController(PP, true, null);
};
Thanks in advance!
The just released MonoTouch 6.0.5 has a fix for a similar issue.

Activating views in regions in Prism

I have problem that I don't seem to be able to solve. I have a created a test project, using MEF and Prism4. I've created a test project where I have 2 views and each of them register themselves inside a region, and also a button in another region. When the button is clicked, I want the view of change to the correct view. The code I think is wrong is below, anyone have any ideas what I am doing wrong here ?
public void Initialize()
{
regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(Views.Module1View));
Button button = new Button() { Content = "Module1" };
button.Click += (o, i) =>
{
var region = this.regionManager.Regions[RegionNames.MainRegion];
if (region != null)
{
region.Activate(typeof(Views.Module1View));
}
};
regionManager.AddToRegion(RegionNames.NavigationRegion, button);
}
I get the following error ...
The region does not contain the specified view.
Parameter name: view
Solved it - amazing what a good nights sleep will do! I had to get the view from the ServiceLocator.
public void Initialize()
{
regionManager.RegisterViewWithRegion(RegionNames.MainRegion, () =>
ServiceLocator.Current.GetInstance<Views.Module2View>());
Button button = new Button() { Content = "Module2" };
button.Click += (o, i) =>
{
var view = ServiceLocator.Current.GetInstance<Views.Module2View>();
var region = this.regionManager.Regions[RegionNames.MainRegion];
if (region != null)
{
region.Activate(view);
}
};
regionManager.AddToRegion(RegionNames.NavigationRegion, button);
}

Resources