Windows 8 GetFileAsync method gives UnAuthorized error - c#

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.

Related

Xamarin Form - TaskCanceledException thrown on ScanFilesToFolderAsync

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.

Grabbing Dropbox access token on Windows Form using Dropbox API

I have done a class which already works with the Dropbox API uploading files, downloading, deleting and so on. It has been working quite well since I was just using my own access token, but I need to register other users and a single but "big" problem appeared: retrieving the access token.
1.- Redirect URI? I'm starting to doubt why do I need this. I finally used this URI (https://www.dropbox.com/1/oauth2/redirect_receiver) because "The redirect URI you use doesn't really matter" Of course I included this one on my app config on Dropbox.
2.- I reach the user's account (I can see the user's count increased and I see the app has access to the user's account.
3.- I have a breakpoint on my code to inspect the variables in order to apply the DropboxOAuth2Helper.ParseTokenFragment but I have no success on there.
This is my code, but on the if before the try catch is where it gets stuck:
string AccessToken;
const string AppKey = "theOneAtmyAppConfigOnDropbox";
const string redirectUrl = "https://www.dropbox.com/1/oauth2/redirect_receiver";
string oauthUrl =
$#"https://www.dropbox.com/1/oauth2/authorize?response_type=token&redirect_uri={redirectUrl}&client_id={AppKey}";
private string oauth2State;
private bool Result;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Start(AppKey, webBrowser1);
webBrowser1.Navigating += Browser_Navigating;
}
private void Start(string appKey, WebBrowser w)
{
this.oauth2State = Guid.NewGuid().ToString("N");
Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OauthResponseType.Token, appKey, redirectUrl, state: oauth2State);
w.Navigate(authorizeUri);
}
private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (!e.Url.ToString().StartsWith(redirectUrl, StringComparison.InvariantCultureIgnoreCase))
{
// we need to ignore all navigation that isn't to the redirect uri.
return;
}
try
{
OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Url);
if (result.State != this.oauth2State)
{
// The state in the response doesn't match the state in the request.
return;
}
this.AccessToken = result.AccessToken;
this.Result = true;
}
catch (ArgumentException)
{
// There was an error in the URI passed to ParseTokenFragment
}
finally
{
e.Cancel = true;
this.Close();
}
}
I've been fighting against this for hours and I'm starting to see the things a little cloudy at this point.
This is the tutorial I used, but I'm not moving forward. I would really appreciate any help!
EDIT: I finally made some steps forward. I changed the line which contains
Uri authorizeUri2 = DropboxOAuth2Helper.GetAuthorizeUri(appKey);
Now I'm showing the generated access token on the WebClient! Bad part comes when trying to get it (it gets inside the if) and it gets generated every time I ask the user for permission, so it gets overwrited.
EDIT 2: I noted the token I get generated on the browser is somehow malformed. I try to manually change it hardcored when I'm debugging and I get an exception when an AuthException when creating the DropboxClient object :( What the hell!
As Greg stated, the solution was using the event Browser_Navigated. Looks like the version of the embedded IE my Visual Studio (2015) uses didn't notice that if it's a redirect, it won't launch the event BrowserNavigating.

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 :)

Why can't I delete files I created in code in Metro style apps?

I can create, read from and edit files created by my application in my Metro style app, but it won't let me delete (and yes, I do have the necessary Declarations and File type associations set) them!
I get Access is denied. message, for the same code that is used (and works) in the Windows 8 Metro File Acccess sample:
private async void RemoveNote_Click(object sender, RoutedEventArgs e)
{
try
{
StorageFile file = await KnownFolders.DocumentsLibrary.GetFileAsync(NotesList.SelectedItem.ToString());
if (file != null)
{
await file.DeleteAsync();
file = null;
}
notes.RemoveAt(NotesList.Items.IndexOf(NotesList.SelectedItem));
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
Can somebody please help?
Did you forget to close a file stream somewhere?

Writing to a file using FileSavePicker

I'm having a little difficulty figuring out what the cause of this error is. I've added FilePicker capabilities in the Manifest, and it's not like I'm trying to do anything crazy; just trying to save to a sub folder within the Documents folder...
Error: "An unhandled exception of type
'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access is denied. (Exception from HRESULT:
0x80070005 (E_ACCESSDENIED))"
I have confirmed that my User Account is Admin and that it has Full Control over folders and files. But I'm not sure what else I can try.
public void NewBTN_Click(object sender, RoutedEventArgs e)
{
var mbox = new MessageDialog("Would you like to save changes before creating a new Note?", "Note+ Confirmation");
UICommand YesBTN = new UICommand("Yes", new UICommandInvokedHandler(OnYesBTN));
UICommand NoBTN = new UICommand("No", new UICommandInvokedHandler(OnNoBTN));
mbox.Commands.Add(YesBTN);
mbox.Commands.Add(NoBTN);
mbox.DefaultCommandIndex = 1;
mbox.ShowAsync().Start();
}
async void OnYesBTN(object command)
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
{
// User clicked yes. Show File picker.
HasPickedFile = true;
}, this, null);
if (HasPickedFile)
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Cascading Stylesheet", new List<string>() { ".css" });
savePicker.FileTypeChoices.Add("Hypertext Markup Language", new List<string>() { ".html" });
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default extension if the user does not select a choice explicitly from the dropdown
savePicker.DefaultFileExtension = ".txt";
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Note";
StorageFile savedItem = await savePicker.PickSaveFileAsync();
if (null != savedItem)
{
// Application now has read/write access to the saved file
StorageFolder sFolder = await StorageFolder.GetFolderFromPathAsync(savedItem.Path);
try
{
StorageFile sFile = await sFolder.GetFileAsync(savedItem.FileName);
IRandomAccessStream writeStream = await sFile.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream oStream = writeStream.GetOutputStreamAt(0);
DataWriter dWriter = new DataWriter(oStream);
dWriter.WriteString(Note.Text);
await dWriter.StoreAsync();
oStream.FlushAsync().Start();
// Should've successfully written to the file that Windows FileSavePicker had created.
}
catch
{
var mbox = new MessageDialog("This file does not exist.", "Note+ Confirmation");
UICommand OkBTN = new UICommand("Ok", new UICommandInvokedHandler(OnOkBTN));
mbox.Commands.Add(OkBTN);
mbox.DefaultCommandIndex = 1;
mbox.ShowAsync().Start();
}
}
}
}
public void OnOkBTN(object command)
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
{
// Do something here.
}, this, null);
}
public void OnNoBTN(object command)
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
{
// Don't save changes. Just create a new blank Note.
Note.Text = String.Empty;
}, this, null);
}
How can I write to a file that was created by the FileSavePicker?
You don't need to call StorageFolder.GetFolderFromPathAsync(savedItem.Path) and sFolder.GetFileAsync(savedItem.FileName). You must remove these two lines because they throw exception.
You should use the StorageFile object which has been returned by method savePicker.PickSaveFileAsync(), because that object has all permissions. Then you can simply call savedItem.OpenAsync(FileAccessMode.ReadWrite).
You probably do not have "Document Library Access" enabled in the capabilities portion of the appxmanifest of your app. Without this capability, windows will restrict access to the file system. There are similar capabilities for music, video, and picture libraries.
You have already added "File Picker" to the declarations portion, which is probably not what you want. The "File Picker" declaration indicates that if some other application invokes the file picker, your app will be listed as a possible source of files.
I've also found that adding Video or Picture Libraries access capability in Manifest only takes effect after restarting Windows 10.
Maybe it is an issue with my computer, but I think it is worth to share.

Categories

Resources