Cannot open file immediately after downloading from OneDrive - c#

after downloading a JPG file from OneDrive successfully under Windows 8.1, I am not able to open it and use the stream as image source immediately. Instead, my app must run in a waiting loop to retry the opening until the exception "Error HRESULT E_FAIL has been returned from a call to a COM component" does not occur anymore. Or the app must inform the user to retry the action. After about one second or so, the file can be opened and the stream can be used as image source. This problem occurs if the JPG file was initially not available offline and my app downloads it. I want to know if anybody has a better solution for that problem. Here is some of my code:
private async void LoadFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpe");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".gif");
Stream stream = null;
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
var basicProperties = await file.GetBasicPropertiesAsync();
var props = await basicProperties.RetrievePropertiesAsync(
new string[] { "System.OfflineAvailability", "System.StorageProviderFileRemoteUri" });
if (props.ContainsKey("System.OfflineAvailability"))
{
var offline = (uint)props["System.OfflineAvailability"];
if (offline == 0)
{
if (file.Provider.DisplayName == "OneDrive")
{
if (props.ContainsKey("System.StorageProviderFileRemoteUri"))
{
var uri = (string)props["System.StorageProviderFileRemoteUri"];
var res = await GameStorage.DownloadOneDriveFile(file, uri, _downloadProgressBar);
if (res is string)
{
await App.InformUserAsync(res.ToString(), _title.Text);
return;
}
stream = (Stream)res;
}
}
else
{
await App.InformUserAsync(String.Format(
App.GetString("MakeFileOfflinePrompt", "GameManagement"),
file.Path), _title.Text);
return;
}
}
}
if (stream == null)
{
stream = await file.OpenStreamForReadAsync();
}
await _photoClipper.SetDisplayImageStreamAsync(stream);
_clipPhotoButton.IsEnabled = true;
}
}
internal static async Task<object> DownloadOneDriveFile(StorageFile file, string url,
ProgressBar progressBar = null)
{
if (progressBar != null)
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 1;
}
if (__liveClient == null)
{
var msg = await ConnectLive();
if (!String.IsNullOrEmpty(msg))
{
return msg;
}
}
var uri = new Uri(WebUtility.UrlDecode(url));
var pathElements = uri.LocalPath.Split(new char[] { '/' },
StringSplitOptions.RemoveEmptyEntries);
var parentId = "folder." + pathElements[0];
IDictionary<string, object> props = null;
for (var i = 1; i < pathElements.Length; i++)
{
props = await FindOneDrivePathElement(parentId, pathElements[i]);
if (props == null)
{
return String.Format(App.GetString("OneDrivePathElementNotFound",
"GameManagement"), pathElements[i], uri);
}
parentId = props["id"].ToString();
if (progressBar != null) progressBar.Value += 1;
}
try
{
var operation = await __liveClient.CreateBackgroundDownloadAsync(parentId +
"/content", file);
LiveDownloadOperationResult result = null;
if (progressBar != null)
{
progressBar.Value = 10;
var progressHandler = new Progress<LiveOperationProgress>(
(progress) => { progressBar.Value = progress.ProgressPercentage; });
var cts = new CancellationTokenSource();
result = await operation.StartAsync(cts.Token, progressHandler);
}
else
{
result = await operation.StartAsync();
}
var trialsCount = 0;
string openErr = null;
Stream stream = null;
while (trialsCount < 5)
{
try
{
stream = await result.File.OpenStreamForReadAsync();
break;
}
catch (Exception ex)
{
openErr = ex.Message;
}
trialsCount += 1;
await App.SuspendAsync(1000);
}
if (stream != null)
{
return stream;
}
return String.Format(App.GetString("OneDriveCannotOpenDownloadedFile",
"GameManagement"), file.Path, openErr);
}
catch (Exception ex)
{
return String.Format(App.GetString("OneDriveCannotDownloadFile",
"GameManagement"), file.Path, ex.Message);
}
finally
{
if (progressBar != null)
{
progressBar.Visibility = Visibility.Collapsed;
}
}
}
private static async Task<IDictionary<string, object>> FindOneDrivePathElement(
string parentId, string childName)
{
var res = await __liveClient.GetAsync(parentId + "/files");
if (res.Result.ContainsKey("data"))
{
var items = (IList<object>)res.Result["data"];
foreach (var item in items)
{
var props = (IDictionary<string, object>)item;
if (props.ContainsKey("name"))
{
var name = props["name"].ToString();
if (name == childName)
{
if (props.ContainsKey("id"))
{
return props;
}
}
}
}
}
return null;
}

I have tried again to open a "available online-only" file and as by a miracle the exception "Error HRESULT E_FAIL" did not occur any more. For what ever reason, I don't know. But, I really do not need to handle that scenario by myself. Thanks.

Related

FluentFTP. How to stop the download process

I need to make a button that will stop downloading the file. For example, I clicked 1 time the download started and the second time it stopped.
private static async void Download()
{
foreach (string fileName in fileList)
{
string localDir = AppDomain.CurrentDomain.BaseDirectory;
localDir.Substring(0, localDir.Length - 1);
localDir += fileName;
long fileSize = await ftp.GetFileSizeAsync(fileName);
fileSize /= 1024;
form.progressBar1.Maximum = (int)fileSize;
var token = new CancellationToken();
Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
{
if (loadedFile.Progress == 100)
{
form.progressBar1.Value = 0;
}
else
{
int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
string value = loadedFile.TransferSpeedToString();
form.label1.Text = "Connection Speed: \n" + value;
form.progressBar1.Value = x;
}
});
await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, token);
}
}
First of all, you don't create directly a CancellationToken, you create a CancellationTokenSource and get it's Token.
Said that, you can imagine the use of that token, to allow to cancel the operation.
You can do something like this:
//At class level
CancellationTokenSource cancel = null;
private static async void Download()
{
if(cancel != null)
{
cancel.Cancel();
cancel.Dispose();
cancel = null;
return;
}
cancel = new CancellationTokenSource();
foreach (string fileName in fileList)
{
string localDir = AppDomain.CurrentDomain.BaseDirectory;
localDir.Substring(0, localDir.Length - 1);
localDir += fileName;
long fileSize = await ftp.GetFileSizeAsync(fileName);
fileSize /= 1024;
form.progressBar1.Maximum = (int)fileSize;
Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
{
if (loadedFile.Progress == 100)
{
form.progressBar1.Value = 0;
cancel.Dispose();
cancel = null;
}
else
{
int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
string value = loadedFile.TransferSpeedToString();
form.label1.Text = "Connection Speed: \n" + value;
form.progressBar1.Value = x;
}
});
try
{
await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, cancel.Token);
}
catch
{
//When the download is cancelled will throw an exception
//you can create a more specific handler
cancel.Dispose();
cancel = null;
}
}
}

How do I adjust the video quality from the camera in xamarin

I want to upload a video into server from my app, now I can upload small size video's, but in the case of larger size the video uploading is not done.How can I do this.
I found a reason that the 2 minutes video has the size 300 mb, so how can I reduce the size of the video with out losing the quality
Please somebody help me..
Here is my code for video taking
private async void TakeVideo_Clicked(object sender, EventArgs e)
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakeVideoSupported)
{
await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
return;
}
var _file = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions
{
Name = "gtsvideo.mp4",
Directory = "GTSVideos",
});
if (_file == null)
{
return;
}
else
{
_path = _file.Path;
using (var _streamReader = new StreamReader(_file.GetStream()))
{
var _array = default(byte[]);
using (MemoryStream _memoryStream = new MemoryStream())
{
_streamReader.BaseStream.CopyTo(_memoryStream);
_array = _memoryStream.ToArray();
if (await DisplayAlert(App._confirmation, "It may take few Minutes..,Do you want to save the video?", "Yes", "Cancel"))
{
FileUploadAsync(_array, false);
activity_Indicator.IsVisible = true;
activity_Indicator.IsRunning = true;
}
else
{
return;
}
}
}
}
}
public async void FileUploadAsync(byte[] fileUpload, bool IsImage)
{
APIResponse _response = await App.DataManager.UpdateFilesAsync(_task.ID, fileUpload, IsImage);
if (IsImage == false)
{
await System.Threading.Tasks.Task.Delay(5000);
}
if (_response != null)
{
activity_Indicator.IsRunning = false;
if (IsImage)
{
DependencyService.Get<IAlertPlayer>().AlertMessege("Image upload successfully");
}
else
{
DependencyService.Get<IAlertPlayer>().AlertMessege("Video upload successfully");
}
}
else
{
DisplayAlertMessage();
}
}
UploadVideo
public async Task<APIResponse> UpdateFilesAsync(int id, byte[] file, bool IsImage)
{
Url _url = new Url(BaseURL).AppendPathSegment("tasks/UploadFiles");
_url.QueryParams["ID"] = id;
return await Service.POSTFILE<APIResponse>(_url, file, IsImage);
}
public async Task<T> POSTFILE<T>(Url url, byte[] uploadFile, bool IsImage)
{
try
{
using (MultipartFormDataContent _content = new MultipartFormDataContent())
{
ByteArrayContent _filecontent = new ByteArrayContent(uploadFile);
if (IsImage)
{
_filecontent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = Guid.NewGuid().ToString() + ".png"
};
}
else
{
_filecontent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = Guid.NewGuid().ToString() + ".mp4"
};
}
_content.Add(_filecontent);
using (HttpResponseMessage _response = await Client.PostAsync(url, _content))
{
string _result = await _response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(_result);
}
}
}
catch (Exception ex)
{
}
return default(T);
}
Simple answer: Unless you implement some fancy lossless compression code yourself, you don't. You get what the operating system of your phone gives you.

Android error: Nested signal detected - original signal being reported

This is killing me. I'm new to android/Xamarin. I can't find anything on the web that explains what is going on here.
I'm using xamarin forms for my application. I have a page that synchronizes the device with a web service.
The method simply retrieves 100 records at a time from the web service and updates a sqlite table on the device. I randomly get this error. I'm running 5000 records for my test sample.
Here is the button click:
public async void OnSyncCachedData_Clicked(object sender, EventArgs e)
{
activityIndicatorAll.IsRunning = true;
try
{
actIndSyncItems.IsRunning = true;
SyncAllFinished += SynchAllFinishedProcessing;
await Task.Run(async () => await App.ItemsRepo.LoadCacheDataFromCacheAsync(DbPath).ConfigureAwait(false));
}
catch (BAL.Exceptions.NetworkException nex)
{
await DisplayAlert(Messages.TitleError, nex.Message, Messages.MsgOk);
}
catch (Exception ex)
{
await DisplayAlert(Messages.TitleError, string.Format(Messages.MsgAreYouConnectedParm1, ex.Message), Messages.MsgOk);
}
finally
{
EventHandler handler = SyncAllFinished;
if (handler != null)
{
handler(this, new EventArgs());
}
SyncAllFinished -= SynchAllFinishedProcessing;
}
}
the main worker method:
public async Task<bool> LoadCacheDataFromCacheAsync(string dbPath)
{
WebSvcManagers.ItemsManager itemsWebServiceManager = new WebSvcManagers.ItemsManager();
List<Models.WebServiceItems> consumedRecords = new List<Models.WebServiceItems>() { };
int bufferSize = 100;
Log.Debug(TAG, "LoadCacheDataFromCacheAsync starting");
try
{
{
int lastID = 0;
IEnumerable<Models.WebServiceItems> remoteRecords = await BAL.DataAccessHelper.GetItemsFromGPCacheAsync(App.Login, lastID, bufferSize, itemsWebServiceManager).ConfigureAwait(false);
while (remoteRecords.Count() != 0)
{
foreach (Models.WebServiceItems remoteItem in remoteRecords)
{
// DbActionTypes dbAction = (DbActionTypes)remoteItem.DbAction;
Models.Items itemRecord = new Models.Items() { ItemNumber = remoteItem.ItemNumber.ToUpper().Trim(), Description = remoteItem.Description.Trim() };
Log.Debug(TAG, "Processing {0}", remoteItem.ItemNumber.Trim());
bool success = await AddRecordAsync(itemRecord).ConfigureAwait(false);
if (success)
consumedRecords.Add(remoteItem);
}
lastID = remoteRecords.Max(r => r.RecordID) + 1;
remoteRecords = await BAL.DataAccessHelper.GetItemsFromGPCacheAsync(App.Login, lastID, bufferSize, itemsWebServiceManager).ConfigureAwait(false);
}
}
// await UpdateConsumedRecords(consumedRecords).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
this.StatusMessage = ex.Message;
Log.Debug(TAG, "Error Catch: {0}", StatusMessage);
return false;
}
finally
{
itemsWebServiceManager = null;
HandleSyncFinished(this, new EventArgs());
SyncAllFinished -= HandleSyncFinished;
}
}
My simple webservice manager:
public static async Task<IEnumerable<Models.WebServiceItems>> GetItemsFromGPCacheAsync(Models.Login login, int offset, int bufferCount, WebSvcManagers.ItemsManager manager)
{
try
{
return await manager.GetCacheRecordsAsync(login, offset, bufferCount).ConfigureAwait(false);
}
catch (Exception)
{
throw;
}
}
And the code for the interaction with the web service:
const int bufferSize = 100;
public async Task<IEnumerable<Models.WebServiceItems>> GetCacheRecordsAsync(Models.Login login, int offSet, int bufferCount)
{
string deviceID = App.ConfigSettings.DeviceID.ToString("D");
try
{
///* Testing start */
//return await DataStore(bufferCount, offSet).ConfigureAwait(false);
///* Testing end */
if (!App.IsConnected)
throw new BAL.Exceptions.NetworkException(Messages.ExceptionNetworkConnection);
string user = login.UserName;
string password = login.Password;
HttpClient client = HttpClientExtensions.CreateHttpClient(user, password);
try
{
List<Models.WebServiceItems> items = new List<Models.WebServiceItems>() { };
int lastID = offSet;
int i = 0;
string uri = string.Format("{0}", string.Format(Messages.WebRequestItemsCacheParms3, deviceID, lastID, Math.Min(bufferCount, bufferSize)));
Log.Debug(TAG, string.Format("Webservice {0}", uri));
string response = await client.GetStringAsync(uri).ConfigureAwait(false);
while (i < bufferCount && response != null && response != "[]")
{
while (response != null && response != "[]")
{
dynamic array = JsonConvert.DeserializeObject(response);
foreach (var item in array)
{
i++;
items.Add(new Models.WebServiceItems()
{
ItemNumber = item["ITEMNMBR"].Value.Trim(),
Description = item["ITEMDESC"].Value.Trim(),
DbAction = (int)(item["DbAction"].Value),
RecordID = (int)(item["DEX_ROW_ID"].Value),
});
lastID = (int)(item["DEX_ROW_ID"].Value);
Log.Debug(TAG, string.Format("Webservice {0}", item["ITEMNMBR"].Value.Trim()));
}
if (i < Math.Min(bufferCount, bufferSize))
{
uri = string.Format("{0}", string.Format(Messages.WebRequestItemsCacheParms3, deviceID, lastID + 1, Math.Min(bufferCount, bufferSize)));
Log.Debug(TAG, string.Format("Webservice {0}", uri));
response = await client.GetStringAsync(uri).ConfigureAwait(false);
}
else
break;
}
}
Log.Debug(TAG, string.Format("Webservice return {0} items", items.Count()));
return items;
}
catch (Exception ex)
{
Log.Debug(TAG, "Error Catch: {0}", ex.Message);
throw ex;
}
}
catch (System.Net.Http.HttpRequestException nex)
{
throw new Exception(string.Format(Messages.ExceptionWebServiceLoginParm1, nex.Message));
}
catch (Exception)
{
throw;
}
}
I've had assistance from a Xamarin instructor and we thought we got it, (because this is random), but it clearly is not swatted. I've been hitting my head up against a wall for over 3 weeks on this. It smells like a memory leak, but I have no idea how to find it with such a generic error message that doesn't appear on web searches.
Somebody out there with some major brains, Please help!
Error:
08-03 12:41:11.281 D/X:ItemsRepositiory(16980): UpdateRecordAsync 65702-40710
08-03 12:41:11.306 D/X:ItemsManager(16980): Webservice DeleteCacheRecordAsync 20497
08-03 12:41:11.406 D/X:ItemsManager(16980): Webservice api/InventoryItems?DeviceID=7c5bb45d-2ea0-45b9-ae50-92f2e25a2983&OffSet=20498&Ma‌​x=100&cached=true
Thread finished: <Thread Pool> #7 08-03 12:41:11.521 E/art (16980): Nested signal detected - original signal being reported The thread 'Unknown' (0x7) has exited with code 0 (0x0).
This might be a problem with the VS Android Emulator. As we have shown in tests, this is not reproducible on the Google Android Emulators, nor on Xamarin Android Player, nor on a physical Android device.

LayoutSerializationCallback not be called

I'm using AvalonDock and I would serialize and deserialize my layout. But the callback (where I use the ContentId for create an instance of correct object) is not always called. For this reason the loaded not work correctly. I have tried to add one "try-catch", but not thrown exception.
This is my code:
` var layoutSerializer = new XmlLayoutSerializer(manager);
layoutSerializer.LayoutSerializationCallback += (s, e) =>
{
MyClass item;
if (items.TryGetValue(e.Model.ContentId, out item))
{
e.Content = item;
var tool = item as IMyClassToolApp;
var anchorable = e.Model as LayoutAnchorable;
var document = item as IMyClassDocumentApp;
var layoutDocument = e.Model as LayoutDocument;
if (tool != null && anchorable != null)
{
addToolCallback(tool);
tool.IsVisible = anchorable.IsVisible;
tool.IsSelected = e.Model.IsSelected;
return;
}
if (document != null && layoutDocument != null)
{
addDocumentCallback(document);
// Nasty hack to get around issue that occurs if documents are loaded from state,
// and more documents are opened programmatically.
layoutDocument.GetType().GetProperty("IsLastFocusedDocument").SetValue(layoutDocument, false, null);
document.IsVisible = true;
document.IsSelected = layoutDocument.IsSelected;
return;
}
}
e.Cancel = true;
};
try
{
layoutSerializer.Deserialize(stream);
}
catch
{
return false;
}`
Thank you for your help!
Are you sure your stream is O.K? If for example configuration file does not exist LayoutSerializationCallback method will not be called.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "MainWindow_Loaded");
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Jofta\Analyzer\configs\AvalonDock.config");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
XmlLayoutSerializer serializer = new XmlLayoutSerializer(this.dockingManager);
serializer.LayoutSerializationCallback += this.Serializer_LayoutSerializationCallback;
serializer.Deserialize(filePath);
}
MainWindow.logger.Debug("Exiting: {0}", "MainWindow_Loaded");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "MainWindow_Loaded");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
private void Serializer_LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "serializer_LayoutSerializationCallback");
if (e.Model.ContentId == ObjectExplorerViewModel.AnchorableContentId)
{
e.Content = Workspace.Instance.ObjectExplorer;
return;
}
// ...
// ...
MainWindow.logger.Debug("Exiting: {0}", "serializer_LayoutSerializationCallback");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "serializer_LayoutSerializationCallback");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}

Screenshot Feature on Windows Store App

I am making an app for the windows store, and one section, 'Create' allows the user to drag images onto a background to create their own little scene (the app is aimed at kids). I'm adding a screenshot button so the user can save their work once they are done, and I have all the coding done, error free, but once I run it and press the screenshot button the app fails. Any advice or help is appreciated.
I get this message originating from the button once it fails:
An exception of type 'System.UnauthorizedAccessException'
occurred in mscorlib.dll but was not handled in user code
async void btnScreenshot_Click(object sender, RoutedEventArgs e)
{
var bitmap = await SaveScreenshotAsync(controlsGrid);
}
async Task<RenderTargetBitmap> SaveScreenshotAsync(FrameworkElement uielement)
{
var file = await PickSaveImageAsync();
return await SaveToFileAsync(uielement, file);
}
async Task<StorageFile> PickSaveImageAsync()
{
var filePicker = new FileSavePicker();
filePicker.FileTypeChoices.Add("Bitmap", new List<string>() { ".bmp" });
filePicker.FileTypeChoices.Add("JPEG format", new List<string>() { ".jpg" });
filePicker.FileTypeChoices.Add("Compuserve format", new List<string>() { ".gif" });
filePicker.FileTypeChoices.Add("Portable Network Graphics", new List<string>() { ".png" });
filePicker.FileTypeChoices.Add("Tagged Image File Format", new List<string>() { ".tif" });
filePicker.DefaultFileExtension = ".jpg";
filePicker.SuggestedFileName = "screenshot";
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.SettingsIdentifier = "picture picker";
filePicker.CommitButtonText = "Save picture";
return await filePicker.PickSaveFileAsync();
}
async Task<RenderTargetBitmap> SaveToFileAsync(FrameworkElement uielement, StorageFile file)
{
if (file != null)
{
CachedFileManager.DeferUpdates(file);
Guid encoderId = GetBitmapEncoder(file.FileType);
try
{
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
return await CaptureToStreamAsync(uielement, stream, encoderId);
}
}
catch (Exception ex)
{
DisplayMessage(ex.Message);
}
var status = await CachedFileManager.CompleteUpdatesAsync(file);
}
return null;
}
Guid GetBitmapEncoder(string fileType)
{
Guid encoderId = BitmapEncoder.JpegEncoderId;
switch (fileType)
{
case ".bmp":
encoderId = BitmapEncoder.BmpEncoderId;
break;
case ".gif":
encoderId = BitmapEncoder.GifEncoderId;
break;
case ".png":
encoderId = BitmapEncoder.PngEncoderId;
break;
case ".tif":
encoderId = BitmapEncoder.TiffEncoderId;
break;
}
return encoderId;
}
async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId)
{
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);
var pixels = await renderTargetBitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
logicalDpi,
logicalDpi,
pixels.ToArray());
await encoder.FlushAsync();
return renderTargetBitmap;
}
catch (Exception ex)
{
DisplayMessage(ex.Message);
}
return null;
}
async void DisplayMessage(string error)
{
var dialog = new MessageDialog(error);
await dialog.ShowAsync();
}

Categories