Write Current URL To String C# - c#

This is what I am trying to do.
Windows Form App loads with web browser
Goes to a certain link
Checks to see if the url bar is empty, if not it takes the current url and writes to a string and then navigates to some other url.
I keep getting Cannot implicitly convert type 'System.Uri' to 'string'
and I have tried a few things but can't get my head around it.
string url;
try
{
if (webBrowser1.Url != null)
{
// url = webBrowser1.Url;
MessageBox.Show("Success!");
}
else
{
MessageBox.Show(":(!");
}
}
catch
{
MessageBox.Show("Something Screwed Up");
}
Now at this point I get :( when I comment out the error. This is on form1.cs - should I be doing this on program.cs? It seems like the object may not be created a the point when I check but I have no idea. By default the form loads with a URL pre-loaded.

webBrowser1.Url is URI object
url is String object
it tells you those are diffrent types and there no implicit convertion
url = webBrowser1.Url.ToString();
see great article:
http://msdn.microsoft.com/en-us/library/ms173105.aspx

Related

C# Get Values from two different websites

I am using HTMLElementCollection, HtmlElement to iterate through a website and using Get/Set attributes of a website HTML and returning it to a ListView. Is it possible to get values from website a and website b to return it to the ListView?
HtmlElementCollection oCol1 = oDoc.Body.GetElementsByTagName("input");
foreach (HtmlElement oElement in oCol1)
{
if (oElement.GetAttribute("id").ToString() == "search")
{
oElement.SetAttribute("value", m_sPartNbr);
}
if (oElement.GetAttribute("id").ToString() == "submit")
{
oElement.InvokeMember("click");
}
}
HtmlElementCollection oCol1 = oDoc.Body.GetElementsByTagName("tr");
foreach (HtmlElement oElement1 in oCol1)
{
if (oElement1.GetAttribute("data-mpn").ToString() == m_sPartNbr.ToUpper())
{
HtmlElementCollection oCol2 = oElement1.GetElementsByTagName("td");
foreach (HtmlElement oElement2 in oCol2)
{
if (oElement2 != null)
{
if (oElement2.InnerText != null)
{
if (oElement2.InnerText.StartsWith("$"))
{
string sPrice = oElement2.InnerText.Replace("$", "").Trim();
double dblPrice = double.Parse(sPrice);
if (dblPrice > 0)
m_dblPrices.Add(dblPrice);
}
}
}
}
}
}
As one of the comments mentioned the better approach would be to use HttpWebRequest to send a get request to www.bestbuy.com or whatever site. What it returns is the full HTML code (what you see) which you can then parse through. This kind of approach keeps you from seinding too many requests and getting blacklisted. If you need to click a button or type in a text field its best to mimic human input to avoid being blacklisted also. I would suggest injecting a simple javascript into the page header or body and execute it from the app to send a 'onClick' event from the button (which would then reply with a new page to parse or display) or to modify the text property of something.
this example is in c++/cx but it originally came from a c# example. the script sets the username and password text fields then clicks the login button:
String^ script = "document.GetElementById('username-text').value='myUserName';document.getElementById('password-txt').value='myPassword';document.getElementById('btn-go').click();";
auto args = ref new Platform::Collections::Vector<Platform::String^>();
args->Append(script);
create_task(wv->InvokeScriptAsync("eval", args)).then([this](Platform::String^ response){
//LOGIN COMPLETE
});
//notes: wv = webview
EDIT:
as pointed out the absolute best approach would be to get/request an api. I was surprised to see that site mason pointed out for bestbuy developers. Personally I have only tried to work with auto part stores who either laugh while saying I can't afford it or have no idea what I'm asking for and hang up (when calling corporate).
EDIT 2: in my code the site used was autozone. I had to use chrome developer tools (f12) to get the names of the username, password, and button name. From the developer tools you can also watch what is sent from your computer to the site/server. This allows you to recreate everything and mimic javascript input and actions using post/get with HttpWebRequest.

How can I fix improper Neutralization of Script-Related HTML Tags in a Web Page?

We recently run VeraCode and it failed the following method:
static public void WriteTargetAttribute(HtmlTextWriter writer, string targetValue)
{
if ((writer != null) && (!String.IsNullOrEmpty(targetValue)))
{
if (targetValue.Equals("_blank", StringComparison.OrdinalIgnoreCase))
{
string js = "window.open(this.href, '_blank', ''); return false;";
writer.WriteAttribute("onclick", js);
writer.WriteAttribute("onkeypress", js);
}
else
{
writer.WriteAttribute("target", targetValue);
}
}
}
The VeraCode fails on the last line: " writer.WriteAttribute("target", targetValue);"
What can I do to fix it?
Thank's
The problem is that 'targetValue' is being passed down to your method, but there is no neutralization of this before it gets used - the string gets uses 'as-is' so could contain scripts that cause harm. There is a good description explaining this and why it is a problem: http://www.veracode.com/images/pdf/top5mostprevalent.pdf
Because 'targetValue' will get rendered to the web page, someone could enter script which will get rendered on the final page. If 'targetValue' was a naughty snippet of code you are exposing yourself and your users to a security vulnerability.
Have a read of the tips on this cheat sheet: https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
You should be able to use HtmlEncode to make this safe HttpUtility.HtmlEncode(targetValue);
writer.WriteAttribute("target", System.web.HttpUtility.HtmlEncode(targetValue));

Get the Control on a page by passing URL? Also get the current page URL?

My Requirement: I want to know which page I am currently in so that if any test fails I want to pass the current page's URL to a method and get the home button link. Ultimately navigating to the home link in case of any exception.
Is there a way to achieve it ?
The URL should be in the address bar of the browser, just read it out of there.
One way of reading out the value is to record an assertion on the value in the address bar, then copy the part of the code in the recorded assertion method that accesses the value.
Another way is to use the cross-hairs tool to select the address area, then (click the double-chevron icon to open the left hand pane and) add the UI control for the selected area. Then access the value.
This will return the top Browser:
BrowserWindow bw = null;
try
{
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
var browser = new BrowserWindow() /*{ TechnologyName = "MSAA" }*/;
PropertyExpressionCollection f = new PropertyExpressionCollection();
f.Add("TechnologyName", "MSAA");
f.Add("ClassName", "IEFrame");
f.Add("ControlType", "Window");
browser.SearchProperties.AddRange(f);
UITestControlCollection coll = browser.FindMatchingControls();
// get top of browser stack
foreach (BrowserWindow win in coll)
{
bw = win;
break;
}
String url = bw.Uri.ToString(); //this is the value you want to save
}
catch (Exception e)
{
throw new Exception("Exception getting active (top) browser: - ------" + e.Message);
}
finally
{
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
}

Pass the file name of a saved file from one class to another

I'll do my best to explain.
My program takes screen shots which the user can save to their desktop or pass to a media server.
However, to pass to the server I first must have the file location of the image they are saving and so they must first save the file using the save file dialog and I store the location of that in a string which triggers a bool to say that the image has been save. The code looks like this to pass the file to server:
// sfd is the safe file dialog
UploadToServer.HttpUploadFile(Settings.Default.ServerAddress , sfd.FileName.ToString(), "file", "image/jpeg", nvc);
I tried to store the sfd in the following way so I could pass this call to another class:
public String SaveImageLocation
{
get { return sfd.FileName.ToString(); }
set { sfd.FileName.ToString() = value; }
}
But I get the following error:
Error 1 The left-hand side of an assignment must be a variable, property or indexer
What I'm trying to achieve is to take the file upload code and move it to another class. can someone help me with this error?
This is a method/function (call).
ToString()
You cannot assign a method/function (call) to a value..
.ToString() = value;
Try
public String SaveImageLocation
{
get { return sfd.FileName.ToString(); }
set { sfd.FileName = value; }
}
Please note you have not indicated what type FileName is, so it still may not work.

Setting Value of an Input Tag in WebBrowser Control

I am attempting to help a user log into their account using a custom WebBrowser control. I am trying to set the value of an input tag to the players username using the WebBrowser's InvokeScript function. However, my current solution is doing nothing but rendering a blank white page.
My current code looks like this (web is the name for my WebBrowser control):
web.Navigate(CurrentURL, null, #"<script type='text/javascript'>
function SetPlayerData(input) {
username.value = input;
return true;
}
</script>");
web.Navigated += (o, e) =>
{
web.IsScriptEnabled = true;
web.InvokeScript("SetPlayerData", #"test");
};
As mentioned, this does not work right now. I am attempting to do this on Windows Phone so a number of the example's I have found here and in other places will not work as I do not have access to the same functions.
How would I perform this successfully?
EDIT: Perhaps I was not clear, but I am working with Windows Phone, which has a limited API available meaning I do not have access to the Document property and a number of other functions. I do have access to InvokeScript, but not much more.
webBrowser1.Document.GetElementById("navbar_username").InnerText ="Tester";
webBrowser1.Document.GetElementById("navbar_password").InnerText = "xxxxxxxxxxx";
foreach (HtmlElement HtmlElement1 in webBrowser1.Document.Body.All)
{
if (HtmlElement1.GetAttribute("value") == "Log in")
{
HtmlElement1.InvokeMember("click");
break;
}
}
you may find more here : http://deltahacker.gr/2011/08/15/ftiakste-to-diko-sas-robot/
It's been along time since this question is posted but I think I'll post an answer to this so that it will help some one who came across the same situation
try
{
webBrowser1.Document.GetElementById("navbar_username").SetAttribute("value", "your user");
webBrowser1.Document.GetElementById("navbar_password").SetAttribute("value", "your pass");
webBrowser1.Document.GetElementById("Log in").InvokeMember("click");
}
catch { }

Categories