I have an UWP app which displays several catalogs of videos. They are located in separate pages. For this purpose I've created an NativeAdV2 control:
public sealed partial class CardAdvert : UserControl
{
NativeAdsManagerV2 manager = new NativeAdsManagerV2("d25517cb-12d4-4699-8bdc-52040c712cab", "test");
NativeAdV2 advert;
public CardAdvert()
{
InitializeComponent();
manager.AdReady += AdReady;
manager.RequestAd();
}
private void AdReady(object sender, NativeAdReadyEventArgs e)
{
advert = e.NativeAd;
Initialize();
e.NativeAd.RegisterAdContainer(this); //Exception is here
}
public void Initialize()
{
title.Text = advert.Title;
image.Source = new BitmapImage(advert.MainImages.First().Url.ToUri());
if (advert.AdIcon == null)
contentGrid.ColumnDefinitions[0].Width = new GridLength(0);
else
icon.ProfilePicture = advert.AdIcon.Source;
if (string.IsNullOrWhiteSpace(advert.SponsoredBy))
sponsor.Visibility = Visibility.Collapsed;
else
sponsor.Text = advert.SponsoredBy;
if (!string.IsNullOrWhiteSpace(advert.Rating))
info.Text += $" {advert.Rating}";
if (string.IsNullOrWhiteSpace(advert.CallToActionText) && string.IsNullOrWhiteSpace(advert.Price))
desc.Visibility = Visibility.Collapsed;
else if (!string.IsNullOrWhiteSpace(advert.CallToActionText))
desc.Text = advert.CallToActionText;
else
desc.Text = advert.Price;
}
}
But no matter where I create it (even on different page) on the second or third time it throws me an exception on e.NativeAd.RegisterAdContainer(this):
Unhandled exception at 0x082A1330 (Windows.UI.Xaml.dll) in FoxTube.exe:
0xC000027B: An application-internal exception has occurred (parameters: 0x1E9F4608, 0x00000003)
There is no anything similar neither on MSDN forum or elsewhere nor in NativeAdV2 class documentation
Perfectly, I'd like to insert this control every 10 videos. Or at least on every page. Is there any solutions?
Actually, I don't know why Microsoft doesn't want to fix this but as they said it works on earlier builds. You just need to downgrade your target and minimal versions to 17134 and it will work. You can also use Windows UI Library to get latest XAML controls
Related
I am using a secondary view to run my media files, but When I close my secondary view with close button on it (while media is still playing) the secondary view/window closes but the media somehow keeps playing because I can hear the sound and source of sound seems to be the primary view (main app window). How can I completely terminate the secondary window when I close it?
Here is my code to create the secondary view.
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var frame = new Frame();
frame.MinHeight = 200;
frame.MinWidth = 200;
compactViewId = ApplicationView.GetForCurrentView().Id;
frame.Navigate(typeof(CompactNowPlayingPage), caption);
Window.Current.Content = frame;
Window.Current.Activate();
ApplicationView.GetForCurrentView().Title = Title;
});
bool viewShown = await ApplicationViewSwitcher.TryShowAsViewModeAsync(compactViewId, ApplicationViewMode.Default);
Update
After some debugging I've come to know that close button pressed on the secondary view only hides the view but it keeps on running on its thread, I just want that close button to completely close the secondary view, close its thread and destroy the window as a whole.
Update 2
I followed windows samples multiple views and was able to complete all steps, the code runs fine until it reaches Windows.Current.Close() in released event.
Then it gives an exception when it tries "Window.Current.Close()" with in the released event. according to documentation exception occurs due to any on going changes ( which might be because of media file playing ), but I need to force close the window even when media file is playing how can I do that? Here is the exception:
Message = "COM object that has been separated from its underlying RCW cannot be used."
Update 3
This is the latest updated, I am not following official sample now, just following simpler approach now.
Code to open secondary view:
await Helpers.DeviceTypeHelper.CompactOpen(e.ClickedItem as Video, identifier); //where identified is just a string for some custom logic in the secondary view.
//following method is located in a helper class within the project
internal static async Task CompactOpen(Video PlayingVideo, string caption)
{
ApplicationView newView = null;
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var frame = new Frame();
frame.Navigate(typeof(CompactNowPlayingPage),new object[] { PlayingVideo,caption});
Window.Current.Content = frame;
Window.Current.Activate();
newView = ApplicationView.GetForCurrentView();
newView.Title = PlayingVideo.MyVideoFile.DisplayName;
});
await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newView.Id);
}
Secondary View:
public sealed partial class CompactNowPlayingPage : Page
{
public CompactNowPlayingViewModel ViewModel { get; } = new CompactNowPlayingViewModel();
private CustomMediaTransportControls controls;
public CompactNowPlayingPage()
{
InitializeComponent();
this.Loaded += MediaPage_Loaded;
this.Unloaded += MediaPage_Unloaded;
Microsoft.Toolkit.Uwp.UI.Extensions.ApplicationView.SetExtendViewIntoTitleBar(this, true);
Microsoft.Toolkit.Uwp.UI.Extensions.TitleBar.SetButtonBackgroundColor(this, Colors.Transparent);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string chk = "";
var paramm = e.Parameter as object[];
NowPlayingVideo = paramm[0] as Video;
var vis = Visibility.Collapsed;
chk = paramm[1].ToString();
switch (chk)
{
case "library":
vis = Visibility.Visible;
break;
case "playlist":
vis = Visibility.Visible;
break;
case "history":
vis = Visibility.Collapsed;
break;
case "directplay":
vis = Visibility.Collapsed;
break;
default:
break;
}
controls = new CustomMediaTransportControls(NowPlayingVideo,vis);
Media.TransportControls = controls;
PlayVideo();
}
private Video NowPlayingVideo { get; set; }
private void PlayVideo()
{
if (NowPlayingVideo != null)
{
string token = "";
if (StorageApplicationPermissions.FutureAccessList.Entries.Count == 800)
{
var en = StorageApplicationPermissions.FutureAccessList.Entries;
StorageApplicationPermissions.FutureAccessList.Remove(en.Last().Token);
}
token = StorageApplicationPermissions.FutureAccessList.Add(NowPlayingVideo.MyVideoFile);
Media.Source = null;
Media.Source = $"winrt://{token}";
SetViews();
}
}
private void SetViews()
{
NowPlayingVideo.Views++;
Database.DbHelper.UpdateViews(NowPlayingVideo.MyVideoFile.Path);
}
private void MediaPage_Loaded(object sender, RoutedEventArgs e)
{
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Consolidated += MediaPage_Consolidated;
}
private void MediaPage_Unloaded(object sender, RoutedEventArgs e)
{
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Consolidated -= MediaPage_Consolidated;
}
private void MediaPage_Consolidated(Windows.UI.ViewManagement.ApplicationView sender, Windows.UI.ViewManagement.ApplicationViewConsolidatedEventArgs args)
{
Window.Current.Close();
}
}
Secondary View XAML:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<vlc:MediaElement AreTransportControlsEnabled="True"
Name="Media"
HardwareAcceleration="True"
AutoPlay="True">
</vlc:MediaElement>
</Grid>
Case 1 : Everything runs perfect if I place a video file in Assets folder and give it as a source to the media element and comment the whole OnanvigatdTo method on secondary page. And I am able to successfully close the window as well.
...
Case 2 : But when I try to set the media through the NowPlayingVideo object as shown in the code above and I also use default Transport Controls, so I don't comment the lines used to assign custom transport controls in the above code it runs fine, but when I then try to close the window I get following exception in App.i.g.cs file but stacktrace doesn't exist:
Message = "Attempt has been made to use a COM object that does not have a backing class factory." Message = "COM object that has been separated from its underlying RCW cannot be used.
Case 3 : Exactly like case 2 but here I uncomment Custom transport controls lines so now I am assigning custom transport controls to my media element, this time exception is a bit different with some stacktrace as well
StackTrace = " at System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRT(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)\r\n at Windows.UI.Xaml.DependencyObject.get_Dispatcher()\r\n at VLC.MediaElement.d__160.MoveNext()\r\n--- End of stack trace ...
Message = "Attempt has been made to use a COM object that does not have a backing class factory."
The short answer is: you need to make sure nothings holds on to your view instance, and you call Window.Close in the view's Consolidated event. The longer answer with code is here in the official sample. Take a look at the ViewLifetimeControl.cs source file: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/MultipleViews/cs
Am new to CefSharp
I have created a class library project and referenced the CefSharp library to render the Web browser, However I am facing some issues showing the web Browser. Please find the exact code
WebBrowser_test1:
public partial class ChildWidget : Window
{
public CefSharp.Wpf.ChromiumWebBrowser webView;
public Widget()
{
InitializeComponent();
CefSharp.CefSettings settings = new CefSharp.CefSettings();
settings.PackLoadingDisabled = true;
if (CefSharp.Cef.Initialize(settings))
{
webView = new CefSharp.Wpf.ChromiumWebBrowser();
main_grid.Children.Add(webView);
webView.Address = "http://www.google.co.uk";
}
}
}
and I am referencing this library (dll) in another project
public MainWindow()
{
InitializeComponent();
Button newbutton = new Button();
newbutton.Width = 50;
main_grid.Children.Add(newbutton);
newbutton.Click += ButtonClick;
}
private void ButtonClick(object sender, RoutedEventArgs e)
{
try
{
Webbrowser_test1.ChildWidget childWidget = new Widget();
childWidget.Show();
}
catch (Exception)
{
throw;
}
}
Now on the Button click I will open the (WebBrowser_test1) child widget in which I will show the web browser .. when the window opens it is showing blank.
Please let me know if I missing anything
Subscribe to IsBrowserInitializedChanged after creating a ChromiumWebBrowser. Then once the browser is initialized you can call Load and your control will be displayed.
...
_browser = new ChromiumWebBrowser();
mainGrid.Children.Add(_browser);
_browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
...
void OnIsBrowserInitializedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_browser.IsBrowserInitialized)
{
_browser.Load("https://www.google.com/");
}
}
I can think of the first three potential issues. But it's hard to tell what the real issue is from your code alone as it strays off a bit from the official examples
Move Cef.Initialize() to your MainWindow constructor. It should only be called once to launch the CefSharp.BrowserSubprocess.exe renderer process.
See my answer to CefSharp 3 always failing Cef.Initialize() for a few things to check regarding binaries and their placement. Really, the recommended approach is to start having the WPF example in the CefSharp.MinimalExample repo running first and then adjust to your use case from there.
I'm not sure a ChromiumWebBrowser() without explicitly setting a width and height works. A 0x0 window might not receive any rendered content. I haven't tried with recent code.
Have you tried replacing
webView.Address = "http://www.google.co.uk";
with
webView.Load("http://www.google.co.uk");
Like jornh mentions, you may have to explicitly set the height and width of the ChromiumWebBrowser. If you don't know the exact size, setting HorizontalAlignment and VerticalAlignment to Stretch (to fill the parent container) will probably also work.
Have you checked if the Cef.Initialize() actually returns true? You could be missing some files, and CefSharp doesn't always give clear error messages when this is the case.
In my App you can open a Site where you can switch on and off the Flashlight.
The first time it works, but if I try to switch the flashlight on a second time the App crashes.
I think this is a Problem with AudioVideoCaptureDevice.OpenAsync. If I call it a second time the App crashes with a System.Reflection.TargetInvocationException WinRT-Informationen: Unable to acquire the camera. You can only use this class while in the foreground.
Someone know this Problem?
protected AudioVideoCaptureDevice Device { get; set; }
public Page10()
{
InitializeComponent();
}
async void tglSwitch_Checked(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
if (this.Device == null)
{
// get the AudioVideoCaptureDevice
this.Device = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
}
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
this.tglSwitch.Content = "Light on";
this.tglSwitch.SwitchForeground = new SolidColorBrush(Colors.Green);
}
}
void tglSwitch_Unchecked(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
sensorLocation = CameraSensorLocation.Back;
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (this.Device != null && supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.Off))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
this.tglSwitch.Content = "Light off";
}
}
I would recommend to initialize the camera with OpenAsync ONE TIME in page lifecycle, for example in OnNavigatedTo event. And only makeSetProperty() methods calls code in your checkbox events to control light. It is also very important to dispose camera correctly then leaving the page, for example in OnNavigatedFrom event, by calling device.Dispose(). This option also make your flashlight to work faster.
Keep in mind that Windows Phone 8.1 now has dedicated API for torch, which works great and the code is more beautiful. You can use in Silverlight project as well, but you have to migrate your project. Here is more about this http://developer.nokia.com/community/wiki/Using_the_camera_light_in_Windows_Phone_7,_8_and_8.1 and https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.devices.torchcontrol.
I'm developing a Windows Phone app that uses the older WP7 Microsoft.Phone.Controls.Maps.Map / Bing Map control.
The map tiles are being served up from a local source so the app doesn't not need a network connection to work. Unfortunately the map control insists on showing an "Unable to contact Server. Please try again later." message over the map when offline.
Does anyone know of a method to remove / hide this message?
Just in case you're curious - I'm developing a WP8 app but using the depreciated WP7 Bing map control as the new WP8 map control provides no method for replacing the Bing base map.
i think this may suits you better:
void YourPage_Loaded(object sender, RoutedEventArgs e)
{
m_Map.ZoomLevel = 11;
m_Map.LayoutUpdated += m_Map_LayoutUpdated;
}
void m_Map_LayoutUpdated(object sender, EventArgs e)
{
if (!isRemoved)
{
RemoveOverlayTextBlock();
}
}
void RemoveOverlayTextBlock()
{
var textBlock = m_Map.DescendantsAndSelf.OfType<TextBlock>()
.SingleOrDefault(d => d.Text.Contains("Invalid Credentials") ||
d.Text.Contains("Unable to contact Server"));
if (textBlock != null)
{
var parentBorder = textBlock.Parent as Border;
if (parentBorder != null)
{
parentBorder.Visibility = Visibility.Collapsed;
}
isRemoved = true;
}
}
You have to include a class LinqToVisualTree witch can be downloaded from here.
And here is the original post
You can either handle the LoadingError event per instance or extend the Map control yourself as described in this post. You can then remove the layer than contains the error message so that it's not shown to the user.
public partial class CachedMap : Map
{
public CachedMap() : base()
{
base.LoadingError += (s, e) =>
{
base.RootLayer.Children.RemoveAt(5);
};
}
}
I know it's a very old thread, but anyways...
You can listen for LoadingError event as suggested #keyboardP, search for LoadingErrorMessage control in visual tree and simply hide it.
Map.LoadingError += MapOnLoadingError;
private void MapOnLoadingError(object sender, LoadingErrorEventArgs e)
{
var errorMessage = Map.FindChildOfType<LoadingErrorMessage>();
errorMessage.Visibility = Visibility.Collapsed;
}
Firstly, a disclaimer, what you're about to witness is my first bit of coding for almost 20 years. I'm new to C# and WPF, trying to get my head WPF is more than a challenge.
For the past month I've been working on a pet project console application, which has been performing well. I'm now trying to take it another step further by adding a modern GUI to the project.
I'd like to emulate a console (just the basic outpu functionality) by using a WPF textblock wrapped inside a scroller in a WPF window. You can see the original console application in action here to get a better idea of the kind of console output I'm trying to emulate. But I'm having a major problem with basic function calls, and I assume it's because I don't fully understand how WPF/C# work under the hood.
The Application starts in code via Main() like so:
class Program
{
public static ConsoleWindow MainConsole = new ConsoleWindow();
[STAThread]
static void Main(string[] args)
{
Application MyApplication = new Application();
MyApplication.Run(MainConsole);
// The following code does not work, it produces no output in the Textblock
MainConsole.WriteLine("Crystal Console");
MainConsole.WriteLine("Version: " + Properties.Settings.Default.BuildVersion);
MainConsole.WriteLine("Current Time: " + DateTime.Now);
MainConsole.WriteLine("Last Login: " + Properties.Settings.Default.dateLastLogin);
}
}
The problem is that the methods called don't seem to have any affect on the content of the textblock.
Although I'm about to give a lot of information just in case it's needed, the question itself is quite simple: Why does the Textblock update fine when taking content from a textbox control on the same window, but doesn't show any updates when the same method is called in Main() ?
For testing purposes the window has a few Textboxes that call the .WriteLine method inside the window, and THAT works, so I know there isn't a problem with the .WriteLine code, which you can see here:
public void WriteLine(string Message = null, string Sender = null)
{
_Console.AddElement(new ConsoleElement(Sender, Message + "\n"));
_Console.DisplayContent(ConsoleTextBlock);
ConsoleScroller.ScrollToEnd();
}
Here is the code for the console itself in case it's needed, the class "ConsoleElement" is essentially just a object that contains the messages to be displayed in the Textblock as well as the formatting for each one.
class ConsoleStream
{
IList<ConsoleElement> ConsoleElements = new List<ConsoleElement>();
public void AddElement(ConsoleElement NewElement)
{
if (NewElement.Sender == null) // Sender is System not user.
{
NewElement.Content = " " + NewElement.Content;
NewElement.Font = new FontFamily("Arial");
NewElement.FontSize = 12;
}
ConsoleElements.Add(NewElement);
}
public void ClearElements()
{
ConsoleElements.Clear();
}
public void DisplayContent(TextBlock sender)
{
sender.Text = null;
foreach (ConsoleElement Message in ConsoleElements)
{
//If message is a status update, i.e. has no sender, format it as a system message.
if (Message.Sender != null)
{
sender.Inlines.Add(new Run(Message.Sender + ": ") { Foreground = Message.SenderColour, FontFamily = Message.Font, FontSize = Message.FontSize });
}
//if message has a sender it's either the user or the AI. Format it as a user message.
if (Message.Sender != null) sender.Inlines.Add(new Run(Message.Content) { Foreground = Message.ContentColour, FontFamily = Message.Font, FontSize = Message.FontSize });
else sender.Inlines.Add(new Run(Message.Content) { Foreground = Message.SystemColour, FontFamily = Message.Font, FontSize = Message.FontSize });
}
}
}
MyApplication.Run(MainConsole); takes control of the thread, the code after it doesn't execute until after you close the window.
Move the code to the load (or init) method of your ConsoleWindow