Suppress "yourdomain.com could not be found" dialog in GeckFX45 - c#

I am using GeckFX45 from NuGet to host a webpage for my OAuth2 login, During testing its behavior without internet connection I noticed that I get a dialog generated by the browser saying the URL could not be found. How can I suppress this to I can catch and handle the scenario in my app without alerting user?
My browser code is pretty standard, but for arguments sake included here anyway (Note I am using WPF not Win Forms hence the host control):
public OAuthLogin2(OAuthActions action, string args = null)
{
this.action = action;
Gecko.Xpcom.Initialize("Firefox");
host = new WindowsFormsHost();
browser = new GeckoWebBrowser();
browser.DocumentCompleted += Browser_DocumentCompleted;
browser.Navigating += Browser_Navigating;
browser.NavigationError += Browser_NavigationError;
browser.NSSError += Browser_NSSError;
InitializeComponent();
host.Child = browser;
GridWeb.Children.Add(host);
}

I can add a PromptService, but this may not work depending on language;
public class NoPromptService : PromptService
{
public override void Alert(string dialogTitle, string text)
{
log.Warn(dialogTitle, new Exception(text));
if (text.EndsWith("could not be found. Please check the name and try again."))
{
// Do Whatever
}
}
}
Add this in constructor:
PromptFactory.PromptServiceCreator = () => new NoPromptService();

Related

Xamarin.Forms handle notification launch (UWP)

Xamarin documentation is a mess all over the internet but I cannot seem to find a solid example of how to handle my Xamarin.Forms application being launched from a notification or handling a notification being clicked while my application is already running.
So I am inside of the Xamarin.Forms.UWP application in the App.xaml.cs file that handles all the UWP launching. Within the OnActivated method I can see that my application receives a fire and gets the proper data from my toast notification. My question is how do I pass that data back into the Xamarin.Forms instance.
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
var _args = (args as LaunchActivatedEventArgs).Arguments;
}
Custom UWP Notification Service:
ToastContent content = new ToastContent()
{
Launch = "...",
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = title,
HintMaxLines = 1
},
new AdaptiveText()
{
Text = body
}
}
}
},
Actions = new ToastActionsCustom()
{
Buttons =
{
new ToastButton(acceptAction.Key, $"action={acceptAction.Value}")
{
ActivationType = ToastActivationType.Foreground
},
new ToastButton(declineAction.Key, $"action={declineAction.Value}")
{
ActivationType = ToastActivationType.Background
}
}
}
};
var toast = new ToastNotification(content.GetXml());
ToastNotificationManager.CreateToastNotifier().Show(toast);
How do I go about sending this _args variable back into the running instance of my cross-platform application so that I can process the logic of navigating to a route, etc.
Furthermore if I have to write some custom code to handle this I will want the code to be easy to integrate the same functionally with the Xamarin.Forms.Android app in this project as well.

How can I avoid a memory leak in my .net Application (using VLC)

Im building a digital signage application. I need to show a mix of images and videos (3 images and then a video - then repeat this). I am using a WPF application for this. I ran out of luck using the "MediaElement" in WPF - I had some files that would not play (even the default "wildlife.wmv" file in some situations). I turned to VLC and now my application only runs for ~3 hours before i run out of memory / my vlc player going black.
I have a VLC component wrapped inside a Windows Forms component. The Windows Forms component is then added to my WPF application.
My code is shown below. Im loading this using reflection - I found this using the least amount of memory. Been going about with this for hours.
//code
string path = Assembly.GetExecutingAssembly().Location;
string directory = new System.IO.FileInfo(path).Directory.FullName;
string newPath = System.IO.Path.Combine(directory, "MedianVLCLibrary.dll");
if (System.IO.File.Exists(newPath))
{
Assembly vlcAssembly = Assembly.LoadFrom(newPath);
myVlcType = vlcAssembly.GetType("MedianVLCLibrary.VLCUserControl");
}
else
{
MedianLog.Log.Instance.LogFatal("Could not fild MedianVLCLibrary.dll");
throw new FileNotFoundException(newPath);
}
obj = Activator.CreateInstance(myVlcType);
this.presentationGrid.Children.Add((UIElement)obj); //adding the ui element to the WPF grid
MethodInfo playMethod = myVlcType.GetMethod("Play");
playMethod.Invoke(obj, new object[] { file });
EventInfo completedEvent = myVlcType.GetEvent("PlayCompleted");
Delegate completedDelegate = Delegate.CreateDelegate(completedEvent.EventHandlerType, this, "PlayerCompleted");
completedEvent.AddEventHandler(obj, completedDelegate);
And then im doing my cleanup in my "PlayComplete" method before im invoking a callback method.
obj = null;
myVlcType = null;
vlcAssembly = null;
this.presentationGrid.Children.Clear();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
FinishedCallback();
I have made a wrapper around VLC, using samples found online. Please see code below.
public partial class VLCUserControl : UserControl, IDisposable
{
AxVLCPlugin2 vlc;
public VLCUserControl()
{
InitializeComponent();
vlc = new AxVLCPlugin2();
vlc.BeginInit();
windowsFormsHost.Child = vlc;
vlc.EndInit();
}
public void Play(string path)
{
var uri = new Uri(path);
var convertedURI = uri.AbsoluteUri;
vlc.playlist.add(convertedURI, null, null);
vlc.playlist.play();
vlc.MediaPlayerEndReached += Vlc_MediaPlayerEndReached;
}
private void Vlc_MediaPlayerEndReached(object sender, EventArgs e)
{
vlc.playlist.items.clear();
vlc.MediaPlayerEndReached -= Vlc_MediaPlayerEndReached;
if (PlayCompleted != null)
{
PlayCompleted();
}
//vlc = null;
GC.Collect();
}
public void Dispose()
{
vlc.Dispose();
}
public event Action PlayCompleted;
}

How to open settings programmatically in ios

I was searching for the Xamarin implementation of How to open settings programmatically
Vito-ziv answered it for objective C - what is the correct way to do this in C# for iOS in Xamarin Studio?
For current devices this is only possible in ios8 (ios9 not available at time of writing) (It used to be possible before ios5 apparently - see this blog post from Adrian Stevens at Xamarin - shout out to him for the inspiration for this answer)
To do it in ios8, I did it like this:
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
Where the above code was called from a click event via delegate class in a UIAlertView click.
Since I am supporting ios7 too, to handle ios7 devices I did this, where the HandleLocationAuthorisation method is called when deciding whether to present a view controller - the user on ios8 and above can choose to go to the settings directly, whereas the user on ios7 has to go there manually.
This example below is checking for location services, but with trivial changes could easily be changed to check for other types of settings.
public bool HandleLocationAuthorisation ()
{
if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
return true;
} else {
UIAlertView uiAlert;
//iOS 8 and above can redirect to settings from within the app
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0)) {
uiAlert = new UIAlertView
("Location Services Required",
"",
null,
"Return To App","Open Settings");
uiAlert.Delegate = new OpenSettingsFromUiAlertViewDelegate();
uiAlert.Message = "Authorisation to use your location is required to use this feature of the app.";
//ios7 and below has to go there manually
} else {
uiAlert = new UIAlertView
("Location Services Required",
"Authorisation to use your location is required to use this feature of the app. To use this feature please go to the settings app and enable location services",
null,
"Ok");
}
uiAlert.Show ();
return false;
}
}
For completeness, here is the code for the event delgate referenced above:
public class OpenSettingsFromUiAlertViewDelegate : UIAlertViewDelegate {
public override void Clicked (UIAlertView alertview, nint buttonIndex)
{
if (buttonIndex == 1) {
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
}
}
}
Hope this will help you. This is working in iPhone not sure about working on iPad.
var url = new NSUrl("prefs:root=Settings");
UIApplication.SharedApplication.OpenUrl(url);

Problem with Delegates in C#, forms and multiple solutions

EDIT: this is a winform application, sorry for the inconvenience
Disclaimer: this is an assignment we got in college, and I'm stuck over this particular section of code.
I have 2 solutions in Visual Studio 2008, one for a Form and one for a DLL which the form can use for functionality. The idea is to send HTML mails from the client, and to use the Delegate to confirm this.
One class of the DLL contains nothing else but a single Delegate:
namespace Console.Grand
{
public delegate void ObserverDelegate(string info);
}
In a file called Delegate.cs
In the form, I have the following method which I will use for the Delegate:
private void Update(string info)
{
this.logBox.Text += Environment.NewLine + info;
}
The logBox variable is a TextArea on the form.
On transmitting, the following occurs(BL stands for "Business Layer"):
BL_MailOut bm = new BL_MailOut(s1,ListViewAdresses());
ObserverDelegate deleg = new ObserverDelegate(Update);
bm.SendMail(deleg);
The BL_MailOut constructor looks like this(we're in the DLL now):
public BL_MailOut(StandardPage page, List<MailAddress> list)
{
this.s = page;
this.adresslist = new List<MailAddress>();
foreach (MailAddress m in list)
{
this.adresslist.Add(m);
}
}
And the method SendMail:
public void SendMail(ObserverDelegate deleg)
{
IO_MailOut im = new IO_MailOut(s, adresslist, deleg);
Thread t = new Thread(new ThreadStart(im.Send));
t.Start();
}
And finally, we arrive at the method Send():
public void Send()
{
SmtpClient sc;
MailMessage msg;
string info;
foreach (MailAddress adress in this.list)
{
try
{
sc = new SmtpClient(HOST);
msg = new MailMessage(SENDER, adress.Address);
msg.IsBodyHtml = true;
msg.Subject = "test";
msg.Body = page.ToString();
sc.Send(msg);
info = "(" + DateTime.Now + ") MAIL SENT TO" + Environment.NewLine + adress.Address;
deleg(info);
}
}
I do catch the needed errors, I just left that out here to save room.
When deleg(info); is reached, expected behavior would be that the textBox receives the needed text. However, it does not. The instance of the delegate is preserved and the compiler gives no error. I've read the material on the MSDN site on Delegates, but nothing there helped.
Your Update method on the form is performing a cross-thread operation, which is not allowed.
Change your Update method on the form to this
private void Update(string info)
{
ObserverDelegate callBack = new ObserverDelegate((x) =>
{
this.logBox.Text += Environment.NewLine + info;
});
if (this.InvokeRequired)
this.Invoke(callBack, info);
else
callBack(info);
}
I do something similar to this in my program...here is how I did it.
public void setBoxText(string value)
{
if (InvokeRequired)
Invoke(new SetTextDelegate(setBoxText), value);
else
statusBox.Text += value;
}
delegate void SetTextDelegate(string value);
I then call setBoxText whenever I want to append text to the box.

Forms authentication + URL Rewriting gives access to secure pages

I have a problem with URL rewriting and Forms authentication in ASP.NET... Based on articles I've found on the net, I have created the following HttpModule:
public class UrlRewriter : IHttpModule
{
private UrlRewriteConfigurationSection config;
public UrlRewriter()
{
config = ConfigurationManager.GetSection("urlrewrites") as UrlRewriteConfigurationSection;
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
httpApplication.AuthorizeRequest += new EventHandler(OnAuthorizeRequest);
}
private void OnAuthorizeRequest(object sender, EventArgs e)
{
string requestedPath = HttpContext.Current.Request.Path;
foreach (UrlRewriteRule rule in config.UrlRewriteRules)
{
RegexOptions options = config.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
Regex regex = new Regex(rule.UrlPattern, options);
Match match = regex.Match(requestedPath);
if (match.Success)
{
string newPath = regex.Replace(requestedPath, rule.RewritePattern);
if (!String.IsNullOrEmpty(newPath))
{
HttpContext.Current.RewritePath(newPath);
return;
}
}
}
}
}
The problem, however, is that this somehow disables authorization! To explain assume i have the following rewrite rule:
UrlPattern: ^user/profile$
RewritePattern: protected/profile.aspx
And assume that the folder protected is setup to deny anonymous users access..
Now, when the code in the OnAuthorizeRequest runs, it correctly rewrites the path to protected/profile.aspx, however, the problem is that I am shown the page, even though I'm not logged in! If I request the page directly (http://localhost/site/protected/profile.aspx) it does not allow access to the site..
All articles I find on the net says I need to do the rewrite in AuthorizeRequest as opposed to AuthenticateRequest or BeginRequest..
Any ideas?
N.B.: I have tried moving my rewriting code to AuthenticateRequest which does seem to work, but redirection to the login page is not correct (e.g. it redirects to /login?returnUrl=protected/profile.aspx instead of login?returnUrl=user/profile)

Categories

Resources