WPF Webbrowser control issue when no internet - wpf

I have a Web browser control in my project. Works great! However if I loose connection to the internet then open the project, IE opens and shows the standard cannot display webpage.
I'd prefer the Web browser control in my project show this message and not pop up a IE browser window when the internet connection is lost.
Thanks!

You can do this by importing System.Net.NetworkInformation namespace. NetworkChange Class exposes a event called NetworkAvailabilityChanged which is responsible to notify the application on connection status change. Please find the below snippet. Please mark the answer if useful.
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}

I don't see IE open on my machine, but I do see the normal IE error messages displaying within the WebBrowser control.
I believe you could detect that the webpage wasn't loaded properly by handling the WebBrowser's Navigated event, and looking at the document's url property. Here is some XAML:
<WebBrowser Source="http://www.google.com" Navigated="WebBrowser_Navigated" />
And a bit of code (I don't do VB, sorry):
private void WebBrowser_Navigated(object sender, NavigationEventArgs e) {
var browser = sender as WebBrowser;
if (browser != null) {
var doc = browser.Document as HTMLDocument;
if (doc != null)
MessageBox.Show(doc.url);
}
}
On my machine, when the navigation failed, I got this URL:
res:ieframe.dll/navcancl.html#http://www.google.com
While I don't think we could count on the URL being exactly this all the time, I bet you could inspect it and determine that it's NOT the URL you were looking for. In fact, the "http:" is now "res:". When you see this happen (and don't expect it) you could make the browser point to a local source to display a message.

Related

Wpf webbrowser disable external links

elI am working on a Wpf application. it contains a webbrowser where the user authenticates via Facebook. The problem is that the user is capable of clicking on links (for example: Forgot your password?) the standaard browser then open... what i want to do is to disable/block all the external links. so users can only authenticate and not navigate through the webbrowser control. I hoop you guys can help me out.
Update 1
Like suggested i can check the source of the webbrowser. So i can allow the wanted pages. but the problem are the links. they open on IE. i dont want to open them, but to block them at all
Description image
private void webBrowserFacebook_Navigating_1(object sender, NavigatingCancelEventArgs e)
{
string huidigeLink = Convert.ToString(webBrowserFacebook.Source);
MessageBox.Show(huidigeLink);
// check for allowed pages
}
Update 2
I was able to find a solution: http://social.technet.microsoft.com/wiki/contents/articles/22943.preventing-external-links-from-opening-in-new-window-in-wpf-web-browser.aspx
Very slef explanatory.. thank you guys for the help!
void Window1_Loaded(object sender, RoutedEventArgs e)
{
browser = new WebBrowser();
browser.Navigate(new Uri("http://www.google.com"));
browser.Navigating += new NavigatingCancelEventHandler(browser_Navigating);
browser.Navigated += new NavigatedEventHandler(browser_Navigated);
}
void browser_Navigating(object sender, NavigatingCancelEventArgs e)
{
//Your checks should happen here..
Console.WriteLine("Loading Webpage !!");
}
void browser_Navigated(object sender, NavigationEventArgs e)
{
Console.WriteLine("Webpage Loaded !!");
}
You can register for WebBrowser.Navigating Event.
Navigating event handlers are passed an instance of the NavigatingCancelEventArgs class. You can cancel the navigation by setting the Cancel property of the NavigatingCancelEventArgs object to true.
Or you can invoke script or browser instance to stop loading if URL navigating doesn't matches.
yourWebBrowser.InvokeScript("eval", "document.execCommand('Stop');");

Navigate back button with ssrs in Silverlight app

I have a Silverlight application which has a RadHtmlPlaceholder which points to ssrs to display reports like so:
<telerik:RadHtmlPlaceholder SourceUrl="http://serverName/ReportServer/Pages/ReportViewer.aspx?/Northwind/Employees&rs:Command=render" />
This works fine but when I have a report that allows you to drill down to display a child report, there is no way of getting back to the parent report without having to load the whole lot again. There doesn't seem to be an option to turn on the navigate back button toolbar option and I've seen other ways of implementing a back button by using javascript to set the window location back one in the history, but obviously this won't work in a Silverlight application. Is there anyway to implement a navigate back button?
Take a look at this thread over in the Telerik forums: http://www.telerik.com/community/forums/silverlight/htmlplaceholder/html-place-holder-back-forward-refresh.aspx
Basically you need to get a handle on the IFrame from the presenter and inject some JavaScript. The history object also has a length property you can use to evaluate if your buttons should be enabled.
public MainPage()
{
InitializeComponent();
// Get the IFrame from the HtmlPresenter
HtmlElement iframe = (HtmlElement)htmlPlaceholder.HtmlPresenter.Children[0];
// Set an ID to the IFrame so that can be used later when calling the javascript
iframe.SetAttribute("id", "myIFrame");
}
private void Refresh_Click(object sender, RoutedEventArgs e)
{
// Code to be executed
string code = "document.getElementById('myIFrame').contentWindow.location.reload(true);";
HtmlPage.Window.Eval(code);
}
private void Back_Click(object sender, RoutedEventArgs e)
{
// Code to be executed
string code = "document.getElementById('myIFrame').contentWindow.history.back();";
HtmlPage.Window.Eval(code);
}
private void Forward_Click(object sender, RoutedEventArgs e)
{
// Code to be executed
string code = "document.getElementById('myIFrame').contentWindow.history.forward();";
HtmlPage.Window.Eval(code);
}
}

CameraCaptureTask completed event not firing in the ViewModel

I have a simple application that has a single page with a button that invokes the CameraCaptureTask in Windows Phone 7. I use the MVVM pattern for this. My code behind is clean and I have offloaded the button click response to the ViewModel using behaviors. My code looks like this:
public class MainViewModel : ViewModelBase
{
private readonly CameraCaptureTask cameraCaptureTask;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
}
else
{
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += cameraCaptureTask_Completed;
CaptureCommand = new RelayCommand(() => CaptureImage());
}
}
public RelayCommand CaptureCommand { get; set; }
private void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e == null || e.TaskResult != TaskResult.OK)
{
return;
}
else
{
// TODO
}
}
private object CaptureImage()
{
cameraCaptureTask.Show();
return null;
}
}
Now when I run my application and hit the button that binds to the 'CaptureCommand' RelayCommand, I hit my breakpoint in the 'CaptureCommand()' method and it fires the 'Show()' method of the CameraCaptureTask resulting in my camera coming up on the device successfully. However once I complete taking a picture and hit 'Accept', the 'cameraCaptureTask_Completed(object sender, Photoresult e)' event handler never gets invoked. Am I missing something here?
Thanks in advance!
Why are you relaying this when you have just a show?
Try moving the cameraCaptureTask out of the Constructor and into an invoked method
Are you using the WPConnect tools when you do this with the debugger AND a device connected?
http://msdn.microsoft.com/en-us/library/gg180729(v=VS.92).aspx
The Windows Phone Connect Tool allows you to establish serial or USB connectivity to the device without running the Zune software. When you test an application on a physical Windows Phone device, usually the Zune software is running. However, you are not able to test applications that interact with the photo chooser and camera launcher tasks while the Zune software is running, because it locks the local media database.

App xaml assumes the first window instantiated is the main window (showdialog is ignored), I need to show multiple windows

I have the following code in my App.xaml.cs
private void App_Start(object sender, StartupEventArgs e)
{
if ( CompletedInstall())
{
//using show to allow for pacifier if loading is slow
var manager = new WINServiceConfig();
MainWindow = manager;
manager.ShowDialog();
}
}
private bool CompletedInstall()
{
var window = new Initialize();
window.ShowDialog();
return window.DoLaunchManager;
}
and the following in the App.xaml
<Application x:Class="Manager.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="App_Start">
When i comment out the line that checks CompletedInstall() the manager.ShowDialog() works fine, and my configuration window shows.
When CompletedInstall() is called the call to manager.ShowDialog() returns right away without displaying the window. I added the main window on the assumption that somewhere along the line someone decided an app should only show one window.
I found a workaround by setting the main window before calling CompletedInstall
private void App_Start(object sender, StartupEventArgs e)
{
var manager = new WINServiceConfig();
MainWindow = manager;
if (CompletedInstall())
{
manager.ShowDialog();
}
but this forces me to develop WINServiceConfig (specifically the constructor) based on its use, because it cannot count on the prerequisites being completed. This is bad form. What else can i do to get around this problem?
Dummy window? That can't be the best answer. Can it??
You should set the ShutdownMode to OnExplicitShutdown (at least while showing the initial dialog).

Custom Mark-up Extensions return RoutedEvents

I'm trying to create a generalized event for my Close buttons, where they have to close the window but before that set focus to the owner window. I don't want to have an event for every file for that, because that'd be pretty unpractical since I have 30+ windows in my application. (So if I wanted to change that behavior, i'd have to change on 30 files everytime)
I'm not sure if that's the correct approach, but I tried making a MarkUp Extension which returns a delegate(object sender, RoutedEventArgs e) Here is the code:
delegate void RoutedDelegate(object sender, RoutedEventArgs e);
[MarkupExtensionReturnType(typeof(RoutedEvent))]
public class CloseWindowExtension : MarkupExtension
{
Window win = null;
public Window Win
{
get { return this.win; }
set { this.win = value; }
}
public CloseWindowExtension(Window win)
: base()
{
this.win = win;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (win == null)
{
throw new InvalidOperationException("The window must be specified!");
}
return new RoutedDelegate(delegate(object sender, RoutedEventArgs e)
{
Extensions.FocusClose(win);
});
}
}
The FocusClose method gets a window, closes it, but sets focus to its owner before. But I can't make it work. When i set my button in the xaml,
Button Click="{e:CloseWindow {Binding win}}"
(win is my Window name), I get the error message:
Click="{e:CloseWindow {Binding win}}" is not valid. '{e:CloseWindow {Binding win}}' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid. Line 28 Position 17.
Am I doing something wrong? Is this the best approach or do I have another options?
Thanks in advance!
Clark
You can't use a markup extension to set an event handler. Instead, you can use an attached behavior, which allows you to bind a command to an event.
See this article by Marlon Grech for details
.NET 4.5+ supports markup extensions for events, so you can implement what you wanted now :)

Resources