UWP release build crashes but not in Visual Studio - c#

The app Works perfectly fine when I deploy it from VS 2015 (Windows 10)
But the story is very different when I create the build from "Store > Create App Packages...", then install the app from the app from the powershell script.
I have isolated the problem to a section where I set an image for the lock screen. Whenever I click yes on the message dialog to change the lock screen I get a crash, I have attached the debugger and I only get the following exception:
Exception thrown at 0x00007FFA61091F08 (KernelBase.dll) in
ApplicationFrameHost.exe: 0x80010012:
The callee (server [not server application]) is not available
and disappeared; all connections are invalid. The call did not execute.
The code to reproduce the error is based on the following article:
https://msdn.microsoft.com/en-us/windows.system.userprofile.userprofilepersonalizationsettings.trysetlockscreenimageasync
public async Task<bool> ChangeLockScreenBackground()
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
var uri = new Uri("ms-appx:///Assets/SplashScreen.scale-400.png");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetLockScreenImageAsync(file);
}
return success;
}
I have no idea what is going on, I thought it was the capabilities of the app.
But I have enabled User Account Information and Pictures Library and still no luck :(

Looks that you're using a file already opened: SplashScreen* and also from that folder may be you can't set the wallpaper.
Pay Attention: "Your app can't set wallpapers from any folder. Copy file in ApplicationData.Current.LocalFolder and set wallpaper from there"
So I have changed the code a Little bit and also I put attention to documentation:
Remarks
Caution For the mobile device family, you can only set a lock screen image that is smaller than 2 megabytes (MB). Attempting to set
a lock screen image that is larger fails, even though the async
operation returns true.
Caution When you set an image more than once, the new image file must have a different name than the previously set image. If you set a
new image using a file with the same name as the previous image, it
will fail.
In this code I'm adding a file to Visual Studio Project in a folder called img, and setting the image properties to "Copy if newer". Then I load the image from such location.
async Task<bool> SetWallpaperAsync(string localAppDataFileName)
{
bool success = false;
var uri = new Uri($"ms-appx:///img/{localAppDataFileName}");
//generate new file name to avoid colitions
var newFileName = $"{Guid.NewGuid().ToString()}{Path.GetExtension(localAppDataFileName)}";
if (UserProfilePersonalizationSettings.IsSupported())
{
var profileSettings = UserProfilePersonalizationSettings.Current;
var wfile = await StorageFile.GetFileFromApplicationUriAsync(uri);
//Copy the file to Current.LocalFolder because TrySetLockScreenImageAsync
//Will fail if the image isn't located there
using (Stream readStream = await wfile.OpenStreamForReadAsync(),
writestream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(newFileName,
CreationCollisionOption.GenerateUniqueName)
)
{ await readStream.CopyToAsync(writestream); }
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(newFileName);
success = await profileSettings.TrySetLockScreenImageAsync(file);
}
Debug.WriteLine(success);
return success;
}
This code works perfectly in Windows Mobile 10, and because this is an Universal App you should expect it runs same way in Windows 10 Apps... and yes.
Letme know if this was enough for you.

Related

Unable to access files on Windows 8.1 phone device

I am using Json files for local storage for my app. While using Visual Studio's emulator reading and writing to the files works correctly. When I connect a device and try to run on that device I cannot access my Json files.
My json files are set to Content and Copy always.
Here is my try statement for reading the file. I have tried two main ways to access the file Current.InstalledLocation and Uri("ms-appx:///). Both seem to work in the emulator but neither work on the device.
try
{
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder folder = await package.GetFolderAsync("Data");
StorageFile file = await folder.GetFileAsync("Users.json");
//Uri dataUri = new Uri("ms-appx:///Data/Users.json");
//StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
string jsonText = await FileIO.ReadTextAsync(file);
JsonArray jsonArray = JsonArray.Parse(jsonText);
foreach (JsonValue userValue in jsonArray)
{
//Build my model object out of json
}
}
catch(Exception e)
{
//Creating instance for the MessageDialog Class
//and passing the message in it's Constructor
MessageDialog msgbox = new MessageDialog(e.Message);
//Calling the Show method of MessageDialog class
//which will show the MessageBox
await msgbox.ShowAsync();
}
The Output Window Displays:
Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
Edit:
The try catch loop is not catching the exceptions related to the file system access problem.
On startup when stepping through I am failing out at StorageFile file = await folder.GetFileAsync("Users.json");
Why I trigger the function through a button I fail at string jsonText = await FileIO.ReadTextAsync(file);
The device I am looking to run my application on is running Windows Embedded 8.1 Handheld update 2 (its a ToughPad Panazonic FZ-E1). Do I need to to targeting windows 8.1 instead of windows phone 8.1? It has been working fine with phone up until this point controlling the POS bar-code scanner.
Any help would be appreciated I am at a loss. Could my issue be caused by settings on the device?
Try using a stream reader on it like below:
var myStream = await (await Package.Current.InstalledLocation.GetFolderAsync("Data")).OpenStreamForReadAsync("Users.json");
Check the properties of the json file. Right click the file-> Properties.
Check the copy to output directory and select copy always option in the menu.
That should help.

How to display an image from a network folder or local drive in a Windows Universal App

I'm having trouble displaying an jpg in an Image control in a Windows Universal App. (I had the same problem trying to create a Windows 8 Store app as well)
I have a simple form with an Image control on it. All I want to do is be able to open images in a folder on my local drive or a network drive on my local network and display them. But I am not having any luck. The only thing I get is E_NETWORK_ERROR, with no additional information.
I assume it probably has something to do with security, but surely there must be a setting or permission to allow me to do it. I tried enabling Private Networks in the Capabilities tab of the manifest, but that didn't help. I don't see anything in Declarations that sounds like what I need.
I know UWP apps are somewhat sandboxed, but if you can't even access local files, what good are they?
Here is a sample of code I have tried. I've done other iterations as well, but they all have the same end result.
Xaml:
<Image Name="Image1"/>
Code behind:
public LoadImage()
{
var bitmap = new BitmapImage();
bitmap.ImageFailed += Bitmap_ImageFailed;
bitmap.UriSource = new Uri(#"D:\Users\Steve\Documents\SomeImage.JPG", UriKind.Absolute);
Image1.Source = bitmap;
}
private void Bitmap_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
Debug.Write(e.ErrorMessage);
}
When I run it, I end up in the Bitmap_ImageFailed event and the ErrorMessage property is simply "E_NETWORK_ERROR", and nothing is displayed in the Image. Not very helpful.
What am I missing? It has to be something simple and obvious that I am overlooking.
Update:
Thanks to all the suggestions here I was able to get it going. The part I was failing to get through my skull was that you can't just give it a folder and expect it to read a file, even as a "quick & dirty test". You have to go through "proper channels" to get there. I pieced it all together and came up with this example which displays the first image in the selected folder:
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add(".jpg");
folderPicker.FileTypeFilter.Add(".tif");
folderPicker.FileTypeFilter.Add(".png");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
var files = await folder.GetFilesAsync();
var bitmap = new BitmapImage();
bitmap.ImageFailed += Bitmap_ImageFailed;
var stream = await files.First().OpenReadAsync();
await bitmap.SetSourceAsync(stream);
Image1.Source = bitmap;
}
}
In addition, I had to add the file types for .jpg, .tif and .png as well as File Open Picker to the Declarations.
You can figure out all necessary information in MSDN article File access permissions
In addition to the default locations, an app can access additional files and folders by declaring capabilities in the app manifest (see App capability declarations), or by calling a file picker to let the user pick files and folders for the app to access (see Open files and folders with a picker).
So if you want to read a file from users document folder you need to update your applications AppXManifest to request the Document Library Access capability.
You also need to update your AppXManifest by declaring what file type(s) you want to access. Then, even with access to the folders, you only have access to a limited set of file types. You have to specify supported files types on Declarations tab
I set a new file type (.txt) and let it role from there. And code example
async void Button_Click_2(object sender, RoutedEventArgs e)
{
var _Name = "HelloWorld.txt";
var _Folder = KnownFolders.DocumentsLibrary;
var _Option = Windows.Storage.CreationCollisionOption.ReplaceExisting;
// create file
var _File = await _Folder.CreateFileAsync(_Name, _Option);
// write content
var _WriteThis = "Hello world!";
await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis);
// acquire file
try { _File = await _Folder.GetFileAsync(_Name); }
catch (FileNotFoundException) { /* TODO */ }
// read content
var _Content = await FileIO.ReadTextAsync(_File);
await new Windows.UI.Popups.MessageDialog(_Content).ShowAsync();
}

W10 UWP - Set remote image as desktop wallpaper / lockscreen

I'm trying to set a remote image as the desktop wallpaper / phone lockscreen in my W10 UWP app:
string name = "test_image.jpg";
Uri uri = new Uri("http://www.ucl.ac.uk/news/news-articles/1213/muscle-fibres-heart.jpg");
// download image from uri into temp storagefile
var file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri));
// file is readonly, copy to a new location to remove restrictions
var file2 = await file.CopyAsync(KnownFolders.PicturesLibrary);
// test -- WORKS!
//var file3 = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Design/1.jpg"));
// try set lockscreen/wallpaper
if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // Phone
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file2);
else // PC
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file2);
file1 doesn't work as it is read-only, so I copy it to a new location (pictures library) to remove restrictions -> file2.
Note: file3 works, so I'm not sure what's happening -- I assume TrySetWallpaperImageAsync/TrySetLockScreenImageAsync only accepts msappx local files...
Anyone have any ideas on work arounds?
Thanks.
Save your remote image to ApplicationData.Current.LocalFolder first, then use TrySetWallpaperImageAsync/TrySetLockScreenImageAsync and point to the saved image instead of directly referencing the remote image should work.

UnauthorizedAccessException when trying to save a photo to the same file a second time

So, the code below allows me to take a picture. I then display the picture. My XAML is bound to the Photo property of the Vehicle object. It works fine, until I go in and try to take a picture again. I then get an UnauthorizedAccessException. I create the file in 'LocalStorage', so I don't believe I need special permissions to write files there. I'm not sure what is causing the error.
public async Task TakePicture()
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
StorageFile photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
var targetFolder = ApplicationData.Current.LocalFolder;
var targetFile = await targetFolder.CreateFileAsync(String.Format
("VehiclePhoto{0}.jpg", this.Vehicle.PrimaryKey), CreationCollisionOption.ReplaceExisting);
if (targetFile != null)
{
await photo.MoveAndReplaceAsync(targetFile);
this.Vehicle.Photo = String.Format("ms-appdata:///local/VehiclePhoto{0}.jpg", this.Vehicle.PrimaryKey);
}
}
}
I assume that StoragePhoto encapsulates some kind of File I/O under the hood. You must properly dispose these objects in order to release the underlying unmanaged OS resources that will keep "hooks" into the file. If you don't dispose them, the application will keep access to the file open, which is probably why your second access to the file gives you an exception (the first access still remains). Show me the StoragePhoto code and I can get more specific.
On another note, if this application is multi-threaded, you should create granular semaphores/locks around writing the files to disk (perhaps by interning the physical path string and locking on that reference) to ensure you don't try to write the same file to disk at the same physical path at the same time - that would be bad.

Windows 8 URI Launcher won't launch image and document paths

I'm trying to launch a file (document, picture,...) from my Windows 8 app using the Launcher API but the file won't open with the default program associated with it.
Following code runs when clicked on a file:
AttachedFile file = e.ClickedItem as AttachedFile;
bool isLaunched = await Launcher.LaunchUriAsync(new Uri(file.Path, UriKind.Absolute));
//isLaunched is false
The specified path is an absolute path that works when pasting it into the File Explorer. (C:\Users...\file.txt)
Using the Launcher with a StorageFile returns an error because the app doesn't have the permissions to edit the file.
Do you need a programmatic access to the files outside of the local folder or the libraries? Sorry, there is no API for this.
var fold = Windows.Storage.KnownFolders.DocumentsLibrary;
var f1 = await fold.GetFileAsync("hi.txt");
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
bool success = await Windows.System.Launcher.LaunchFileAsync(f1, options);
Should add "capability in manifest", to use KnownFolders like DocumentLibrary,PictureLibrary,MusicLibrary...
Source:http://lunarfrog.com/blog/2011/10/03/winrt-storage-overview

Categories

Resources