TrySetWallpaperImageAsync() always returns false - c#

I'm trying to set the wallpaper to an image on my Windows 10 device:
var fileName = postInf.title + ".jpg";
BitmapImage img = new BitmapImage();
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using (var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read))
{
img.SetSource(pictureStream);
}
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetWallpaperImageAsync(pictureFile);
}
return success;
The storagefile is created fine, have tried with various images from various folders (e.g. My Pictures, Assets, LocalState); always returns false and wallpaper is not set? I have read/write permissions to pictures library, have tried running in debug and release versions. Apparently others are also having this problem.

Your app can't set wallpapers from any folder. Copy file in ApplicationData.Current.LocalFolder and set wallpaper from there.
My code:
if (list.SelectedIndex != -1)
{
var data = list.SelectedItem as ThumbItem;
StorageFile newFile = await data.File.CopyAsync(ApplicationData.Current.LocalFolder);
await SetWallpaperAsync(newFile);
}
async Task<bool> SetWallpaperAsync(StorageFile fileItem)
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetWallpaperImageAsync(fileItem);
}
return success;
}

Related

Xamarin Unauthorized Access Permission In downloading a file

I've been trying to create a function where the user will download a file(PDF) when a button is clicked.
I stored the file in firebase storage and can be accessible via url/link. I found this solution How to download files in Xamarin.Forms? that helps you download from a url. However I got an error that say **System.UnauthorizedAccessException:** 'Access to the path '/data/user/0/com.companyname.pawadopt_v5/files' is denied.' I already made sure to check and request permission using Xamarin.Essentials but I keep getting this error even with Permission.Granted for StorageRead and StorageWrite.
Here is my code:
Download Function
public async Task<bool> DownloadFile(string fileURL)
{
var checkPermission = await PermissionServices.PermissionClientInstance.checkStorage();
if(checkPermission == true)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
{
var client = new HttpClient();
var downloadStream = await client.GetStreamAsync(fileURL);
var fileStream = File.Create(path);
await downloadStream.CopyToAsync(fileStream);
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
return false;
}
}
Check and Request Permission
var Readpermission = await Permissions.CheckStatusAsync<Permissions.StorageRead>();
var Writepermission = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (Readpermission != PermissionStatus.Granted || Writepermission != PermissionStatus.Granted)
{
Readpermission = await Permissions.RequestAsync<Permissions.StorageRead>();
Writepermission = await Permissions.RequestAsync<Permissions.StorageWrite>();
}
if (Readpermission != PermissionStatus.Granted && Writepermission != PermissionStatus.Granted)
return false;
else
return true;
What are your thoughts and solutions about this?
Any ideas and solution are greatly appreciated
UPDATE
When I changed the path into string localPath = Path.Combine(FileSystem.AppDataDirectory,"File.pdf");, No error shows and prompt the 'Download Successful'. However I cant find where this local path is.

UWP Windows 10 IoT 2 channel Simultaneous Audio Recording

I would like to know how to record 2 separate audio channel simultaneously.
I have 2 USB adapters with mic & speaker respectively.
The samples code which I can find only support single channel recording at a time.
Please help. Thanks.
For single channel my code as follow;
MediaCapture audioCapture = new MediaCapture();
MediaCaptureInitializationSettings captureInitSettings = new MediaCaptureInitializationSettings();
captureInitSettings.StreamingCaptureMode = StreamingCaptureMode.Audio;
captureInitSettings.MediaCategory = MediaCategory.Other;
captureInitSettings.AudioProcessing = AudioProcessing.Default;
await audioCapture.InitializeAsync(captureInitSettings);
private async void recordChannelA()
{
StorageFolder externalDevices = KnownFolders.RemovableDevices;
IReadOnlyList<StorageFolder> externalDrives = await externalDevices.GetFoldersAsync();
StorageFolder usbStorage = externalDrives[0];
if (usbStorage != null)
{
StorageFolder recordFolder = await usbStorage.CreateFolderAsync(recFolderName, CreationCollisionOption.OpenIfExists);
await usbStorage.GetFolderAsync(recFolderName);
StorageFile recordFile = await recordFolder.CreateFileAsync("Recording - " + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".mp3", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
MediaEncodingProfile profile = null;
profile = MediaEncodingProfile.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto);
await audioCapture.StartRecordToStorageFileAsync(profile, recordFile);
Message.Text = "Recording ... ";
recordingtimerRun = new TimeSpan(0, 0, 0);
recordingTimer.Start();
}
else Message.Text = "Recording error !";
}
Update;
I created a 'listview' for the enumerated devices and to select the respective capture device. However, there is an Syntax Error which i cannot convert the enumaration.deviceinformation to imediasource.
captureInitSettings.AudioSource = captureDeviceList[audioCaptureList.SelectedIndex];
Update: I managed to get it to work
The solution is
captureInitSettingsA.AudioDeviceId = captureDeviceList[audioCaptureList.SelectedIndex].Id;
captureInitSettingsB.AudioDeviceId = captureDeviceList[audioCaptureList.SelectedIndex].Id;
However, how do i save these selections in app settings .. so that when I reboot I don't have to re-select again.
Update:
I manage to save the app setting for audiocapture & audiorender devices but I am not sure how to retrieve them & also to check if there is any previous settings saved.
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
localSettings.Values["audioACaptureSettings"] = captureAInitSettings.AudioDeviceId;
localSettings.Values["audioARenderSettings"] = mediaPlayerA.AudioDevice.Id;
localSettings.Values["audioBCaptureSettings"] = captureBInitSettings.AudioDeviceId;
localSettings.Values["audioBRenderSettings"] = mediaPlayerB.AudioDevice.Id;
private void loadAudioConfig()
{
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
if (localSettings.Values["audioACaptureSettings"] != null)
{
captureAInitSettings.AudioDeviceId = localSettings.Values["audioACaptureSettings"].ToString();
}
if (localSettings.Values["audioARenderSettings"] != null)
{
Object audioARenderValue = localSettings.Values["audioARenderSettings"];
mediaPlayerA.AudioDevice = audioARenderValue;
}
if (localSettings.Values["PAaudioCaptureSettings"] != null)
{
captureBInitSettings.AudioDeviceId = localSettings.Values["audioBCaptureSettings"].ToString();
}
if (localSettings.Values["PAaudioRenderSettings"] != null)
{
Object audioBRenderValue = localSettings.Values["audioBRenderSettings"];
mediaPlayerB.AudioDevice = audioBRenderValue;
}
You can refer to this document which introduced how to store and retrieve settings and other app data. You can save the data to Settings and Files.
When you use Settings, it only supports multiple data types as mentioned in the document.
If use files, you can store binary data or to enable your own, customized serialized types,.
In your provided code, it is correct to check if there is any previous settings saved:
if (localSettings.Values["audioACaptureSettings"] != null)
{
captureAInitSettings.AudioDeviceId = localSettings.Values["audioACaptureSettings"].ToString();
}
But it is incorrect about how to retrieve the setting as AudioDevice because it can not implicitly convert string to DeviceInformation. Please try in this way:
if (localSettings.Values["audioARenderSettings"] != null)
{
var aduioSource = localSettings.Values["audioARenderSettings"] as string;
mediaPlayerA.AudioDevice = await DeviceInformation.CreateFromIdAsync(aduioSource);
}

Upload to Dropbox not working .NET SDK

I have the following function that uploads files to Drobox and returns shared links to these files.
private async Task<string> Upload(DropboxClient dbx, string localPath, string remotePath)
{
const int ChunkSize = 4096 * 1024;
using (var fileStream = File.Open(localPath, FileMode.Open))
{
if (fileStream.Length <= ChunkSize)
{
WriteMode mode = new WriteMode();
FileMetadata fileMetadata = await dbx.Files.UploadAsync(remotePath, body: fileStream, mode: mode.AsAdd, autorename: true);
//set the expiry date
var existingDoc = await dbx.Files.GetMetadataAsync(remotePath);
if (existingDoc.IsFile)
{
var sharedLink = dbx.Sharing.ListSharedLinksAsync(remotePath);
var settings = new ListSharedLinksArg(remotePath);
ListSharedLinksResult listSharedLinksResult = await dbx.Sharing.ListSharedLinksAsync(remotePath);
if (listSharedLinksResult.Links.Count > 0)
{
return listSharedLinksResult.Links[0].Url;
}
else
{
var settings2 = new SharedLinkSettings(expires: DateTime.Today.AddDays(7));
SharedLinkMetadata sharedLinkMetadata = await dbx.Sharing.CreateSharedLinkWithSettingsAsync(remotePath, settings2);
return sharedLinkMetadata.Url;
}
}
else
{
var settings = new SharedLinkSettings(expires: DateTime.Today.AddDays(7));
SharedLinkMetadata sharedLinkMetadata = await dbx.Sharing.CreateSharedLinkWithSettingsAsync(fileMetadata.PathLower, settings);
return sharedLinkMetadata.Url;
}
}
else
{
await this.ChunkUpload(dbx, remotePath, fileStream, ChunkSize);
}
return "error";
}
}
But it's not working properly, when it gets to the ListSharedLinksAsync function, it stops working witout throwing any error.
I notices that the files that I try to upload are not accessible after it crashes, I get a "used by another proccess error"...
What am I doing wrong?
It looks like you are missing an await on this row, thus causing a deadlock?
var sharedLink = dbx.Sharing.ListSharedLinksAsync(remotePath);
Should be
var sharedLink = await dbx.Sharing.ListSharedLinksAsync(remotePath);

How to save image from clipboard to file in UWP

Is there any equivalent of
Clipboard.GetImage().Save(FileName, Imaging.ImageFormat.Jpeg)
for UWP (Windows Universal Platform)?
I.e. saving the graphics image from clipboard into jpg format to file.
I am looking for example in vb.net/C#.
I have already started with
Dim datapackage = DataTransfer.Clipboard.GetContent()
If datapackage.Contains(StandardDataFormats.Bitmap) Then
Dim r As Windows.Storage.Streams.RandomAccessStreamReference = Await datapackage.GetBitmapAsync()
...
but I do not know how to continue (and even if I have even started correctly).
The first step is to try and get the image from the clipboard, if it exists:
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
IRandomAccessStreamReference imageReceived = null;
try
{
imageReceived = await dataPackageView.GetBitmapAsync();
}
catch (Exception ex)
{
}
If it exists, launch a file save picker, choose where to save the image, and copy the image stream to the new file.
if (imageReceived != null)
{
using (var imageStream = await imageReceived.OpenReadAsync())
{
var fileSave = new FileSavePicker();
fileSave.FileTypeChoices.Add("Image", new string[] { ".jpg" });
var storageFile = await fileSave.PickSaveFileAsync();
using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await imageStream.AsStreamForRead().CopyToAsync(stream.AsStreamForWrite());
}
}
}
}

SQLiteDatabase import Windows Universal

I'm trying to import an excisting SQLitedatabase in my Windows Universal project.I followed along this tutorial. Which does just what I want.
However it states:
then copy the database with a .sqlite extension to the root of the shared project in your universal app.
So I added my excisting databse to the root of my Shared Project
However when I try the following code I get an IOException the File could not be found.
private async Task CopyDatabase()
{
bool isDatabaseExisting = false;
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("FixedCamerasOK.sqlite");
isDatabaseExisting = true;
}
catch(Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("FixedCamerasOK.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
}
So where do I place the .sqlite file so it can be found.
Add the File As Content instead as none or empty
Search for the file(FixedCamerasOk.sqlite) in the Installed folder to see if it exists
public async Task<bool> DoesDatabaseExist()
{
bool dbexists = true;
try
{
var files = Package.Current.InstalledLocation.GetFilesAsync();
var retvalues = (from f in await files
where f.Name == "FixedCamerasOk.sqlite"
select f);
int count = retvalues.Count();
if (count > 0)
return dbexists;
else
return false;
}
catch (Exception)
{
dbexists = false;
}
return dbexists;
}
First select your file and in properties select Build Action as Content then open the file like this
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///FixedCamerasOK.sqlite"));

Categories