How to verify that the web page is opened in the browser - c#

I'm automating a windows based desktop application(C#, LeanFT).
Clicking on a button, opens a web page in the browser.
How can I verify the web page is opened?

Two ways:
Brute force
By describing the browser that was opened, which has a title, a url and other attributes, and then attaching to it.
The problem with this approach is that, if the browser was not opened, it will throw an error, so you'll have to try..catch that error
For example:
/*
* Desktop related logic that opens a browser
*/
// Use "Attach" to connect a new (or replacement) browser tab with the LeanFT test.
try {
IBrowser yourPage = BrowserFactory.Attach(new BrowserDescription
{
Title = "The title of the page",
Url = "https://thesitethatwasopened.com"
});
} catch (Exception ex) {
// the browser was not opened
}
/*
* Rest of the desktop app actions
*/
Iterating over all opened browsers
You'd still need the same description, but this way you can either get no browsers at all, which means that the page was not opened, or one or more browsers - in either case, this doesn't throw an error, so you can call it a "cleaner" way:
For example:
/*
* Desktop related logic that opens a browser
*/
// Use "GetAllOpenBrowsers" to get a collection of IBrowser instances that matches the description
IBrowser[] yourPages = BrowserFactory. GetAllOpenBrowsers(new BrowserDescription
{
Title = "The title of the page",
Url = "https://thesitethatwasopened.com"
});
/*
* Rest of the desktop app actions (maybe by making use of yourPages.Count
*/

Related

ASP.NET C# Response.Write doesn't display message

So I am told just by using Javascript inside the Response.Write method, I can display an alert/message box on ASP.NET C#.
Using Response.Write("<script>alert('Data inserted successfully')</script>") as the template given in other answers.
When I first attempted to use it, it worked, displaying the message and redirecting me sucessfully. Since then, it has not worked, I only changed the message to display and also where the redirect URL would go after. Logically it is working as it is taking me back to the application form, it just isn't displaying the message.
Can anyone explain why it suddenly doesn't work?
Code;
public ActionResult UpdateApplication(int ApplicationId, ApplicationEdit applicationEdit)
{
if(applicationEdit.Firm == false)
try
{
applicationService.UpdateApplication(applicationEdit, ApplicationId);
return RedirectToAction("GetUser", "User", new { ApplicationId = applicationEdit.ApplicationId });
}
catch
{
return View();
}
else
{
Response.Write("<script language=javascript>alert('Sorry, You can only have 1 firm application to send off, please update the old application and untick firm option on other application first.')</script>");
return RedirectToAction("UpdateApplication", new { ApplicationId = applicationEdit.ApplicationId });
}
}
Because you're redirecting the user:
return RedirectToAction("UpdateApplication", new { ApplicationId = applicationEdit.ApplicationId });
This returns a redirect HTTP code to the browser (HTTP 307 or 308 I imagine) which tells the browser to direct the user to the specified URL. Since the browser knows it's redirecting the user, it has no reason to render any content in the response.
Either return content to be rendered in the browser or return a redirect response, but not both. If you return the view instead then you should see your <script> element in the resulting response. If you want to redirect then any message you want to display to the user should be on that next page, not in the current response.
As an aside, using Response.Write in an ASP.NET MVC application is pretty much always the wrong approach. Any client-side code should be in or referenced by the view, and you can use data on the view's model to conditionally render or not render that content.

Xamarin iOS C# Open Links in Safari from UIWebView

I'm coding an iPhone app with a UIWebView, in Xamarin using C#.
By default embedded links within the web view open a web page in that same web view. I would instead like them to launch the linked page in a new safari browser instance.
This has been answered for objective C in X-Code but as far as I can see not for Xamarin C#
webView.LoadHtmlString(html, new NSUrl(Const.ContentDirectory, true));
Thanks in advance
Adam
You can open a web page in the brower of the device (Safari) with this command.
UIApplication.SharedApplication.OpenUrl(new NSUrl("www.google.com"));
You don't have to use UIWebView at all. If you want to open some web pages in UIWebView and some with Safari you need to implement the ShouldStartLoad delegate. Here you can determine whether to open the web page in UIWebView or rather in Safari.
private bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
{
// you need to implement this method depending on your criteria
if (this.OpenInExternalBrowser(request))
{
// open in Safari
UIApplication.SharedApplication.OpenUrl(request.Url);
// return false so the UIWebView won't load the web page
return false;
}
// this.OpenInExternalBrowser(request) returned false -> let the UIWebView load the request
return true;
}
At last somewhere in ViewDidLoad (or other place where you initiliaze the WebView) add the following code.
webView.ShouldStartLoad = HandleShouldStartLoad;
If loading content into a UIWebView and you want to use Safari to open links, doing it the way described above will get you a blank page. You need to check the NavigationType.
private bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navType)
{
if (navType == UIWebViewNavigationType.LinkClicked)
{
UIApplication.SharedApplication.OpenUrl(request.Url);
return false;
}
return true;
}
The easiest/simplest way to do it is to assign a delegate to the UIWebView's ShouldStartLoad property:
webView.ShouldStartLoad = (w, urlRequest, navigationType) => {
// Open the url in Safari here.
// The urlRequest parameter is of type NSUrlRequest, you can get the URL from it.
return false; //return true for urls you actually want your web view to load.
};
Make sure the delegate returns false, for the links you want to load in Safari, so that your UIWebView does not load the link.

Automated system for opening other website links in new window/tab

I have a website, in which when user clicks a link it opens up in the same window if it is of my website's page, else in new window if domain is different. But I am doing this manually like this:
Open Link
checkdomain() checks the domain name of the link and returns true if it's of my website else false. I used the code from [ HERE ] for this purpose.
My question is: Is there any efficient and client side way available for checking link domains and open up them in new windows/tab if of another website(domain)? Like a JavaScript solution will be better, but then again JavaScript can be disabled by user. So, is there any other solution? Even JS solution will be great. Ignoring the disabling by user.
Somewhere on the page, or in an external JS file:
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href")
&& anchor.getAttribute("rel")
&& anchor.getAttribute("rel").indexOf("external") >= 0)
anchor.target = "_blank";
}
}
window.onload = function() {
externalLinks();
};
Then, any external links just need to have rel="external" in the markup. For example:
Click here!
The main advantages of this approach is that you're not going to cause any validation errors, even with an XHTML Strict doctype. Users are also able to easily prevent links opening in new windows by simply disabling JS.
If you need the decision of external/internal to be made automatically (and client-side), you can alter the logic of externalLinks to base the decision on the href attribute rather than the rel attribute. Of course, if you've already got the external/internal logic functioning in your codebehind, I would recommend using that information to render the anchor with the appropriate semantics (with rel), rather than re-writing almost identical code in your client-side JS.
Try comparing your link url's host part (www.wrangle.in) with following in you function logic.
string currentURL = HttpContext.Current.Request.Url.Host;
I do not recommend to compare the name (i.e http or https), you can split using substring function.
For Client side
var homeURL = document.location.hostname;
$('a').each(function() {
if ( $(this+'[href*='+homeURL+']')) {
$(this).attr('target','_self');
}else{
$(this).attr('target','_blank');
} });
This link may help you to understand Url Parts.

Google map Api Share location issue in Firefox

How can I prevent Firefox from asking the user to share their location every time it is requested?
I am using the Google map api. Below is my code to share the location. In Firefox it always asks to share location with the popup below. This happens every time, whether I click on Share or Not Now.
Below is my code
<% if (!Page.IsPostBack)
{ %>
// opened the share location
if (navigator.geolocation)
{
try
{
navigator.geolocation.getCurrentPosition(onPositionUpdate);
}
catch (err)
{
alert(err);
}
}
else
{
alert("You location is not available. Please enter your location to continue!");
}
<%}%>
function onPositionUpdate(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
try
{
var latLng = new google.maps.LatLng(lat, lng);
if (marker == null)
{
alert("Sorry we are not able to update your location.");
}
else
{
setTimeout(function ()
{
marker.setPosition(latLng);
map.setCenter(latLng);
document.getElementById('ctl00_ContentPlaceHolderBody_latSel').value = lat;
document.getElementById('ctl00_ContentPlaceHolderBody_lngSel').value = lng;
geocodePosition(latLng);
}, 100);
}
}
catch (err)
{
alert(err);
}
}
This happens because you're using navigator.geolocation.getCurrentPosition.
Browsers have to ask users permission for sharing your geolocation. It depends of the settings of your browser. If you want to always share your geolocation, in firefox, just follow this link and go to the last paragraph.
Location-Aware Browsing is always opt-in in Firefox. No location information is ever sent without your permission. If you wish to disable the feature completely, please follow this set of steps:
In the URL bar, type about:config
Type geo.enabled
Double click on the geo.enabled preference
Location-Aware Browsing is now disabled
Most likely because your port number changes when you run your website on development server. Goto project properties -> Web -> Servers section: and set Specific Port instead of Auto-assign.
Because by default setting with webkit and opera browser's normally. For iOS it is necessary to use html5 with -webkit keyword in css some functions doesn't works in other browsers. Basically safari, chrome, opera is used in mobile devices and device features works fine with these.
Firefox browser is not a better option for mobile devices.

Accessing Response Packet from within C# code, using an existing instance of Web Browser

I am writing C# Coded UI Tests in Visual Studio 2010. To enhance the testing, I need to access all the responses coming back from the server. For instance, I am testing the Add New Member use case, if user’s attempt to add a new member fails, and the UI doesn’t show neither the success or failure massage, I want to be able to get more detail from the http response and show the appropriate respond to the tester.
My code first open an instance of
SHDocVw.ShellWindows allBrowsers = new SHDocVw.ShellWindows();
if (allBrowsers.Count > 1)
{
MessageBox.Show("Number active browsers = " + allBrowsers.Count + "." + " Please close all windows and try again...");
throw new Exception("Multiple IE Instances not allow ");
}
p = Process.Start("iexplore.exe", "http://bing/");
BrowserWindow win = new BrowserWindow();
current.SearchProperties[BrowserWindow.PropertyNames.Name] = "Bing";
if (p == null) throw new Exception("Could not launch IE");
Now, I need to somehow capture all the responses that server sends back to requests going out from the instance of win object?
I am not sure if there is any way to do with HttpContext or such.
To track responses from web server you need to setup your HTTP proxy that you can control from the tests. See How do I automate a web proxy in .NET for unit tests (including set up and tear down)? , search for something like "fiddler automation unit test" for more articles.

Categories

Resources