I want to open FileOpenPicker for two times one after the other.i.e)After selecting the image from FileOpenPicker for first time it returns back to the page with the selected image,that time a MessageDialog is shown,And clicking OK button on MessageDialog I am opening the FileOpenPicker again,this time I get a weird crash on
open.FileTypeFilter.Clear();
as 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'.And My code is below.
private async void PickImage()
{
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
if (prop1.Source == null)
{
Dialogpopup();
return;
}
else if (prop2.Source == null)
{
Dialogpopup();
return;
}
}
}
private async void Dialogpopup()
{
MessageDialog msgDialog = new MessageDialog("Would you like to add additional photos?");
UICommand okBtn = new UICommand("Yes");
okBtn.Invoked = OkBtnClick;
msgDialog.Commands.Add(okBtn);
UICommand cancelBtn = new UICommand("No");
cancelBtn.Invoked = CancelBtnClick;
msgDialog.Commands.Add(cancelBtn);
//Show message
msgDialog.ShowAsync();
}
private async void OkBtnClick(IUICommand command)
{
img_PointerPressed(img_galary, null);
}
private void img_PointerPressed(object sender, PointerRoutedEventArgs e)
{
if (sender == img_galary)
{
PickImage();
}
}
Related
I started a windows form application which imports images from files and store them and specify a radio button to each one.
it have a button with the name 'Lock'
so if user select one radio button and then press the button the app should change the lock screen image and then Lock the screen.
But I don't know how to set the image and lock the screen.
I googled later and the answer about the LockScreen.blabla didn't work for me because I can't do using windows.system.userprofile;
If some one get me the assembly i will do the thing.
there is the events:
private void rB_CheckedChanged(object sender, EventArgs e)
{
MyRadioButton radioButton = sender as MyRadioButton;
pictureBox1.Image = radioButton.Image;
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
foreach (Control control in FindForm().Controls)
{
if (control.GetType() == typeof(MyRadioButton))
{
MyRadioButton mrb = control as MyRadioButton;
if (mrb.Checked == true)
{
mrb.Image = pictureBox1.Image;
}
}
}
}
}
private void btnLock_Click(object sender, EventArgs e)
{
//should set the lock screen background
LockScreen.LockScreen.SetImageFileAsync(imagefile);//shows error 'the name lock screen does not exist
}
I have made a UWP application to use the LockScreen class provided by windows.userProfile.dll And the event's changed to:
private Dictionary<string, string> Images = new Dictionary<string, string>();
private async void btnLock_Click(object sender, RoutedEventArgs e)
{
string path;
if (Images.TryGetValue(selectedRadioButton.Name, out path))
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
await LockScreen.SetImageFileAsync(file);
try
{
HttpClient httpClient = new HttpClient();
Uri uri = new Uri("http://localhost:8080/lock/");
HttpStringContent content = new HttpStringContent(
"{ \"pass\": \"theMorteza#1378App\" }",
UnicodeEncoding.Utf8,
"application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
uri,
content);
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
throw ex;
}
}
}
private async void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
using (var imageStream = await file.OpenReadAsync())
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(imageStream);
image.Source = bitmapImage;
}
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
await file.CopyAsync(storageFolder, selectedRadioButton.Name+file.FileType,NameCollisionOption.ReplaceExisting);
addOrUpdate(selectedRadioButton.Name, Path.Combine(storageFolder.Path, selectedRadioButton.Name + file.FileType));
save();
}
}
private async void rb_Checked(object sender, RoutedEventArgs e)
{
RadioButton rb = sender as RadioButton;
selectedRadioButton = rb;
btnBrowse.IsEnabled = true;
string path;
if (Images.TryGetValue(rb.Name, out path))
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
using (var imageStream = await file.OpenReadAsync())
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(imageStream);
image.Source = bitmapImage;
}
}
}
private void addOrUpdate(string key, string image)
{
if (Images.Keys.Contains(key))
{
Images.Remove(key);
Images.Add(key, image);
}
else
{
Images.Add(key, image);
}
}
private async void save()
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file = await storageFolder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, JsonConvert.SerializeObject(Images));
}
private async void load()
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
string fileText = await FileIO.ReadTextAsync(sampleFile);
try
{
Images = JsonConvert.DeserializeObject<Dictionary<string, string>>(fileText);
}
catch (Exception)
{
}
}
and you can see in the lock button click event there is a request to a web server cause you cannot directly lock the screen in a UWP app and you can follow the rest of your question in my next answer to the question "why I can't directly lock screen in UWP app?and how to do so?".
Application works when its connected to PC and run with debugger. The problem starts when I disconnect phone from PC, run app from phone and try to open gallery and set image to image control. I tried to write error in a file on try/catch but catch is never called, like there is no error on app executing.
This is code where i select img:
private async void galleryBtn_Click(object sender, RoutedEventArgs e)
{
try
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
catch (Exception err)
{
string error = err.StackTrace.ToString();
await saveStringToLocalFile("test11", error);
}
}
And than it goes to :
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
try
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
var obj = App.Current as App;
obj.ImageToEdit = bitmapImage;
obj.fileTransfer = storageFile;
checkTorch = -1;
await newCapture.StopPreviewAsync();
Frame.Navigate(typeof(EditImage));
}
}
catch (Exception err) {
string error = err.StackTrace.ToString();
await saveStringToLocalFile("test11", error);
}
}
When img is selected i open screen for image editing and run this
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
var obj = App.Current as App;
slika = obj.ImageToEdit;
original = obj.ImageToEdit;
ImagePreview.Source = slika;
RotateTransform myRotateTransform = new RotateTransform();
myRotateTransform.Angle = 0;
ImagePreview.RenderTransform = myRotateTransform;
var localSettings = ApplicationData.Current.LocalSettings;
}
catch (Exception err)
{
string error = err.StackTrace.ToString();
await saveStringToLocalFile("test11", error);
}
}
That is all, any advice is appreciated;
Problem was with my MediaCapture. First use mediaCapture.stopPreviewAsync(); to stop preview and than you must release the mediaCapture.
Before you call fileOpener use this code:
newCapture.Dispose();
In order to catch unhandled exceptions you can use a global exception catcher,
in App.xaml.cs file define:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
this.UnhandledException += UnhandledExceptionHandler;
}
private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
log.Critical(e.Exception);
}
It's important to understand that not all exceptions can be caught using try\catch such as Corrupt State Exceptions:
https://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035
In this case you can debug the issue by viewing the .dmp file generated by your application found in: {Phone}\Documents\Debug
I have a CommandBar in my Windows Store app, and when I click the Open button on my CommandBar, it runs the OpenFile handler as follows:
private async void OpenFile(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("You are about to open a new file. Do you want to save your work first?");
dialog.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(SaveAndOpen)));
dialog.Commands.Add(new UICommand("No", new UICommandInvokedHandler(Open)));
await dialog.ShowAsync();
}
private async void SaveAndOpen(IUICommand command)
{
await SaveFile();
Open(command);
}
private async void Open(IUICommand command)
{
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.ViewMode = PickerViewMode.List;
fileOpenPicker.FileTypeFilter.Add(".txt");
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
await LoadFile(file);
}
I see the message just fine, but only when I hit Yes do I get presented with the FileOpenPicker. When I hit No I get an UnauthorizedAccessException: Access is denied. at the following line: StorageFile file = await fileOpenPicker.PickSingleFileAsync();
I'm baffled...does anyone know why this is happening? I even tried running it in a dispatcher on the off-chance that the handler was being called on a different thread, but...unfortunately, same thing:
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
await LoadFile(file);
});
Yes, it was due to RT's dialog race conditions. The solution was for me to literally make use of the MessageDialog class the same way you would use MessageBox.Show in WinForms:
private async void OpenFile(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("You are about to open a new file. Do you want to save your work first?");
IUICommand result = null;
dialog.Commands.Add(new UICommand("Yes", (x) =>
{
result = x;
}));
dialog.Commands.Add(new UICommand("No", (x) =>
{
result = x;
}));
await dialog.ShowAsync();
if (result.Label == "Yes")
{
await SaveFile();
}
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.ViewMode = PickerViewMode.List;
fileOpenPicker.FileTypeFilter.Add(".txt");
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
await LoadFile(file);
}
i have been working on a windows store project using c#
i have a method called
void TranscodeProgress(IAsyncActionWithProgress<double> asyncInfo, double percent)
{
pg1.Value=percent;
}
when i try to add a progress bar to this it gives me an error
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
please help me to correct this error
thanks
this is my entire code
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
Windows.Storage.StorageFile source;
Windows.Storage.StorageFile destination;
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".wmv");
source = await openPicker.PickSingleFileAsync();
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
savePicker.DefaultFileExtension = ".wmv";
savePicker.SuggestedFileName = "New Video";
savePicker.FileTypeChoices.Add("MPEG4", new string[] { ".wmv" });
destination = await savePicker.PickSaveFileAsync();
// Method to perform the transcoding.
TranscodeFile(source, destination);
}
async void TranscodeFile(StorageFile srcFile, StorageFile destFile)
{
MediaEncodingProfile profile =
MediaEncodingProfile.CreateWmv(VideoEncodingQuality.HD1080p);
MediaTranscoder transcoder = new MediaTranscoder();
PrepareTranscodeResult prepareOp = await
transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);
if (prepareOp.CanTranscode)
{
var transcodeOp = prepareOp.TranscodeAsync();
transcodeOp.Progress +=
new AsyncActionProgressHandler<double>(TranscodeProgress);
// p1.Value = double.Parse(transcodeOp.Progress.ToString());
// txtProgress.Text = transcodeOp.Progress.ToString();
transcodeOp.Completed +=
new AsyncActionWithProgressCompletedHandler<double>(TranscodeComplete);
}
else
{
switch (prepareOp.FailureReason)
{
case TranscodeFailureReason.CodecNotFound:
MessageDialog md=new MessageDialog("Codec not found.");
await md.ShowAsync();
break;
case TranscodeFailureReason.InvalidProfile:
MessageDialog md1 = new MessageDialog("Invalid profile.");
await md1.ShowAsync();
break;
default:
MessageDialog md2 = new MessageDialog("Unknown failure.");
await md2.ShowAsync();
break;
}
}
//txtDisplay.Text = a;
}
void TranscodeProgress(IAsyncActionWithProgress<double> asyncInfo, double percent)
{
}
void TranscodeComplete(IAsyncActionWithProgress<double> asyncInfo, AsyncStatus status)
{
asyncInfo.GetResults();
if (asyncInfo.Status == AsyncStatus.Completed)
{
// Display or handle complete info.
}
else if (asyncInfo.Status == AsyncStatus.Canceled)
{
// Display or handle cancel info.
}
else
{
// Display or handle error info.
}
}
You should:
Avoid async void.
Use the TAP naming pattern (make your Task-returning methods end in "Async").
Use AsTask to do complex interop between TAP and WinRT asynchronous operations.
Something like this:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
...
await TranscodeFileAsync(source, destination);
}
async Task TranscodeFileAsync(StorageFile srcFile, StorageFile destFile)
{
MediaEncodingProfile profile =
MediaEncodingProfile.CreateWmv(VideoEncodingQuality.HD1080p);
MediaTranscoder transcoder = new MediaTranscoder();
PrepareTranscodeResult prepareOp = await
transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);
if (prepareOp.CanTranscode)
{
var progress = new Progress<double>(percent => { pg1.Value = percent; });
var result = await prepareOp.TranscodeAsync().AsTask(progress);
// Display result.
}
else
{
...
}
}
You are trying to access UI component from non UI Thread.
use:
void TranscodeProgress(IAsyncActionWithProgress<double> asyncInfo, double percent)
{
if(InvokeRequired)
{
Invoke(new MethodInvoker() => TranscodeProgress(asyncInfo, percent));
return;
}
pg1.Value=percent;
}
You cannot access UI components from non UI threads, Calling Invoke with a delegate passes the function call to thread that owns the component and than that thread call the passed delegate.
i try whithout success to delete a file in my local storage. Exactly, i took a photo and i want to delete it later with a button for exemple. But when i click on the button, the app bugs and i have : "access denied".
I sude a simple Delet.Async() after i get the file in a StorageFile.
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
}
Try the code below to see if it works for you.
private async void takephoto_click(object sender, RoutedEventArgs e)
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// store the file
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myImg.jpg");
await file.MoveAndReplaceAsync(myFile);
// display the file
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
}
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filefound != null)
{
// do something here
}
}
i am having same problem in deleting file from local storage. there are many files stored in the local storage with different names so how to delete other files. in the above case you have hard coded the file name to delete.
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
instead of myImg.jpg user want to delte other file then how user will delete
/// <summary>
/// Delete the indicated application file
/// </summary>
/// <param name="strFilePathName">The file path name to delete</param>
/// <returns>True, if successful; else false</returns>
public async static Task<bool> DeleteAppFile(string strFilePathName)
{
try
{
StorageFile fDelete = null;
if (!strFilePathName.Equals(""))
{
fDelete = await ApplicationData.Current.LocalFolder.GetFileAsync(strFilePathName);
if (fDelete != null)
{
try
{
await fDelete.DeleteAsync();
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
return false;
}
return true;
}
}
else
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile", "File path name is empty.");
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
}
return false;
}