I want to do web browser bot. It should click link and wait 25 seconds.
private void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // This is only way It worked for me.
{
if (webBrowserMain.Url.AbsoluteUri == #"http://www.clix-cents.com/pages/clickads")
{
Regex regAddId = new Regex("onclick=\\'openad\\(\"([\\d\\w]+)\"\\);", RegexOptions.IgnoreCase); // Find link and click it.
if (regAddId.IsMatch(webBrowserMain.DocumentText))
{
string AddId = regAddId.Match(webBrowserMain.DocumentText).Groups[1].ToString();
webBrowserMain.Navigate(#"http://www.clix-cents.com/pages/clickads?h=" + AddId);
}
}
else if (webBrowserMain.Url.AbsoluteUri.Contains("http://www.clix-cents.com/pages/clickads?h=")) // up to there everything is ok. But problem starts here.
{
Thread.Sleep(25000); // It pouses whole thread and browser, so timer in browser is not counting down.
Regex regCaptchaCode = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase);
if (regCaptchaCode.IsMatch(webBrowserMain.DocumentText))
{
pictureBox1.ImageLocation = #"http://www.clix-cents.com/pages/captcha?t=c&s=" + regCaptchaCode.Match(webBrowserMain.DocumentText).ToString();
}
}
}
How to write bot for something like that? I have no idea.
Don't reinvent the wheel - there's already solutions out there like WatiN which is mainly used for testing but is also suitable for automation.
Code example from the WatiN page:
[Test]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
}
}
You could probably use a timer. Eg:
private Timer t = new Timer();
private string nextUrl = "";
private void buttonStart_Click(object sender, EventArgs e)
{
t.Interval = 2500;
t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(nextUrl))
webBrowser1.Navigate(nextUrl);
else
{
Regex regCaptchaCode = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase);
if (regCaptchaCode.IsMatch(webBrowserMain.DocumentText))
{
pictureBox1.ImageLocation = #"http://www.clix-cents.com/pages/captcha?t=c&s=" + regCaptchaCode.Match(webBrowserMain.DocumentText).ToString();
}
}
}
private void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // This is only way It worked for me.
{
if (webBrowserMain.Url.AbsoluteUri == #"http://www.clix-cents.com/pages/clickads")
{
Regex regAddId = new Regex("onclick=\\'openad\\(\"([\\d\\w]+)\"\\);", RegexOptions.IgnoreCase); // Find link and click it.
if (regAddId.IsMatch(webBrowserMain.DocumentText))
{
string AddId = regAddId.Match(webBrowserMain.DocumentText).Groups[1].ToString();
nextUrl = #"http://www.clix-cents.com/pages/clickads?h=" + AddId;
t.Start();
}
}
else if (webBrowserMain.Url.AbsoluteUri.Contains("http://www.clix-cents.com/pages/clickads?h=")) // up to there everything is ok. But problem starts here.
{
nextUrl = "";
t.Start();
}
}
The actual implementation will depend on the actual data on the site and how you want to use it. If all the links are on one page and you want to open each one, you could parse for all the links and store into a list. Then start the timer. At each Tick, you could open 1 item.
Related
I'm having this issue for a while now on some machines, when the user runs the application all the buttons, images, menu items, almost everything goes blank.
My first thought was: I have a separate thread using BackgroundWorker updating a StatusBar and I've read that this can cause issues to form rendering.
I found an article (it's in portuguese, since I'm a Brazilian) that explains this is a issue caused by a security plugin installed by our banks called Warsaw. One of the solutions was to contact the developers to have them analyze your software so the plugin will work correctly. I've done this and I'm waiting for their response.
The other solution is to sign our assembiles so the plugin may recognize as a trusted software, this is good but not free of charge unfortunately.
Now, here's an example of my application looks like when it's launched with this issue:
A form with a GridView
The code for the separate thread as mentioned above:
int countAlerta = 0;
int countAlertaRFRP = 0;
int countAlertaAditivo = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
backgroundWorker1.RunWorkerAsync();
else
{
alertaToolStripStatusLabel.Text = "Continuando a verificação...";
alertaToolStripStatusLabel.IsLink = false;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(0);
timer1.Enabled = false;
lock (new object())
{
countAlerta = new BLL.AlertasBLL().CountRVSRAS();
countAlertaRFRP = new BLL.AlertasBLL().CountRFRP();
countAlertaAditivo = new BLL.AlertasBLL().CountAditivos();
}
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
alertaToolStripStatusLabel.Text = "Verificando...";
alertaToolStripStatusLabel.IsLink = false;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (countAlerta + countAlertaAditivo + countAlertaRFRP > 0)
{
alertaToolStripStatusLabel.Text = "ALERTA: Verifique!!!";
alertaToolStripStatusLabel.IsLink = true;
alertaToolStripStatusLabel.Font = new Font(alertaToolStripStatusLabel.Font, FontStyle.Bold);
}
else
{
alertaToolStripStatusLabel.Text = "Não existem alertas";
alertaToolStripStatusLabel.IsLink = false;
}
timer1.Enabled = true;
}
I've got this annoying problem which I can't track down where it goes wrong.
I'm creating a Windows Media Player in code and I'm trying to loop a video... It loops, but only once...
So it plays the video, and once more. And then it just stop and shows the end of the video. So it seems as if it loops only once.
This is the code I have:
try {
wmPlayer = new AxWMPLib.AxWindowsMediaPlayer();
wmPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit();
wmPlayer.Name = "wmPlayer";
wmPlayer.Enabled = true;
wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
mainForm.Controls.Add(wmPlayer);
((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit();
wmPlayer.uiMode = "none";
if(kind == "idle") {
IdleVideo(name);
}
}
catch { }
}
private static void IdleVideo(string name) {
System.Diagnostics.Debug.WriteLine("Video called once");
wmPlayer.URL = #"C:\ProjectSilver\assets\RadarDetectie\idle\" + name + "_idlescreen_movie.ogv";
Debug.WriteLine(wmPlayer.URL);
wmPlayer.settings.setMode("loop", true);
wmPlayer.Ctlcontrols.play();
}
So I hope you guys can help, why doesn't it keep playing?
just use
private void Form1_Load(object sender, EventArgs e)
{
// give the path of your video here
axWindowsMediaPlayer1.URL = "Path of your video";
// this line will automatically start your video
axWindowsMediaPlayer1.settings.autoStart = true;
//here the system will automatially create a thread and will keep on
running your video...
axWindowsMediaPlayer1.settings.setMode("loop", true);
}
Add an event handler for the PlayStateChange event:
wmPlayer.PlayStateChange += wmPlayer_PlayStateChange;
Then in the event handler check if e.newState==8 which means media ended:
AxWMPLib.AxWindowsMediaPlayer wmPlayer;
private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(e.newState==8) // MediaEnded
// call function to play the video again
}
For play states, check this:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd562460%28v=vs.85%29.aspx
Edit:
I don't know what you do with kind, or where the first part of your code is defined, but this worked for me:
AxWMPLib.AxWindowsMediaPlayer wmPlayer;
private void button2_Click(object sender, EventArgs e)
{
wmPlayer = new AxWMPLib.AxWindowsMediaPlayer();
wmPlayer.CreateControl();
wmPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit();
wmPlayer.Name = "wmPlayer";
wmPlayer.Enabled = true;
wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
this.Controls.Add(wmPlayer);
((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit();
wmPlayer.uiMode = "none";
wmPlayer.URL = #"C:\...";
wmPlayer.settings.setMode("loop", true);
wmPlayer.Ctlcontrols.play();
}
I have a situation which occurs in WebBrowser with C#.
I am trying to do downloader through a site However , when i click first time, it doesn't work but if I click second times it works.
How can i solve this problem .
Sincerely.
Codes :
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementById("youtube-url").SetAttribute("value", textBox1.Text);
webBrowser1.Document.GetElementById("submit").InvokeMember("click");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
label3.Text = "Video Alındı , indirme işleminin hazır olması bekleniyor";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("a");
String link = "";
foreach (HtmlElement el in col)
{
if (el.InnerText == "Download")
{
link = el.GetAttribute("href");
Download(link);
label3.Text = "Video indiriliyor";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("http://www.youtube-mp3.org/tr");
}
void Download(String link)
{
WebClient downloader = new WebClient();
downloader.DownloadFileAsync(new Uri(link),#"D:\a.mp3");
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = "Video İndiriliyor : " + progressBar1.Value + "%";
if (progressBar1.Value == 100)
label3.Text = "Video İndirildi";
}
You're blocking yourself from investigating what the problem is. It's never a good idea to disable script errors for WebBrowser control (as you do with ScriptErrorsSuppressed = true), unless you handle them internally in your host app. Do the following:
enable script errors (ScriptErrorsSuppressed = false);
enable script debugging for all applications;
implement WebBrowser Feature Control (FEATURE_BROWSER_EMULATION), so the web page is getting the same (or close) experience and HTML features as with full-featured IE browser.
Then, hopefully, you can find out what's going wrong when you're simulating a button click, and debug it.
Having a lot of trouble with this. I'm working on a large project, so there's only a few classes I'm interested in and working on. Basically, these are forms - one is a main editor where a user edits details and the other is used to assign a pin number. In the main editor form, if the user has a pin, they can choose to edit this pin. Here's where my problem lies - if I edit the pin, what I'm doing in the code is deleting the old pin and adding the new one. However, the database doesn't update until AFTER the editor form is closed. Therefore, I'd like to call the method that does change the database on the OKButton click, if I could. The problem I'm facing is I don't know how.
Here is the DB code, we'll say the class is called DetailsConn:
public string editPin(int driverID)
{
if (SchemaChecker.PINAvailable())
{
string sql = "EditPIN";
using (SqlCommand cmd = new SqlCommand(sql, base.connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Remove("#nDriverID");
cmd.Parameters.AddWithValue("#nDriverID", driverID);
cmd.Parameters.Remove("#nPIN");
SqlParameter pinParameter = cmd.Parameters.Add("#nPIN", SqlDbType.Char);
pinParameter.Direction = ParameterDirection.Output;
pinParameter.Size = 32;
cmd.ExecuteNonQuery();
return pinParameter.Value.ToString();
}
}
return "";
}
Here's the code for my edit:
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.listViewDriverTags.SelectedItems.Count > 0)
{
ListViewItem lvi = this.listViewDriverTags.SelectedItems[0];
DriverTag driverTag = lvi.Tag as DriverTag;
else if (blahTag.blahType == 2)
{
buttonAssignPIN_Click(sender, e);
}
//message stuff and dialog boxes with localization info
if (dr == DialogResult.Yes)
{
this.listViewDriverTags.Items.Remove(lvi);
if (Tag.id != -1)
{
TagsToBeDeleted.Add(driverTag);
}
}
if (dr == DialogResult.No)
{
this.listViewTags.Items.Clear();
this.listViewTags.Items.Add(lvi);
}
}
}
Here's my buttonAssignPIN stuff:
private void buttonAssignPIN_Click(object sender, EventArgs e)
{
using (AssignPINForm form = new AssignPINForm())
{
if (form.ShowDialog(this) == DialogResult.OK)
{
DriverTag PIN = DriverTag.GetNewPIN(form.DriverTag);
ListViewItem lvi = this.listViewTags.Items.Add(PIN.driverTag);
lvi.SubItems.Add(this.TagTypes[PIN.TagType]);
lvi.Tag = PIN;
}
}
}
And finally, here's my AssignPINForm code:
public partial class AssignPINForm : Form
{
public AssignPINForm()
{
InitializeComponent();
this.buttonOK.Click += new EventHandler(buttonOK_Click);
this.buttonCancel.Click += new EventHandler(buttonCancel_Click);
this.buttonOK.Enabled = false;
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"^[0-9]{4,20}$";
Regex regex = new Regex(pattern);
buttonOK.Enabled = regex.IsMatch(textBoxPin.Text);
};
LoadStrings();
}
public void LoadStrings()
{
//stome stuff
}
public string DriverTag
{
get { return this.textBoxPin.Text; }
set { this.textBoxPin.Text = value; }
}
private void buttonOK_Click(object sender, EventArgs e)
{
}
private void buttonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void AssignPINForm_Load(object sender, EventArgs e)
{
}
}
I know it's kind of all over the place but I've provided everything I think is relevant. The middle two snippets are in the same class too, and the DB stuff is the same solution but a different project. I'd be grateful if someone can decipher what I'm after and help me out, it's the only thing I have left to do on this particular bit!
Thanks!
Not sure I fully got what you're after and I agree with some of the comments that this isn't the best of practice but I guess what you're after is to update the buttonOK_Click method to something like this:
private void buttonOK_Click(object sender, EventArgs e)
{
using(DetailsConn connection = new DetailsConn())
{
int driver = -1;
if(int.TryParse(this.DriverTag, out driver)) {
connection.editPin(driver);
}
}
}
Also, you may want to remove any other possible references to the editPin() function.
I actually figured out that even if I got that working correctly, it wasn't going to solve my problem. I've had to call a new procedure and declare that in the database schema - basically it was a lot more complicated than what I was giving it credit for. Thanks for the responses nonetheless.
I have a for loop and inside there is a navigate method for a browser. and it's suppose to load diffrent sites, but the problem is that it will start to load 1 site and before it will load it, it'll load another site. so I need to like pause it until it's completed.
I started to write an event to when the ProgressChanged event is at 100%.. than I figured I don't have any idea what to do next but I think it's a start.
Please help, Thanks!
Edit: I am using Forms as Roland said.
I assume you are doing windows forms programming. The event you want is DocumentCompleted Here's an example:
public Uri MyURI { get; set; }
public Form1()
{
InitializeComponent();
MyURI = new Uri("http://stackoverflow.com");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.Url = MyURI;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(e.Url == MyURI)
MessageBox.Show("Page Loaded");
}
For a list of URIs it's straight forward.
public int CurrentIndex = 0;
List<Uri> Uris;
public Form1()
{
InitializeComponent();
Uris = new List<Uri> { new Uri("http://stackoverflow.com"), new Uri("http://google.com/") };
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.Url = Uris[CurrentIndex];
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = (WebBrowser)sender;
if (e.Url == Uris[CurrentIndex])
{
CurrentIndex++;
if (CurrentIndex < Uris.Count)
{
browser.Url = Uris[CurrentIndex];
}
}
}