Issues when saving files to OneDrive on Windows 10 Mobile - onedrive

I’m working on an application where you should be able to open and save files, similar to “Notepad”. It’s a universal application that should work both on computers and mobiles.
The application works fine on computers. It also works fine on mobile if I save or open files locally or on Dropbox.
But if I open a file on OneDrive (via the file picker), and then try to save an exception is thrown: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
If I select “Save as” on OneDrive it works. But every time I select Save after this a new instance of the file is created (I get “file 1”, “file 2”, “file 3” and so on).
I have only tested this on my phone. I might have a bug on my application, but since it works on DropBox I don’t think so. Is this a known issue with OneDrive? Or might I just have some local issues? I’m using Windows 10 Mobile 10.10586.420 and OneDrive 17.11.
Here is some code to illustrate the problem:
<Page
x:Class="BasicEditor.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BasicEditor"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="40">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Content="Open"
Click="OpenButton_Click" />
<Button Content="Save"
Click="SaveButton_Click" />
<Button Content="Save as"
Click="SaveAsButton_Click" />
</StackPanel>
<TextBox Grid.Row="1" x:Name="TextEditor"
TextWrapping="Wrap" />
</Grid>
</Page>
using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace BasicEditor
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
string MruToken;
private async void OpenButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".txt");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
try
{
string fileContent = await FileIO.ReadTextAsync(file);
TextEditor.Text = fileContent;
string token = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "");
MruToken = token;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write($"Open-Error: {ex.Message}");
var dialog = new MessageDialog($"Open-Error: {ex.Message}");
await dialog.ShowAsync();
}
}
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
try
{
var file = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(MruToken);
string fileContent = await FileIO.ReadTextAsync(file);
await FileIO.WriteTextAsync(file, TextEditor.Text);
var dialog = new MessageDialog($"Saved successfully");
await dialog.ShowAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write($"Save-Error: {ex.Message}");
var dialog = new MessageDialog($"Save-Error: {ex.Message}");
await dialog.ShowAsync();
}
}
private async void SaveAsButton_Click(object sender, RoutedEventArgs e)
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "New Document";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
await FileIO.WriteTextAsync(file, TextEditor.Text);
string token = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "");
MruToken = token;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write($"SaveAs-Error: {ex.Message}");
var dialog = new MessageDialog($"SaveAs-Error: {ex.Message}");
await dialog.ShowAsync();
}
}
}
}
}
A beta of my app is available here: https://www.microsoft.com/store/apps/9NBLGGH3MFM3
Another app with exactly the behavior when OneDrive is used is NotepadX.

Related

Converting XAML to PDF and Paginating it for a Xamarin.Forms UWP Project

Until recently I have been stuck on how to achieve the goal of "exporting" a report from a StackLayout into a PDF in a project I somehow pulled out of Dev Limbo.
--BackStory--
Previously I have tried to continue the use of the already placed (in the project) PDFSharp package to convert the data presented in the XAML to a PDF for a client. Long story short, I was unable to get PDFSharp to do what I needed it to do and turned to Syncfusion. They seemed to have the features I needed to make this happen. Going based off the code samples they had, I was able to get close to my goal, but not quite. They have the capture portion and they have the pagination portion, but not a combination of the two. I essentially needed to paginate the screenshot that CaptureAsync() saves to make a pdf of the entire report.
--How was this resolved?--
After doing some digging, I came across an answer in this article (I am forever grateful) and forged a solution using it.
Here's a sample of my XAML content page for context:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:ReportTool.Controls"
x:Class="ReportTool.ReportViewer">
<ContentPage.Content>
<StackLayout Style="{StaticResource TopLevelStackLayout}">
<!-- Body Block -->
<Grid x:Name="MainGrid" Style="{StaticResource MainContainingGrid}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<ScrollView x:Name="MainScrollLayout" VerticalOptions="Fill" HorizontalOptions="Fill" Grid.Row="0" Grid.Column="0" BackgroundColor="#FFFFFF" MinimumWidthRequest="700">
<StackLayout x:Name="MainStackLayout" Style="{StaticResource MainBkg}">
<Button x:Name="DownloadPdfBtn" Text="Export to PDF" Clicked="DownloadPdfBtn_OnClicked" TextColor="White" BackgroundColor="DodgerBlue" VerticalOptions="Start" HorizontalOptions="Start" />
<Image Source="~\..\Assets\Logos\CompanyLogo.png" Margin="0,60,0,10" HorizontalOptions="Center" />
<Label x:Name="TitlePageTitleText" Style="{StaticResource ReportViewerTitleTextMain}" Text="{StaticResource CompanyAnalysisReport}" />
<Label x:Name="TitlePagePreparedFor" Style="{StaticResource ReportViewerTitleTextMiddle}" Text="{StaticResource PreparedFor}" />
<Label x:Name="TitlePageOrganizationName" Style="{StaticResource ReportViewerTitleTextMiddle}" />
<Label x:Name="TitlePageOrganizationAddress1" Style="{StaticResource ReportViewerTitleTextMiddle}" />
<Label x:Name="TitlePageOrganizationAddress2" Style="{StaticResource ReportViewerTitleTextMiddle}" />
<Label x:Name="TitlePageOrganizationCityStateZip" Style="{StaticResource ReportViewerTitleTextLast}" />
<Grid x:Name="ReportGrid" Style="{StaticResource ReportGridBody}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="125"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
</StackLayout>
</ScrollView>
</Grid>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Here is the code for the star of the show, the ExportToPdf button:
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
private async void DownloadPdfBtn_OnClicked(object sender, EventArgs e)
{
try
{
var filename = "SurveyReport_" + ((App)Application.Current).CurrentUser.UserName + "_" + DateTime.UtcNow.ToString("MMddyy") + ".pdf";
// Init Memory Stream.
var stream = new MemoryStream();
//Create a new PDF document
using (var document = new PdfDocument())
{
// Add page to the PDF document.
var page = document.Pages.Add();
// Get the scroll view height.
var xamlPageHeight = MainScrollLayout.ContentSize.Height;
// Get the page dimensions.
var pageWidth = page.GetClientSize().Width;
var pageHeight = page.GetClientSize().Height;
// Capture the number of pages.
var numberOfPages = (int)Math.Ceiling(xamlPageHeight / pageHeight);
for (var i = 0; i < numberOfPages; i++)
{
// Find beginning of page.
await MainScrollLayout.ScrollToAsync(0, i * pageHeight, false).ConfigureAwait(false);
// Capture the XAML page as an image and returns the image in memory stream.
var byteData = await DependencyService.Get<IExportPdf>().CaptureAsync();
var imageStream = new MemoryStream(byteData);
// Load the image in PdfBitmap.
var pdfBitmapImage = new PdfBitmap(imageStream);
// Set the pdf page settings.
document.PageSettings.Margins.All = 0;
document.PageSettings.Orientation = PdfPageOrientation.Portrait;
document.PageSettings.Size = new SizeF(pageWidth, pageHeight);
// Add new page for graphics (otherwise graphics won't know where to draw the rest of the image)
page = document.Pages.Add();
// Graphics for drawing image to pdf.
var graphics = page.Graphics;
// Draw the image to the page.
graphics.DrawImage(pdfBitmapImage,0,0, pageWidth, pageHeight);
// Insert page at i position.
document.Pages.Insert(i, page);
// Save the document into memory stream.
document.Save(stream);
}
}
stream.Position = 0;
// Save the stream as a file in the device and invoke it for viewing.
await Xamarin.Forms.DependencyService.Get<IExportPdf>().Save(filename, "application/pdf", stream);
}
catch (Exception ex)
{
DisplayErrorAlert("DownloadPdfBtn_OnClicked", ex.StackTrace);
}
}
It is important to note that you will need a dependency in order to save anywhere other than local memory. Thankfully, Syncfusion provides a snippet for you to use. For the sake of your time, I will share the snippets. You will need to add two .cs files, one class file with the capture/save functionality and one interface file for your app.
Capture/Save class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
using Xamarin.Forms;
public class ExportPdf : IExportPdf
{
public async Task<byte[]> CaptureAsync()
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(Window.Current.Content);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView().LogicalDpi;
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
displayInformation,
displayInformation,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
var readStream = stream.AsStreamForRead();
var bytes = new byte[readStream.Length];
await readStream.ReadAsync(bytes, 0, bytes.Length);
return bytes;
}
public async Task Save(string filename, string contentType, MemoryStream stream)
{
if (Device.Idiom != TargetIdiom.Desktop)
{
var local = ApplicationData.Current.LocalFolder;
var outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (var outStream = await outFile.OpenStreamForWriteAsync()) { await outStream.WriteAsync(stream.ToArray(), 0, (int)stream.Length); }
if (contentType != "application/html") await Windows.System.Launcher.LaunchFileAsync(outFile);
}
else
{
StorageFile storageFile = null;
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.Desktop,
SuggestedFileName = filename
};
switch (contentType)
{
case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List<string> { ".pptx" });
break;
case "application/msexcel":
savePicker.FileTypeChoices.Add("Excel Files", new List<string> { ".xlsx" });
break;
case "application/msword":
savePicker.FileTypeChoices.Add("Word Document", new List<string> { ".docx" });
break;
case "application/pdf":
savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string> { ".pdf" });
break;
case "application/html":
savePicker.FileTypeChoices.Add("HTML Files", new List<string> { ".html" });
break;
}
storageFile = await savePicker.PickSaveFileAsync();
using (var outStream = await storageFile.OpenStreamForWriteAsync())
{
await outStream.WriteAsync(stream.ToArray(), 0, (int)stream.Length);
await outStream.FlushAsync();
outStream.Dispose();
}
stream.Flush();
stream.Dispose();
await Windows.System.Launcher.LaunchFileAsync(storageFile);
}
}
}
Interface:
using System.IO;
using System.Threading.Tasks;
public interface IExportPdf
{
Task Save(string filename, string contentType, MemoryStream stream);
Task<byte[]> CaptureAsync();
}
And that should do it! I hope this helps anyone that has been tasked with something similar!

The video recording device is preempted by another immersive application

Am I opening the camera for taking a picture, but the user has the possibility to stop the camera if he no longer wants to capture something, so I have a close button which is intended to close the camera, so that the camera preview should be stopped.
If I open the camera, close, open again, I will get the following exception once the close button is clicked for the second time:
System.Runtime.InteropServices.COMException: 'The video recording device is preempted by another immersive application.
I do not know, how the preview camera should be stopped, more than UWP docs say here: https://learn.microsoft.com/en-us/windows/uwp/audio-video-camera/simple-camera-preview-access
The code for stopping the camera preview:
private async Task CleanupCameraAsync()
{
if (_mediaCapture != null)
{
if (_isPreviewing)
{
await _mediaCapture.StopPreviewAsync();
}
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
CameraPreviewControl.Source = null;
if (_displayRequest != null)
{
_displayRequest.RequestRelease();
}
_mediaCapture.Dispose();
});
}
}
I tried to test your code snippet on my side and it can work well. I didn't get the above exception. I tested on the emulator build 15063 and build 14393. Since your code snippet is not the completed code, so I created a minimal project for testing as follows which can work well on my side. You may test it on your side and compare with your code if something wrong with your project.
XAML
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Padding="30">
<CaptureElement Name="PreviewControl" Stretch="Uniform"/>
<Button x:Name="btnpreview" Click="btnpreview_Click" Content="preview test"></Button>
<Button x:Name="btnstop" Click="btnstop_Click" Content="stop"></Button>
</StackPanel>
Code behind
private DeviceInformation _cameraDevice;
private MediaCapture _mediaCapture;
private InMemoryRandomAccessStream _ras;
private LowLagMediaRecording _recording;
private CameraRotationHelper _rotationHelper;
private readonly DisplayRequest _displayRequest = new DisplayRequest();
private bool _isPreviewing;
public MainPage()
{
this.InitializeComponent();
}
private async void btnstop_Click(object sender, RoutedEventArgs e)
{
if (_mediaCapture != null)
{
if (_isPreviewing)
{
await _mediaCapture.StopPreviewAsync();
_isPreviewing = false;
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
PreviewControl.Source = null;
if (_displayRequest != null)
{
_displayRequest.RequestRelease();
}
_mediaCapture.Dispose();
});
}
}
}
private async void btnpreview_Click(object sender, RoutedEventArgs e)
{
try
{
_mediaCapture = new MediaCapture();
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
var desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
_cameraDevice = desiredDevice ?? allVideoDevices.FirstOrDefault();
_rotationHelper = new CameraRotationHelper(_cameraDevice.EnclosureLocation);
_mediaCapture.Failed += MediaCapture_Failed;
var settings = new MediaCaptureInitializationSettings { VideoDeviceId = _cameraDevice.Id };
await _mediaCapture.InitializeAsync(settings);
PreviewControl.Source = _mediaCapture;
_displayRequest.RequestActive();
await _mediaCapture.StartPreviewAsync();
_isPreviewing = true;
}
catch (UnauthorizedAccessException)
{
// This will be thrown if the user denied access to the camera in privacy settings
System.Diagnostics.Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed. {0}", ex.Message);
}
}
If you still have issues, please provide a minimal reproduced project and the testing environment information. More details please reference the official sample.

MyCustomPage.xaml is not loading webView in xamarin.Forms portable

I am beginner in xamarin.forms portable, i am working on xamainr.forms portable project, there i am facing issue. I have a .xaml page in my portable project and i am navigating to this .xaml page from App.cs using following line of code.
var ep = new CustomWebViewPage(dbPath);
var MainEv = new NavigationPage(ep);
Here in CustomWebViewPage i am using WebView in following way to load Url but after successful execution above lines emulator does not load webView. I don't know why it is happening.
I am pasting code of CustomWebViewPage as following.
CustomWebViewPage.xaml.cs
using XamarinDbokReader.SQLite_AppSample;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.IO;
namespace MyDummyProject
{
public partial class CustomWebViewPage : ContentPage
{
public string dbPath = "";
public CustomWebViewPage(string folderPath)
{
this.dbPath = folderPath;
HttpHelperClass helperClass = new HttpHelperClass();
InitializeComponent();
var webView = new WebView();
UrlWebViewSource urlWebViewSource = new UrlWebViewSource()
{
Url = UrlsList.FindUrl("ProEportalLoginPage") + UrlsList.ApiKeys(AppMode.ProductionMode.ToString())
};
webView.Source = urlWebViewSource;
webView.Navigated += (s, e) =>
{
if (e.Url.StartsWith("http://userInfo/?"))
{
string token = "";
try
{
string value_string = Uri.UnescapeDataString(e.Url.ToString());
token = value_string.Split('=')[1];
if (!string.IsNullOrEmpty(token))
{
string path = Path.Combine(dbPath.ToString(), "dBookStore.db3");
helperClass.SaveUserInformation(token, path);
}
}
catch (Exception ss)
{
}
}
};
wvEportalPage = webView;
}
public CustomWebViewPage()
{
}
}
}
CustomWebViewPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDbokReader.EportalPage">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
<WebView x:Name="wvEportalPage"></WebView>
</ContentPage>
App.cs
public App(bool isSqliteDbExist, string sPath)
{
isDbExist = isSqliteDbExist;
dbPath = sPath;
if (isDbExist)
{
if (isLoggedIn)
{
NavigationPage navPage = new NavigationPage(new BooksView());
App.Current.MainPage = navPage;
}
else
{
var tdlx = new CustomWebViewPage(dbPath);
var MainNave = new NavigationPage(tdlx);
}
}
else
{
//When cursor is coming from MainActivity then following line executes. And then OnStart() method executes.
ssd.CreateTablesInDb();
isDbExist = true;
}
}
protected override void OnStart()
{
if (isDbExist)
{
if (isLoggedIn)
{
NavigationPage navPage = new NavigationPage(new BooksView());
App.Current.MainPage = navPage;
}
else
{
var ep = new CustomWebViewPage(dbPath);
var MainEv = new NavigationPage(ep);
}
}
}
MainActivity
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var bookCoverFolder = Path.Combine(documents, "BooksCover");
var booksCollection = Path.Combine(documents, "Books");
var bookResource = Path.Combine(documents, "Resource");
if(!Directory.Exists(bookCoverFolder))
Directory.CreateDirectory(bookCoverFolder);
if (!Directory.Exists(booksCollection))
Directory.CreateDirectory(booksCollection);
if(!Directory.Exists(bookResource))
Directory.CreateDirectory(bookResource);
SQLite_Android androidDb = new SQLite_Android();
if (androidDb.IsExist())
{
LoadApplication(new App(true, androidDb.dbStorePath));
}
else
{
LoadApplication(new App(false, androidDb.dbStorePath));
}
}
The WebView probably isn't getting any Width or Height.
Try setting the VerticalOptions and HorizontalOptions properties to FillAndExpand.
So like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDbokReader.EportalPage">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
<WebView x:Name="wvEportalPage" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"></WebView>
</ContentPage>
If that doesn't seem to work try wrapping it in a Grid.
Thank you for awesome sugessions, but i found my mistake in code.I did a very small mistake in App.cs After setting navigation page i am not setting NavigationPage to MainPage. It should as below.
var tdlx = new CustomWebViewPage(dbPath);
var MainNave = new NavigationPage(tdlx);
MainPage = MainNave;
it worked perfectly. I knew about MainPage but i have not written due to some other regions but ultimately it is working.
You must define Width and Height to Xamarin WebView.

Custom CommandBar to PickerFlyout

By default PickerFlyout has commandbar that has done and cancel buttons. Is it possible to disable done button programmatically? If not is there any way to add custom command bar and replace default one?
With the help of the answer given i tried to write custom picker from PickerFlyoutBase. But now i'm not able to add content to flyout in xaml. Giving me error saying custompicker doesnt support direct content
<Button>
<Button.Flyout>
<local:custompicker>
<TextBlock Margin="20" FontSize="30" Text="MyPickerFlyout Test" />
</local:custompicker>
</Button.Flyout>
</Button
public class custompicker:PickerFlyoutBase
{
private AppBar OriginalAppBar;
private CommandBar MyCommandBar;
private Page CurrentPage;
public custompicker()
{
var cancelButton = new AppBarButton();
cancelButton.Icon = new SymbolIcon(Symbol.Cancel);
cancelButton.Label = "Cancel";
cancelButton.Click += (s, e) =>
{
this.Hide();
};
MyCommandBar = new CommandBar();
MyCommandBar.PrimaryCommands.Add(cancelButton);
this.Closed += MyPickerFlyout_Closed;
this.Opening += MyPickerFlyout_Opening;
this.Placement = Windows.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Full;
}
private void MyPickerFlyout_Opening(object sender, object e)
{
CurrentPage = (Windows.UI.Xaml.Window.Current.Content as Frame).Content as Page;
if (CurrentPage != null)
{
OriginalAppBar = CurrentPage.BottomAppBar;
CurrentPage.BottomAppBar = MyCommandBar;
}
}
private void MyPickerFlyout_Closed(object sender, object e)
{
if (CurrentPage != null)
{
CurrentPage.BottomAppBar = OriginalAppBar;
}
}
}
PickerFlyout class has a ConfirmationButtonsVisible property, we can use this property to disable both "Done" and "Cancel" button.
But there is no way to disable only "Done" button. We have to implement a custom "PickerFlyout". Following is a simple custom "PickerFlyout" based on Flyout, you can refer to it to implement your own.
public class MyPickerFlyout : Flyout
{
private AppBar OriginalAppBar;
private CommandBar MyCommandBar;
private Page CurrentPage;
public MyPickerFlyout()
{
var cancelButton = new AppBarButton();
cancelButton.Icon = new SymbolIcon(Symbol.Cancel);
cancelButton.Label = "Cancel";
cancelButton.Click += (s, e) =>
{
this.Hide();
};
MyCommandBar = new CommandBar();
MyCommandBar.PrimaryCommands.Add(cancelButton);
this.Closed += MyPickerFlyout_Closed;
this.Opening += MyPickerFlyout_Opening;
this.Placement = Windows.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Full;
}
private void MyPickerFlyout_Opening(object sender, object e)
{
CurrentPage = (Windows.UI.Xaml.Window.Current.Content as Frame)?.Content as Page;
if (CurrentPage != null)
{
OriginalAppBar = CurrentPage.BottomAppBar;
CurrentPage.BottomAppBar = MyCommandBar;
}
}
private void MyPickerFlyout_Closed(object sender, object e)
{
if (CurrentPage != null)
{
CurrentPage.BottomAppBar = OriginalAppBar;
}
}
}
Then you can use it in XAML like:
<Button Content="Show Picker">
<Button.Flyout>
<local:MyPickerFlyout Closed="PickerFlyout_Closed">
<TextBlock Margin="20" FontSize="30" Text="MyPickerFlyout Test" />
</local:MyPickerFlyout>
</Button.Flyout>
</Button>
And it looks like:

Microsoft Media Player Platform with AVC encoded MP4 on Win8

I have an AVC encoded MP4 file that I would like to play in the app. But it always failed to play and the error message is "MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED : HRESULT - 0xC00D36B4". How should I resolve the problem?
BTW, the url is here:
http://coursecast2.nus.edu.sg/Panopto/Content/Sessions/1290e053-9cd0-4cda-812a-01a8bcd9a13d/91d06ea8-aaf8-463b-b8f3-1771109ff56e-e746270b-0142-413e-8587-48080a4c1c16.mp4
Thanks
EDIT 1:
I am using C# with XAML.
XAML:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<mmppf:MediaPlayer x:Name="test" MediaFailed="failed"/>
</Grid>
C#:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.test.Source = new Uri("http://coursecast2.nus.edu.sg/Panopto/Content/Sessions/1290e053-9cd0-4cda-812a-01a8bcd9a13d/91d06ea8-aaf8-463b-b8f3-1771109ff56e-e746270b-0142-413e-8587-48080a4c1c16.mp4");
}
private void failed(object sender, ExceptionRoutedEventArgs e)
{
String fail = e.ToString();
}
Edit 2: