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
Related
I have a Button on a Page with the following method on the click event of the button:
StorageFile _sourceFile;
private string _sourceToken;
private async void btnSelect_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".mp4");
StorageFile inFile = await fop.PickSingleFileAsync();
_sourceToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(inFile);
_sourceFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(_sourceToken);
mediaElement.AutoPlay = false;
IRandomAccessStream stream = await _outFile.OpenAsync(FileAccessMode.ReadWrite);
mediaElement.SetSource(stream, _outFile.ContentType);
}
If I click play on the MediaElement the video I select plays fine.
I also have another button which has the following code on its click event:
private async void btnExport_Click(object sender, RoutedEventArgs e)
{
StorageFile outFile = await KnownFolders.VideosLibrary.CreateFileAsync("Outfie.mp4", CreationCollisionOption.ReplaceExisting);
MediaEncodingProfile profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p);
MediaTranscoder transcoder = new MediaTranscoder();
PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(_sourceFile, outFile, profile);
if (prepareOp.CanTranscode)
{
var transcodeOp = prepareOp.TranscodeAsync();
transcodeOp.Progress += new AsyncActionProgressHandler<double>(TranscodeProgress);
transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler<double>(TranscodeComplete);
}
else
{
switch (prepareOp.FailureReason)
{
case TranscodeFailureReason.CodecNotFound:
System.Diagnostics.Debug.WriteLine("Codec not found.");
break;
case TranscodeFailureReason.InvalidProfile:
System.Diagnostics.Debug.WriteLine("Invalid profile.");
break;
default:
System.Diagnostics.Debug.WriteLine("Unknown failure.");
break;
}
}
}
Unfortunately the line transcoder.PrepareFileTranscodeAsync throws an UnauthorizedAccessException. But if I use the following instead of _sourceFile it works:
StorageFile sourceFile = await KnownFolders.VideosLibrary.GetFileAsync("sourceFile.mp4");
The error being thrown is:
System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
To be clear, I am selecting files OUTSIDE the KnownFolders Enumeration, hence I am using Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.
Can anyone explain why?
EDIT:
If I change the source file to be the result of a FileOpenPicker then it works. So it begs the question, why is the FutureAccessList not working??
private async void btnExport_Click(object sender, RoutedEventArgs e)
{
StorageFile outFile = await KnownFolders.VideosLibrary.CreateFileAsync("Outfie.mp4", CreationCollisionOption.ReplaceExisting);
FileOpenPicker fop = new FileOpenPicker();
fop.SuggestedStartLocation = PickerLocationId.ComputerFolder;
fop.FileTypeFilter.Add(".mp4");
StorageFile sourceFile = await fop.PickSingleFileAsync();
MediaEncodingProfile profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p);
MediaTranscoder transcoder = new MediaTranscoder();
PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(sourceFile, outFile, profile);
if (prepareOp.CanTranscode)
{
var transcodeOp = prepareOp.TranscodeAsync();
transcodeOp.Progress += new AsyncActionProgressHandler<double>(TranscodeProgress);
transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler<double>(TranscodeComplete);
}
else
{
switch (prepareOp.FailureReason)
{
case TranscodeFailureReason.CodecNotFound:
System.Diagnostics.Debug.WriteLine("Codec not found.");
break;
case TranscodeFailureReason.InvalidProfile:
System.Diagnostics.Debug.WriteLine("Invalid profile.");
break;
default:
System.Diagnostics.Debug.WriteLine("Unknown failure.");
break;
}
}
}
Do you have access to the file you're trying to write to? Maybe it's read-only or created by another user other than yourself? (Right click + Properties on the file in Explorer should give you a clearer picture of the file permissions)
Also, you might get that exception if you're trying to write to a folder whom you don't have access to.
Check your credentials, I would guess it's something related to that.
So it seems the fact I was opening the source file in ReadWrite mode
IRandomAccessStream stream = await _outFile.OpenAsync(FileAccessMode.ReadWrite);
Was the cause of the issues. According to this page
Use read/write mode only when you're ready to write immediately in order to avoid conflicts with other operations.
So I changed to this and all works well
IRandomAccessStream stream = await _outFile.OpenAsync(FileAccessMode.Read);
I have code to download videos from the internet. My code can run in a runtime app but it can't run in a Windows Phone Silverlight 8.1 app.
private async void dinhmenh_Click(object sender, RoutedEventArgs e)
{
StorageFile destinationFile;
try
{
destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync("Baihay" + ".mp4",
CreationCollisionOption.ReplaceExisting);
MessageBox.Show("1");
}
catch
{
return;
}
MessageBox.Show("2"+ destinationFile.ToString());
// MessageBox
try
{
downloadLink = new Uri("url", UriKind.RelativeOrAbsolute);
var downloader = new BackgroundDownloader();
_download = downloader.CreateDownload(downloadLink, destinationFile);
await _download.StartAsync(); ;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
await HandleDownloadAsync();
MessageBox.Show("Finish!");
}
I'm trying to start and stop a MediaCapture preview for the camera in a Windows 8.1 Universal app. In the OnNavigatedTo method, I have the following code:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var scanItemsParameter = e.Parameter as ScanItemParameter;
if (scanItemsParameter != null)
{
((ScanItemViewModel)DataContext).ScanCallback = scanItemsParameter.ScanCallback;
}
try
{
HardwareButtons.CameraPressed += HardwareButtonsOnCameraPressed;
HardwareButtons.CameraHalfPressed += HardwareButtonsOnCameraHalfPressed;
DisplayInformation.GetForCurrentView().OrientationChanged += OnOrientationChanged;
if (!_mediaInitialized)
{
var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
if (cameras.Count < 1)
{
return;
}
MediaCaptureInitializationSettings settings;
settings = new MediaCaptureInitializationSettings
{
VideoDeviceId = cameras[0].Id,
PhotoCaptureSource = PhotoCaptureSource.Photo
};
await _mediaCapture.InitializeAsync(settings);
VideoCapture.Source = _mediaCapture;
_mediaInitialized = true;
}
SetOrientation(DisplayInformation.GetForCurrentView().CurrentOrientation);
await _mediaCapture.StartPreviewAsync();
await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);
if (_mediaCapture.VideoDeviceController.FocusControl.FocusChangedSupported)
{
var focusSettings = new FocusSettings();
focusSettings.AutoFocusRange = AutoFocusRange.Normal;
focusSettings.Mode = FocusMode.Auto;
focusSettings.WaitForFocus = true;
focusSettings.DisableDriverFallback = false;
_mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
}
_mediaCapture.VideoDeviceController.FlashControl.Auto = true;
}
catch (Exception ex)
{
var ex2 = ex;
throw;
}
}
In the OnNavigatingFrom method, I am cleaning up some event handlers and calling MediaCapture.StopPreviewAsync():
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
await _mediaCapture.StopPreviewAsync();
HardwareButtons.CameraPressed -= HardwareButtonsOnCameraPressed;
HardwareButtons.CameraHalfPressed -= HardwareButtonsOnCameraHalfPressed;
DisplayInformation.GetForCurrentView().OrientationChanged -= OnOrientationChanged;
}
The call works correctly the first time I open the page, but if I navigate away from the page and come back, I get an InvalidOperationException. What am I missing?
As a note, I'm using MVVM light, if that makes any difference...
Thanks in advance for any help...
I was able to resolve this by disposing of the MediaCapture element before navigating away from the page, and re-instantiating it upon returning to the page.
In the OnNavigatingFrom method, I added _mediaCapture.Dispose(); and _mediaCapture = null;:
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (_mediaCapture != null)
{
await _mediaCapture.StopPreviewAsync();
_mediaCapture.Dispose();
_mediaCapture = null;
}
HardwareButtons.CameraPressed -= HardwareButtonsOnCameraPressed;
HardwareButtons.CameraHalfPressed -= HardwareButtonsOnCameraHalfPressed;
DisplayInformation.GetForCurrentView().OrientationChanged -= OnOrientationChanged;
}
Then, just before the _mediaCapture.InitializeAsync() call in OnNavigatedTo, I instantiate a new one:
//...
_mediaCapture = new MediaCapture();
//...
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();
}
}
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.