Xamarin Form - TaskCanceledException thrown on ScanFilesToFolderAsync - c#

in my UWP application i am working on scan functionality. in this application user can scan the document through scanner by selecting flatbed or auto feeder.Now problem is when i am trying to scan it gives the en exception a Task was canceled.
please help..
thanks in advance. :)
have a great day... :)
private async void Btnscan_Click(object sender, RoutedEventArgs e)
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
//set the destination folder name for scan images.
DeviceInformationDisplay selectedScanner = CmbScannerList.SelectedItem as DeviceInformationDisplay; // here i got the selected scanner.
// scanner id is := "\\\\?\\ROOT#IMAGE#0000#{6bdd1fc6-810f-11d0-bec7-08002be2092f}"
ScanToFolder(selectedScanner.id, folder);
}
function Scan To folder
public async void ScanToFolder(string deviceId, StorageFolder folder)
{
try
{
cancellationToken = new CancellationTokenSource();
ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);
if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Flatbed))
{
var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Flatbed, folder).AsTask(cancellationToken.Token); // through an exception(A Task Was Canceled):(
Utils.DisplayImageAndScanCompleteMessage(result.ScannedFiles, DisplayImage);
}
}
catch (Exception ex)
{
// here i got the exception.
}
}
Updated :
Now i am set the DeviceClass to ALL.
private void StartWatcher()
{
resultCollection.Clear();
DeviceWatcher deviceWatcher;
deviceWatcher = DeviceInformation.CreateWatcher(DeviceClass.All); // set Image scanner to all.
deviceWatcherHelper.StartWatcher(deviceWatcher);
}
After run the project in scanner list i got the all connected devices in which i got my scanner name This : when i am trying to pass this name it gives error in imagescanner System.Exception: 'Exception from HRESULT: 0x80210015' means device not found.
Now i am chnage all to ImageScanner i got nothing in scanner list.
and in scanner HP application i got this name. and IT Scan Well :( in scanner list i don't got this name in my application. :(
on my pc setting -> devices -> scanner and printers i got those name.

Rewriting the resolution of the problem as an answer. I tested the code on my machine where it behaved correctly and argued the problem is most likely a driver issue. This has been confirmed by the OP and reinstall of the driver helped make the scanning work again.

Related

I want to use StartRecordingToFileAsync function in UWP

I want to record screen audio using AppRecordingManager in UWP.
I found StartRecordingToFileAsync function in AppRecordingManager Class to write audio and video content in UWP.
Here is the official document URL about this function:
https://learn.microsoft.com/en-us/uwp/api/windows.media.apprecording.apprecordingmanager.startrecordingtofileasync#Windows_Media_AppRecording_AppRecordingManager_StartRecordingToFileAsync_Windows_Storage_StorageFile_
Although I try to use this function to record audio, I always keep getting this error:
The request is invalid in the current state. (Exception from HRESULT: 0xC00D36B2)
I can not find solution for StartRecordingToFileAsync.
How can I solve this error?
Here is my c# code giving me this error.
AppRecordingManager manager = AppRecordingManager.GetDefault();
var status = manager.GetStatus();
if (status.CanRecord || status.CanRecordTimeSpan)
{
var myVideo = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Videos);
StorageFolder projectFolder = await myVideo.SaveFolder.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
var audio = await projectFolder.CreateFileAsync("audio_record.wav", CreationCollisionOption.GenerateUniqueName);
var result = await manager.StartRecordingToFileAsync(audio);
if (result.Succeeded)
{
Debug.WriteLine(result.Succeeded);
}
else
{
Debug.WriteLine(result.ExtendedError.Message);
}
}
I managed to reproduce same error with your code.
But when I changed "audio_record.wav" to "audio_record.mp4" it worked and it saved video to specified location.
Since documentation states that StartRecordingToFileAsync "Writes audio and video content of the current app" it's possible that you can't save just audio using that method.

FilePicker Windows Phone 8.1

This code worked when wanna pick an image in PicturesLibrary:
ImagePath = string.Empty;
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.**PicturesLibrary**;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
I created a folder which contained images of my app.
So I'd like to change the location to open: "PicturesLibrary" into "myFolder".
How can I do that?
Thank for reading! Have a beautiful day!
The ".SuggestedStartLocation" is not supported/functional in windows phone 8.1.
For my camera app i used this:
Inventory all folders in the pictures library:
string savefolder, selectedfilename;
private async void changefolder_button_click(object sender, RoutedEventArgs e)
{
folderlist_box.Items.Clear();
IReadOnlyList<StorageFolder> folderlist = await KnownFolders.PicturesLibrary.GetFoldersAsync();
string folder_read = "";
foreach (StorageFolder folder in folderlist)
{
if (folder.Name != folder_read)
//Filter duplicate names like "Camera Roll" from libraries on phone and SDCard (if any).
//Which one is used depends on: Settings -> Storage Sense.
{
folder_listbox.Items.Add(folder.Name);
folder_read = folder.Name;
}
}
}
Select the folder you want:
public void folder_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
savefolder = folder_listbox.SelectedItem.ToString();
get_files();
}
Get files in picture library subfolder:
private async void get_files()
{
file_listbox.Items.Clear();
StorageFolder currentfolder = await KnownFolders.PicturesLibrary.GetFolderAsync(savefolder);
IReadOnlyList<StorageFile> filelist = await currentfolder.GetFilesAsync();
foreach (StorageFile file in filelist)
{
file_listbox.Items.Add(file.Name);
}
}
Select the file:
public void file_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedfilename = file_listbox.SelectedItem.ToString();
}
The FileOpenPicker cannot be suggested to the custom location no matter it's a phone app or windows store app.
The FileOpenPicker is not designed for users to access all folders on the device. Actually, we can treat it as a way to give user the oppotunity to get access to some user awared locations(like the picture library). By default, an app can access certain file system locations. By having the FileOpenPicker or by declaring capabilities, you can access some additional file system locations. So don't expect it will work as the FileOpenDialog we previously used for windows desktop app.
Something I do agree in mcb's answer is the suggested method to access the sub folders(or your app's local storage folder) that is using a list to show the folder list or file list to enable user access it.
Something I cannot agree in mcb's answer is "The ".SuggestedStartLocation" is not supported/functional in windows phone 8.1.". That is not the truth, it should be supported by windows phone 8.1 but not all options work on the phone.

Windows 8 GetFileAsync method gives UnAuthorized error

The below code an attempt to try and get get an Mp3 file from the MusicLibrary
It gives me,
A first chance exception of type
'System.UnauthorizedAccessException'
occurred in AccessingPictures.exe
This is my code:
public async void getFile()
{
StorageFolder folder = KnownFolders.MusicLibrary;
try
{
sampleFile = await folder.GetFileAsync("Test1.mp3");
}
catch (FileNotFoundException e)
{
// If file doesn't exist, indicate users to use scenario 1
Debug.WriteLine(e);
}
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
getFile();
}
Wouldn't we able to access the media files?
I am able to do this using the file picker.
But it does not work while i try to access it directly.
Am i missing anything here ?
To retrieve Pictures from Camera Roll
Void GetCameraPhotos()
{
using (var library = new MediaLibrary())
{
PictureAlbumCollection allAlbums = library.RootPictureAlbum.Albums;
PictureAlbum cameraRoll = allAlbums.Where(album => album.Name == "Camera Roll").FirstOrDefault();
var CameraRollPictures = cameraRoll.Pictures
}
}
You cannot access the files unless it is in response to a user request. i.e. the user must tap a button or something and that tap logic ends up calling your code that accesses the file. If you want to get at the file afterwards, you'll need to copy it in the app's data folder.
I finally figured the issue. It was because i hadn't enabled the capabilities in the Manifest file.
It works like a charm now.
Thanks everyone.

ZXing.Net.Mobile scan doesn't trigger

I'm currently trying to implement this compontent into my android application built with Xamarins mono for andriod.
I'm having this issue that I can't get any result returned back from the scanner.Scan(); method, the scanner starts and nothing happens?!
So I've tried downloading the sample projects from github and when I try scanning barcodes using the sample code provided there it's the same problem. It will not fire. Here is some of the code responsible for starting the scanner and handeling the result:
public async void ScanArticleNumber()
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of the default overlay
scanner.TopText = "Hold the camera up to the barcode\nAbout 6 inches away";
scanner.BottomText = "Wait for the barcode to automatically scan!";
//Start scanning
var result = await scanner.Scan();
HandleScanResult(result);
}
void HandleScanResult(ZXing.Result result)
{
string msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
msg = "Found Barcode: " + result.Text;
else
msg = "Scanning Canceled!";
Activity.RunOnUiThread(() =>
{
Toast.MakeText(Activity.BaseContext, msg, ToastLength.Short).Show();
});
}
The code never reaches the HandleScanResult method even tho I'm shooting loads of barcodes with the camera.
Any ideas why?
Problem was solved by downloadning the latest version of ZXing.Net.Mobile from Github
and then running that sample project and taking the following dlls from the bin folder:
ZXing.Net.Mobile.dll
zxing.monoandroid.dll
Xamarin.Android.Support.v4.dll
I replaced my current ddls with these and it worked! This is probably because I from first downloaded the dlls from xamarin components, the files was probably not up to date.
Hope this helps.

LockScreen.SetImageFileAsync(...) causes UnauthorizedAccessException

I'm trying to set background image on lock screen in my WinRT app. But when this code is being executed i get an UnauthorizedAccessException with message:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
The code was taken from MSDN and looks like OK.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var imagePicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" },
};
var imageFile = await imagePicker.PickSingleFileAsync();
if (imageFile != null)
{
await LockScreen.SetImageFileAsync(imageFile);
}
}
The exception described below is thrown in this line of code:
await LockScreen.SetImageFileAsync(imageFile);
By the way, i've tried to install some applications which can change your background on lock screen, but all of them show error or just crash. Maybe something is wrong with my OS version?
Does anyone know how to solve this problem? Please help!
You need access to the Pictures Library.
Set it by opening your Package.appxmanifest, goto Capabilities and check Pictures Library.
I faced with exactly the same problem. The problem was that my OS wasn't activated. Check this thing on your computer's properties. Hope it helps.
I guess Its some kind of privilege problem may be admin .
Try a work around by applying this code
private async void Button_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var bytes = await client.GetByteArrayAsync(new Uri("http://transfer-talk.com/wp-content/uploads/Kaka-Real-Madrid.jpg"));
StorageFile sf = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("test.jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sf, bytes);
//var imageFile = await imagePicker.PickSingleFileAsync();
//if (imageFile != null)
{
await LockScreen.SetImageFileAsync(sf);
}
}
it will download an Image and set . Not giving an exception in my case neither your code nor mine.
download this sample and try running and see if error exist lock screen sample
also try setting the stream rather using storage file.
await LockScreen.SetImageStreamAsync(await sf.OpenReadAsync());
try and let me know :)

Categories

Resources