LockScreen.SetImageFileAsync(...) causes UnauthorizedAccessException - c#

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

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.

Windows Phone 8.1 app to share image - works fine on my phone with Visual Studio debugger attached, but crashes when run without the debugger

I'm trying to share an image through my app, everything works just fine when I run the app on my phone through visual studio, but when I try to run it from my phone, it crashes everytime I click the share button
private async void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
args.Request.Data.Properties.Title = "Let's Celebrate";
args.Request.Data.Properties.Description = "It's time to celebrate!";
DataRequestDeferral deferral = args.Request.GetDeferral();
try
{
var finalImg = await GenerateImage();
var folder = Package.Current.InstalledLocation;
const CreationCollisionOption option = CreationCollisionOption.ReplaceExisting;
var file = await folder.CreateFileAsync("letscelebrateshare.png", option);
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var pixelBuffer = await finalImg.GetPixelsAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)finalImg.PixelWidth,
(uint)finalImg.PixelHeight,
logicalDpi,
logicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
StorageFile logoFile =
await Package.Current.InstalledLocation.GetFileAsync("letscelebrateshare.png");
List<IStorageItem> storageItems = new List<IStorageItem>();
storageItems.Add(logoFile);
args.Request.Data.SetStorageItems(storageItems);
}
}
finally
{
deferral.Complete();
}
}
private async void bla... [..]
{
Exception exc= null;
try
{
//All your stuff
}
catch(Exception ex)
{
exc = ex;
}
if(exc!=null)
await msg.ShowAsync();
}
Edit: Since I don't use WP in C#. I guess you could try this. Hope this helps ^^
I had the same issue while opening a file open picker. I found a weird solution. When I removed the navigation parameters in every pages and used static variables instead, worked fine for me. I guess this will help you
If the App is there crashing without debugger, try while debugging and the share targets are visible to "suspend and shutdown" ("Lifecycle Events" in visual studio). In most cases you app will then crash because it is suspended and serialize the data.

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.

Connecting Windows 8 App with Skydrive and Uploading File issue in c#

async private void uploadtosky_Click(object sender, RoutedEventArgs e)
{
try
{
LiveAuthClient auth = new LiveAuthClient();
LiveLoginResult log = await auth.LoginAsync(new List<string> { "wl-basic", "wl.skydrive", "wl.signin" });
if (log.Status == LiveConnectSessionStatus.Connected)
{
LiveConnectClient uploadcl = new LiveConnectClient(auth.Session);
LiveOperationResult up = await uploadcl.BackgroundUploadAsync("me/skydrive", heading.Text, samplefile, OverwriteOption.Overwrite);
}
}
catch
{
MessageDialog msg = new MessageDialog("Oops ! something went wrong while trying to connect");
msg.ShowAsync();
}
}
When I execute the snippet the messagebox showing Oops ! something went wrong while trying to connect. My computer is connected to the internet and on clicking the button for uploading, I get a sign in page to live account in the Windows 8 app. However I guess it can't login to the account and so the exception occurs. Any idea to overcome this problem?
How big is your file? Is it larger than 300MB? I remember that large files have some problems with uploading.
found the answer finally . Actually there is a need to replace auth.Session as log.Session ( in the line LiveConnectClient uploadcl = new LiveConnectClient(auth.Session); ) and add a scope called wl.skydrive_update in LiveLoginResult log = await auth.LoginAsync(new List<string> { "wl-basic", "wl.skydrive", "wl.signin" });
Thats it !

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?

Categories

Resources