I'm trying to make a small program that loads a webpage into the form submits the form on the
page automaticlly - this is apart of a larger project but i cant get this part work properly.
This web page offer Court cases results when the correct case number and date (mm-yy) is typed in and submitted.
I created a simple webBrowser in a form and called it webBrowser1.
And here is my Form.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
firstStep();
// secondStep();
}
private void firstStep()
{
webBrowser1.Url = new System.Uri("http://www.court.gov.il/NGCS.Web.Site/HomePage.aspx", System.UriKind.Absolute);
}
private void HandleRequest(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(HandleRequest);
HtmlElement caseNumber = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaCaseNumberTextBoxHT"];
HtmlElement caseDate = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaMonthYearTextBoxHT"];
caseNumber.Focus();
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(2)");
System.Windows.Forms.SendKeys.Send("(2)");
System.Windows.Forms.SendKeys.Send("(3)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("{TAB}");
System.Windows.Forms.SendKeys.Send("(0)");
System.Windows.Forms.SendKeys.Send("(3)");
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(0)");
HtmlElement inputTag = webBrowser1.Document.All["Header1_CaseLocatorHeaderUC2_SearchHeaderCaseButton"];
inputTag.InvokeMember("Click");
}
}
}
As you can see - I'm typing the values as shown in the picture and then invoking a click on the button that submits this form, but it doesn't work!? this webpage is very tricky and uses scripts that validate the input and then sets the correct values to be submits and by the way he works only on IE < 10....
any idea please?
EDIT:
Its working now - I am firing the invoke twice but I don't have an idea what was the problem.
Now the new problem is that I added a button click that fires the process btnGet_Click and when triggering this function I get an error - it seems that DetailsTag is set to null... but when I un-comment the function in the public Form1() its working fine and loading the website as it should.
What is the difference between calling the the function firstStep() in the button click / public form?
why I receive this error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private readonly object lock_ = new object();
HtmlElement caseNumber;
HtmlElement caseDate;
HtmlElement DetailsTag;
int checks = 1;
public Form1()
{
InitializeComponent();
//webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
//firstStep();
}
private void firstStep()
{
webBrowser1.Url = new System.Uri("http://www.court.gov.il/NGCS.Web.Site/HomePage.aspx", System.UriKind.Absolute);
}
private void HandleRequest(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (checks < 1)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(HandleRequest);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetDetails);
}
caseNumber = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaCaseNumberTextBoxHT"];
caseDate = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaMonthYearTextBoxHT"];
if (caseNumber != null && caseDate != null)
{
caseNumber.Focus();
System.Windows.Forms.SendKeys.Send("(5)");
System.Windows.Forms.SendKeys.Send("(6)");
System.Windows.Forms.SendKeys.Send("(5)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("{TAB}");
System.Windows.Forms.SendKeys.Send("(0)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(3)");
checks = 0;
System.Windows.Forms.SendKeys.Send("{ENTER}");
}
else
{
MessageBox.Show("No such case - enter a new one");
}
}
private void GetDetails(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(GetDetails);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetResults);
DetailsTag = webBrowser1.Document.All["_ctl0_caseDetailsGrid_row1_ct6_Imagebutton1"];
if (DetailsTag != null)
{
DetailsTag.InvokeMember("Click");
}
else
{
MessageBox.Show("Error - try another case!");
}
}
private void GetResults(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(GetResults);
HtmlElement DetailsStatus = webBrowser1.Document.All["_ctl7_caseStatusIDlbl"];
HtmlElement DetailsCourt = webBrowser1.Document.All["_ctl7_courtIDlbl"];
HtmlElement DetailsType = webBrowser1.Document.All["_ctl7_caseTypeIDlbl"];
HtmlElement DetailsAmount = webBrowser1.Document.All["_ctl7_claimAmountlbl"];
HtmlElement DetailsPrev = webBrowser1.Document.All["_ctl7_privilegeIDlbl"];
txtAmount.Text = DetailsAmount.InnerText;
txtCount.Text = DetailsCourt.InnerText;
txtPrev.Text = DetailsPrev.InnerText;
txtStatus.Text = DetailsStatus.InnerText;
txtType.Text = DetailsType.InnerText;
}
public void btnGet_Click(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
firstStep();
}
}
}
As said via comment, your approach for populating the textboxes is not too orthodox and, actually, is not working on my computer. The usual proceeding is relying on the SetAttribute function. Your code would become:
caseNumber.SetAttribute("value", "12283");
caseDate.SetAttribute("value", "03-10");
If I do that and then I use your inputTag.InvokeMember("Click"), the form is submitted (at least, no popup appears and the browser is redirected to a new page).
Related
why can't I add a new item/object to my list in button (or combobox etc.) events? I mean, the events don't see my list if it's outside of the brackets...it's underlined in red... can you help me?
long story short: i want to add a new object by clicking the button
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
namespace Samochody
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Samochod> ListaSamochodow = new List<Samochod>();
comboBox1.DataSource = ListaSamochodow;
comboBox1.DisplayMember = "Marka";
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ListaSamochodow.Add(new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text)));
}
catch (Exception oException)
{
Console.WriteLine("Aplikacja wygenerowała następujący wyjątek: " + oException.Message);
}
}
I think you should instantiate your list globally and not under Form1_Load event.
that way it will be accessible all around your class (the window in this case).
This seems to work fine. You might need to set your textboxes to contain valid values when you start the form. also make sure that you make the list visible throughout your form1 class.
namespace Samochody
{
public partial class Form1 : Form
{
// make sure your list looks like this, created outside your functions.
List<Samochod> ListaSamochodow = new List<Samochod>();
public Form1()
{
InitializeComponent();
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
textBox1.Text = "string here";
textBox2.Text = "string here";
textBox3.Text = "100";
}
private void Form1_Load(object sender, EventArgs e)
{
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click_1(object sender, EventArgs e)
{
Samochod s = new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
ListaSamochodow.Add(s);
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using mshtml;
using System.Text.RegularExpressions;
namespace Extract_Images
{
public partial class Form1 : Form
{
private string[] linkstoextract;
private int numberoflinks;
private int currentLinkNumber = 0;
private string mainlink;
private WebClient client;
private WebBrowser webBrowser1;
private string htmlCode;
private bool pagesorimages = false;
public Form1()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
label1.Text = "Number of links: ";
mainlink = "http://www.test.com/";
numberoflinks = 13;
backgroundWorker1.RunWorkerAsync();
}
private void ProcessNextLink()
{
if (currentLinkNumber < numberoflinks)
{
currentLinkNumber++;
string linktonav = mainlink + "index"+currentLinkNumber.ToString() + ".html";
pagesorimages = false;
backgroundWorker1.ReportProgress(0,currentLinkNumber);
webBrowser1.Navigate(linktonav);
}
}
int count = 0;
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mshtml.HTMLDocument objHtmlDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
string pageSource = objHtmlDoc.documentElement.innerHTML;
List<string> links = new List<string>();
string[] hrefs = this.webBrowser1.Document.Links.Cast<HtmlElement>()
.Select(a => a.GetAttribute("href")).Where(h => h.Contains(".jpg")).ToArray();
foreach(string a in hrefs)
{
using (WebClient client = new WebClient())
{
client.DownloadFile(a, #"C:\Images\file" + count + ".jpg");
}
count ++;
pagesorimages = true;
backgroundWorker1.ReportProgress(0, count);
}
//ProcessNextLink();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ProcessNextLink();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (pagesorimages == false)
{
label1.Text = e.UserState.ToString();
}
if (pagesorimages == true)
{
label2.Text = e.UserState.ToString();
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
}
The exception is on the second ReportProgress:
backgroundWorker1.ReportProgress(0, count);
This operation has already had OperationCompleted called on it and further calls are illegal
What i want to do is to report first the current page number in this case it's 1 to label1.
And then to report the number of downloaded images in this page to label2.
Then to move to the next page with the method ProcessNextLink(); and again report the page number it should be 2 and then to report the number of images downloaded in page 2.
But i'm getting this exception already on the first page.
It was working fine without the backgroundworker in the event webBrowser1_DocumentCompleted i called ProcessNextLink(); in the bottom and it was working fine. But with the backgroundworker it's not working.
This is the link for the login:
Log In
If im trying to login manualy in the webbrowser it does nothing but open a popup message ask me if to close the window i click yes and nothing happen. In the regular chrome browser not in the webbrowser when i put in user name and password and click log in it also close the window of the log in automatic refresh the page and im logged in.
But through the webbroswer its never log in. Its not givinig any errors or exceptions just does nothing.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace Champinos
{
public partial class Form1 : Form
{
WebClient webc = new WebClient();
string url = "";
string username = "";
string password = "";
string commit = ""; //this matches the data from Tamper Data
private int timeElapsed;
private string newline1 = "";
private bool complete;
private int count;
public Form1()
{
InitializeComponent();
timeElapsed = 1;
label3.Visible = false;
label5.Visible = false;
complete = false;
count = 1;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
url = "http://www.tapuz.co.il/Common/SignInPage.aspx?backUrl=http://www.tapuz.co.il/Common/SignIn.aspx#loginDone=1";
username = "yasonikolados";
password = "ynnad1972";
commit = "Login";//"Sign+In";
label1.Text = "Completed";
string source = "";
source = webc.DownloadString("http://www.tapuz.co.il/forums2008/forumpage.aspx?forumid=393&r=1");
string start = "data-token=";
string end = " href";
int firstTag = source.IndexOf(start);
int lastTag = source.IndexOf(end, firstTag);
int startIndex = firstTag + start.Length + 1;
int endIndex = lastTag;
string authenticityToken = source.Substring(startIndex, endIndex - startIndex - 30);
webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted2;
string postData = string.Format(
"authenticity_token={2}&session" +
"[username_or_email]={0}&session[password]={1}&commit={3}",
username, password, authenticityToken, commit);
ASCIIEncoding enc = new ASCIIEncoding();
webBrowser1.Navigate("http://www.tapuz.co.il/Common/SignInPage.aspx?backUrl=http://www.tapuz.co.il/Common/SignIn.aspx#loginDone", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.Navigate("http://www.tapuz.co.il/forums2008/forumpage.aspx?forumid=393&r=1");
}
private void webBrowser1_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = sender as WebBrowser;
string response = b.DocumentText;
if (response.Contains("Sign out"))
{
MessageBox.Show("Login Successful");
}
}
}
}
It is because you are using webBrowser1.Navigate as the last call in your DocumentCompleted event handler. Since you added the webBrowser1_DocumentCompleted2 as the event handler for the DocumentCompleted event prior to the Navigate call, what is happening is that when the call to Navigate happens, it is immediately calling your DocumentCompleted2 function which is signing you out. Instant signin and signout.
If you want to confirm, place breakpoints at the first line of both the DocumentCompleted and DocumentCompleted2 functions and debug it.
Quick note - I am very new to c# so I apologize if this is stupid simple.
I am having a hard time trying to complete a simple c# task in a book.
Pseudocode-
Text box text = user input
if button one is clicked
replace all capital letters in the text box with an asterisk
else if button two is clicked
replace the asterisks with their original characters (back to normal)
Here is what I have so far
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new System.EventHandler(ClickedButton);
button2.Click += new System.EventHandler(ClickedButton);
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void ClickedButton(object sender, EventArgs e)
{
string orignalText = textBox1.Text;
if (sender == button1)
{
string replaced = Regex.Replace(orignalText, #"[A-Z]", "*");
textBox1.Text = (replaced);
}
else if (sender == button2)
{
textBox1.Text = (orignalText);
}
}
}
}
The problem is that button2 is showing the text with the asterisks. It should be showing (I want it to show) the original characters.
The originalText should be a class field instead of a local variable. Also you should not store a textbox's value in case if someone clicked on the button2. Try to replace your ClickedButton method with this:
string orignalText;
public void ClickedButton(object sender, EventArgs e)
{
if (sender == button1)
{
orignalText = textBox1.Text;
string replaced = Regex.Replace(orignalText, #"[A-Z]", "*");
textBox1.Text = replaced;
}
else if (sender == button2)
{
textBox1.Text = orignalText;
}
}
You have 2 issues. First, you're setting the originalText before knowing which button was pressed. Second, originalText is a local variable, so when you want to replace it back in, it won't contain the original text anymore.
You just need to globalize originaltext variable and move the line
string orignalText = textBox1.Text;
into the first if check.
try this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new System.EventHandler(ClickedButton);
button2.Click += new System.EventHandler(ClickedButton);
}
private void Form1_Load(object sender, EventArgs e)
{
}
string orignalText = null; //you should define this var outside of ClickedButton method to keep its value during button1/2 clicks
public void ClickedButton(object sender, EventArgs e)
{
if (sender == button1)
{
orignalText = textBox1.Text;
string replaced = Regex.Replace(orignalText, #"[A-Z]", "*");
textBox1.Text = replaced;
}
else if (sender == button2)
{
if (orignalText != null) textBox1.Text = orignalText;
}
}
}
}
I am new to c#. I have been trying to add values from my datagrid to mysql but in vain and i really need your help. The values are automatically generated after a time interval of 1 sec and i need to insert them to the mysql in the same time interval. Here are the codes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace BLIND_SHOPPING_SYSTEM
{
public partial class Form2 : Form
{
private DataTable m_TagDataTable = new DataTable("Tag List");
long passiveID = 0;
public Form2()
{
InitializeComponent();
this.m_TagDataTable.Columns.Add("TagID");
}
private void btn_GenerateID_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
public void timer1_Tick(object sender, EventArgs e)
{
if (passiveID < 10)
{
passiveID = passiveID + 1;
//listBox1.Items.Add(passiveID);
//this.m_TagDataTable.Columns.Add("TagID");
this.dataGridView1.DataSource = m_TagDataTable;
DataRow dr = m_TagDataTable.NewRow();
dr["TagID"] = passiveID;
m_TagDataTable.Rows.Add(dr);
}
else
// Application.Exit();
Console.ReadLine();
}
private void btn_Stop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
}
}
Please kindly help me.
You probably want to use a DataTableAdapter and specify the Update command, see here for some examples ;) http://msdn.microsoft.com/en-us/library/ms233819(v=vs.80).aspx