Browser not opening when LaunchUriAsync is true - c#

I'm trying to have the default web browser open up an URL that is provided by the user in this case let's say it's https://stackoverflow.com/ but when the program runs the app is returning true for the LaunchUriAsync, but it isn't opening the browser and navigating to the site. How would I get a browser to open up the URL?
private void Button_Click(object sender, RoutedEventArgs e)
{
string url = StoreUrl.Text;
Uri uri = new Uri(#"" + url);
DefaultLaunch(uri);
}
async void DefaultLaunch(Uri uri)
{
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
}

I just created a new project and pasted the following code into the Loaded event
var success = await Windows.System.Launcher.LaunchUriAsync(new Uri("https://stackoverflow.com/"));
It worked fine for me.
If the call returns true, there seemingly nothing to stop this from working. At this stage I would suggest this is an environmental issue, or something do with the shell mechanism of that browser.
From here I would
Test this in a new clean project.
Change the default browser, if this works then there is likely some sort of setting/corruption within the browser
Disable your antivirus and see if it works.

Related

Xamarin Android get Current Url after login and cookies

This question was asked before but not the correct working answer given.
Android - extracting cookies after login in webview
My question has many sub-parts: (visual studio 2017 Android Emulator API25)
1-I need to connect an url ../signin that redirects me to Office365 login.
after that it will send me to ../login.
2- I need to get cookies that was given by office365/backend after the ../login redirection. (in iOS you dont need to declare the url to get the cookie, but in android you have to)(How do I access cookies in a Xamarin WebView?)
3- ../signin has HTTPS, but my webview element cannot open the website. However, I can open google, facebook etc. I recieve untrusted SSL error. from my laptop, I can connect to that url.
4- Although it is literally 2-3 lines of code for iOS, for android I couldnt find any result. I need to get current url of webview after redirections. However, webview.URL only returns the initial given url of webview.loadURl(String url), although it is not the current url.
5- I searched for webview.onPageFinished(WebView webview,String URL) in order to put current url and check if it is ../login rightnow. So I can get the cookies. iOS has onPageFinished event listener, but Android has not.
Heres my code for the thing:
WebView wv = new WebView(this);
SetContentView(wv);
wv.SetWebViewClient(new WebViewClient());
wv.LoadUrl("../signin");
wv.Settings.JavaScriptEnabled = true;
var client = new WebViewClient();
wv.SetWebViewClient(new WvClient(this, wv));
for onPageListener
public class WvClient : WebViewClient
{
public Activity mActivity;
public WvClient(Activity mActivity,WebView wv)
{
this.mActivity = mActivity;
onPageFinished(wv,wv.Url);
}
public void onPageFinished(WebView wv, String url)
{
var cookieHeader = CookieManager.Instance.GetCookie(wv.Url);//This is how I will get the cookie.
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, Android.Net.Http.SslError er)
{
handler.Proceed();// Ignore SSL certificate errors
}
}
Thank you!!
You should override these method. Then you could each url of webview after redirections.
For example:
public override void OnPageFinished(WebView view, string url)
{
var cookieHeader = CookieManager.Instance.GetCookie(view.Url);
base.OnPageFinished(view, url);
}
public override void OnReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
{
handler.Proceed();
}

Programatically press a button in a website from an app in a phone

I am creating a UWP app using c#. The app is supposed to fetch information from a website and present it to the user. I've went through the DOM of the site and managed to download the HTML of the site. But some of the information is hidden and only appears when certain buttons or selections are made on the website. Is there a way that I can programmatically go into the site, make a selection, the download the new html?
2nd Question: The app should have an fb liveChat function linked an fb page. How do I link facebook liveChat into this app? I do not have an idea in my head on how to make this work. Thank you for you help.
Here is an example for Entering text in search box and Click search button in Bing
Use WebView to do all the work
WebView webView = new WebView();
Use InvokeScriptAsync method for WebView to use JS code
webView.InvokeScriptAsync("eval", new string[] {});
Get the HTML of the site using below code
public LoadURI()
{
webView.Navigate(new Uri("https://www.bing.com/"));
webView.NavigationCompleted += webView_NavigationCompletedAsync;
}
string siteHtML = null;
private async void webView_NavigationCompletedAsync(WebView sender, WebViewNavigationCompletedEventArgs args)
{
siteHtML = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
}
Enter text in search box using below code
private async void EnterTextAsync(string enterText)
{
var functionString = string.Format(#"document.getElementsByClassName('b_searchbox')[0].innerText = '{0}';", enterText);
await webView.InvokeScriptAsync("eval", new string[] { functionString });
}
Simulate click using below code
private async void SimulateClickAsync()
{
var functionString = string.Format(#"ddocument.getElementsByClassName('b_searchboxSubmit')[0].click();");
await webView.InvokeScriptAsync("eval", new string[] { functionString });
}
Get new site's HTML using Step 3
Here is a Sample app for LogIn to StackOverflow: StackOverFlow-LogIn

asp.net response.redirect hitting url, but not changing browser page

I have an aspx page (webforms) that is called from a jQuery Post method (which works fine), however the Response.Redirect method from the code behind does not reload the browser with the redirected URL. It does actually hit the URL, however.
I'm pretty sure this has something to do with the page being called from jQuery, but not sure why this behavior is happening.
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//lid = Validation.StripToGUID(ObjToGUID(Request.QueryString("lid")))
lid = Validation.StripToGUID(ObjToGUID(Request.Form["lid"]));
string sid = null;
if (lid.Length == 36)
{
//retrieve the link (and product data) from the database
LiveItem_Data.DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem o = new LiveItem();
o = LiveItem_Data.GetLive_ItemFromLID(lid);
if (HTTPStuff.RemoteFileExists(o.product_link))
{
Response.Redirect(o.product_link, true);
}
else
{
//generate an error
}
}
}
}
I stepped through the code and the product_link is working (manually cutting and pasting into a browser), and the remote page is being called (I'm testing the link with another site that has logging).
The browser however does not open (tried FF, IE, Opera, Chrome) the new URL.
The jQuery post:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID });
});
I verified that HTTPredirect feature is turned on in IIS Express (from Visual Studio 2012). Stumped!
I think from the jquery function, it will not redirect the page from server you will have to do this on client side itself i.e in the success part of the click function
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID }).success(function() {
//write the redirection code here
});
});
I don't think you're using post right. Post is for making a hidden service call and does not affect the browser window.
If you just want to redirect the browser window, and redir.aspx will accept either GET or POST, you can use window.location.href:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
window.location.href = "redir.aspx?lid=" + ListID;
});
If redir.aspx does not accept GET, I suggest you create a hidden form on your page (with an lid hidden input element) and post it programmatically.

Facebook re-authentication in a popup window

I write a windows forms application that connects to user's profile in facebook, reads his wall and shows him updates in a widget, with the help of facebook c# sdk.
Everything works fine, except for the fact that facebook won't let my user change his credentials, that means re-login as a different user.
My authentication flow is schematically as follows:
In login process initializer:
note: The dialog is shown in a popup. If you show dialog in a full
browser, it's possible to logout, but in popup this functionality
seems to be lacking.
private void loginButton_Click(object sender, EventArgs e){
browser = new WebBrowser();
this.browser.Navigated += new WebBrowserNavigatedEventHandler(browser_Navigated);
//+ all types of gui settings for the borwser
form.Controls.Add(browser);
Uri url=new Uri("https://www.facebook.com/dialog/oauth?client_id=" + {*MyAppsId*}+
"&redirect_uri=" + "https://www.facebook.com/connect/login_success.html" +
"&response_type=token"+
"&auth_type=reauthenticate"+
"&display=popup"+
"&scope=read_stream"
browser.Navigate(url);// +try/catches - omitted
}
Navigation response parsing:
note: just parsing the response with the use of c# sdk classes FacebookOAuthResult and FacebookClient
private void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e){
FacebookOAuthResult oauthResult; //helps to streamline parsing
if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult)){ //type of fb is FacebookClient of c# sdk
if (oauthResult.IsSuccess){
accessToken = oauthResult.AccessToken;
//from here start reaing user's feed with the help of access token
}
}
}
What i meant to do by it is that when the login button is clicked, the user is prompted his username and password.
However, the user is prompted to re-enter his password only, not to re-enter his username.
If I use the url without the "&auth_type=reauthenticate" parameter , it doesn't prompt for anything and straight sends me the access token.
How can I force the facebook to ask for a username?
After days of fighting, the answer was under my nose.
You just need to call https://www.facebook.com/logout.php with your access token:
WebBrowser browser = new WebBrowser();
browser.Navigated += browser_NavigatedLogout;
string logoutUrl = "https://www.facebook.com/logout.php?" +
"next=https://www.facebook.com/connect/login_success.html" +
"&access_token=" + MyAccessToken;
try
{
browser.Navigate(new Uri(logoutUrl));
}
catch (System.Exception other)
{
MessageBox.Show("error logging out: "+other.Message);
}
and the handler is:
private void browser_NavigatedLogout(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
{
//here anything you need to do after the user logged off
}
}

"The post's links must direct to the application's connect or canvas url"?

I'm building an application for WP7 using the Facebook C# SDK. When I attempt to post a message to a users wall (Just a plain message) everything works fine. But when I attempt to post a link to the users wall I get this exception message:
(OAuthException) (#100) The post's links must direct to the application's connect or canvas URL.
Does anyone know how to fix this? I have heard of canvas applications but I didn't think this applied to a phone app. Perhaps this is a setting on Facebook?
Any feedback is appreciated.
Here is the code I used to post to facebook:
private void button1_Click(object sender, RoutedEventArgs e)
{
_fbClient.PostCompleted +=
(o, er) =>
{
if (er.Error == null)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(er.Error.Message);
}
};
var args = new Dictionary<string, object>();
args["name"] = "Hello World!!";
args["link"] = "http://www.nfl.com";
args["caption"] = "";
args["description"] = "";
args["picture"] = "";
args["message"] = "Hello World from application.";
args["actions"] = "";
FacebookAsyncCallback callback = new FacebookAsyncCallback(this.postResult);
_fbClient.PostAsync("me/feed", args, callback);
}
private void postResult(FacebookAsyncResult asynchResult)
{
MessageBox.Show("Success");
}
NOTE: If I remove the string from "link" it works.
I found a solution to my problem "here". In your app settings within Facebook you have to set "Stream Post Url Security" to false. Hope this helps someone.
Go to the Facebook App. Edit its settings. On the Advanced settings page, disable the "Stream post URL security" option.

Categories

Resources