Winforms Webbrowser control URL Validation - c#

I am trying to validate a winform web browser control url when a button is clicked. I would like to see if the web browser's current url matches a certain url. When I try to run this code the program freezes
private void button_Click(object sender, EventArgs e)
{
// Check to see if web browser is at URL
if (webBrowser1.Url.ToString != "www.google.com" || webBrowser1.Url.ToString == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else {
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}

Here you go.
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Url = new Uri("https://www.google.ca");
// Check to see if web browser is at URL
if (webBrowser1.Url != null)
{
if (webBrowser1.Url.ToString() != "https://www.google.com" || webBrowser1.Url.ToString() == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else
{
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
}
1) Please use the schema with the URL.
2) Use ToString() as a function.

Related

C# Wait for Web Page to Load Before Scraping

I am trying to make a Windows Forms app that logs in another web application, navigates for a few steps (clicks) until it reaches a specific page and then scrape some info (names and addresses).
The problem is that I am using the DocumentCompletedEventHandler in order to have a page loaded before I execute the code for navigating to the next page (in order to reach the final web page).
When it fires, DocumentCompletedEventHandler fires multiple times.
When I reach the loggin page, it enters the credentials and then the message "Page loaded!" appears multiple times.
I press enter, it appears again.
Then it navigates to the next page and with that new page I have the same problem.
how can I make DocumentCompletedEventHandler to fire only once and not multiple times?
private void loadEvent(object sender, WebBrowserDocumentCompletedEventArgs e)
{
MessageBox.Show("Page loaded!");
}
private void loadLogin(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var inputElements = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement i in inputElements)
{
if (i.GetAttribute("name").Equals("utilizator"))
{
i.InnerText = textBox1.Text;
}
if (i.GetAttribute("name").Equals("parola"))
{
i.Focus();
i.InnerText = textBox2.Text;
}
}
var buttonElements = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement b in buttonElements)
{
if (b.GetAttribute("name").Equals("Intra"))
{
b.InvokeMember("Click");
}
}
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(loadEvent);
var inputElements1 = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement i1 in inputElements1)
{
if (i1.GetAttribute("id").Equals("headerqstext"))
{
i1.Focus();
i1.InnerText = textBox3.Text;
}
}
var buttonElements1 = webBrowser1.Document.GetElementsByTagName("button");
foreach (HtmlElement b1 in buttonElements1)
{
if (b1.GetAttribute("title").Equals("Caută"))
{
b1.InvokeMember("Click");
}
}
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(loadEvent);
}
private void Button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://10.1.104.23/ecris_cdms/");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(loadLogin);
}
}
}
try this :)
Uri last = null;
private void CompleteResponse(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!(last != null && last != e.Url))
return;
//your code here
}

Cookies viewstate are not maintaining in AjaxControlToolkit

I have cookies and viewstate in below control .
This ajax Control is used to upload multiple file images.
protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
int userid = 25;
DAL_Cart objdalcart = new DAL_Cart();
if (Viewstate["Imagestringname"] == null)
{
objdalcart.InsertTempImage(userid, ImageName, 1);
}
else
{
objdalcart.InsertTempImage(userid, ImageName, 0);
}
Response.Cookies["JewelleryUserCookiesUserId"].Value = Convert.ToString(userid);
Response.Cookies["JewelleryUserCookiesUserId"].Expires = DateTime.Now.AddYears(1);
Viewstate["Imagestringname"] = ImageName + ",";
}
The issue is when I try to retrive view state value or Cookies value on different click event of button in same page I am not able to retrive the value
protected void lnkcheckout_Click(object sender, EventArgs e)
{
if (Request.Cookies["JewelleryUserCookiesUserId"] == null || Request.Cookies["JewelleryUserCookiesUserId"].Value == "")
{
}
if (Viewstate["Imagestringname"] != null)
{}
}
For both the case it is going in if condition. for viewstate I have placed Enableviewstate=true on master page .Any idea why?
Review
Want ajax multiple file upload on my button click event
var c = new HttpCookie("JewelleryUserCookiesUserId");
c.Value = Convert.ToString(userid);
c.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(c);
Just note: this is insecure. the client can manipualte the cookie...

How to set website theme to all webpages using a drop down list?

I am trying to use a drop down list on my homepage to select and set the theme for all webpages. It sets it for the homepage but when I go to any other page it has no theme. This is my code for my homepage:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string selectedTheme = Page.Theme;
HttpCookie userSelectedTheme =
Request.Cookies.Get("UserSelectedTheme");
if (userSelectedTheme != null)
{
selectedTheme = userSelectedTheme.Value;
}
if (!string.IsNullOrEmpty(selectedTheme) &&
ddlSetTheme.Items.FindByValue(selectedTheme) != null)
{
ddlSetTheme.Items.FindByValue(selectedTheme).Selected =
true;
}
}
}
protected void ddlSetTheme_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie userSelectedTheme = new
HttpCookie("UserSelectedTheme");
userSelectedTheme.Expires = DateTime.Now.AddMonths(6);
userSelectedTheme.Value = ddlSetTheme.SelectedValue;
Response.Cookies.Add(userSelectedTheme);
Response.Redirect(Request.Url.ToString());
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
I am thinking that the code I have is only sufficient to apply the theme to one page, so how do I apply it to all pages?
By default, your HttpCookie's scope is the page you're on.
If you want it to be the entire domain, you need to set the Path to be the entire site, probably like this:
userSelectedTheme.Path = "/";
More info:
http://msdn.microsoft.com/en-us/library/system.web.httpcookie.path(v=vs.110).aspx
All I had to do was put the preinit code in the code files of the other pages.

saving picture after 5 seconds when a linklabel clicked

it is little bit hard to solve.. :D first you should solve my english :D :D
i want save a webbrowser snapshot like a this placement
//first : user clicks a linklabel
//
after : program navigates my browser
//
last : 5 seconds later program will takes snapshot of webbrowser.
i have this code for this.but..
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(linkLabel1.Text);
///how can i set after 5 seconds take snapshot
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb1.png", ImageFormat.Png);
}
sorry for bad english :( i cannot explain more detailed.
edit:
i will try explain more detailed...
here is my new tab function of my web browser and i want take favorites screenshot.after when user open new tab ,user will see favorites with small photo...
so, if favorite doesnt have any pic,it will be first time.when user click to the link.it will navigates to favorite and then when document completed,it will take screenshot..thats all
What I can comprehend from your post and comments, is that you have six LinkLabels (named linkLabel1 to linkLabel6). When the user clicks any of the links, your WebKitBrowser control has to navigate to the URL (which is the text of the linklabel) and when the document is loaded, it has to take automatically a screenshot.
Now, as you would like to do all the same with the different linklabels, you should only create one event handler to handle the clicks of the different linklabels. You can just attach the _LinkClicked() event to any of the linklabels. You'll also have to define in your class some private field that will contain the LinkLabel that was last clicked on.
private LinkLabel _lastClickedLinkLabel = null;
private void linkLabelX_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Cast the sender to a LinkLabel object as you want to know which LinkLabel
// was clicked on
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}
Now as you want to take the screenshot after the page is loaded, you'll have to create the DocumentCompleted event. (Don't forget to attach it to your tabControl!)
private void tabControl1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Save the screenshot
// you might want to determine the filename dynamically, otherwise the file will be overwritten
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb1.png", ImageFormat.Png);
if (_lastClickedLinkLabel != null)
{
// Do something here based upon the _lastClickedLinkLabel
}
}
Note that I don't have actual experience with that exact control, I just used a search engine to find all information.
i did this below and that works i solved my problem but,last thing i cannot change picture while my application is working..
when document completed,,.......
void Form1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (_lastClickedLinkLabel.Text == linkLabel1.Text)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Dispose();
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb1.png", ImageFormat.Png);
// Do something here based upon the _lastClickedLinkLabel
}
if (_lastClickedLinkLabel.Text == linkLabel2.Text)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb2.png", ImageFormat.Png);
// Do something here based upon the _lastClickedLinkLabel
}
if (_lastClickedLinkLabel.Text == linkLabel3.Text)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb3.png", ImageFormat.Png);
// Do something here based upon the _lastClickedLinkLabel
}
if (_lastClickedLinkLabel.Text == linkLabel4.Text)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb4.png", ImageFormat.Png);
// Do something here based upon the _lastClickedLinkLabel
}
if (_lastClickedLinkLabel.Text == linkLabel5.Text)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb5.png", ImageFormat.Png);
// Do something here based upon the _lastClickedLinkLabel
}
if (_lastClickedLinkLabel.Text == linkLabel6.Text)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).PageScreenshot.Save("thumb6.png", ImageFormat.Png);
// Do something here based upon the _lastClickedLinkLabel
}
}
and when links clicked,,.....
private LinkLabel _lastClickedLinkLabel = null;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}
private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}
private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}
private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}
private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var senderLinkLabel = sender as LinkLabel;
if (senderLinkLabel != null)
{
((WebKitBrowser)tabControl1.SelectedTab.Controls[0]).Navigate(senderLinkLabel.Text);
_lastClickedLinkLabel = senderLinkLabel;
}
}

Cancel opening link in browser

In my Windows phone application I use RichTextBox element
I have a hyperlink on it, and when user click on it there is a dialog: Do you want to open this link in exteranl browser. If user say no, external browser shouldn't be opened. I cancel navigation but in any case - external browser opens. How can I cancel opening link in browser?
//Constructor
static Helper()
{
var phoneApplicationFrame = Application.Current.RootVisual as PhoneApplicationFrame;
if (Application.Current.RootVisual as PhoneApplicationFrame != null)
{
phoneApplicationFrame.Navigating += new NavigatingCancelEventHandler(NavigationService_Navigating);
}
}
link.Foreground = new SolidColorBrush(Colors.Blue);
link.MouseOverForeground = new SolidColorBrush(Colors.Blue);
link.TargetName = "_blank";
var linkText = new Run() { Text = linkDesc };
link.Inlines.Add(linkText);
link.Click += new RoutedEventHandler(NavidateTo);
private static void NavidateTo(object sender, RoutedEventArgs routedEventArgs)
{
if (MessageBox.Show(
Constants.BrowserNavigating,
"",
MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
{
StateManager.Set("ExternalBrowser", "true");
}
else
{
StateManager.Set("Browser", "true");
}
}
public static void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
{
var res = StateManager.Get("ExternalBrowser");
if (res != null)
{
StateManager.Remove("ExternalBrowser");
e.Cancel = true;
}
}
Rather than have the HyperlinkButton open the link itself, don't specify the NavigationUri but handle the Tap event yourself.
In the eventhandler ask the question and only open the browser if they say yes.
This will be much simpler than trying to cancel something that is already in progress.

Categories

Resources