The below code is for searching files. The thing is that when I select a large folder (like C disk) program starts with some delay. I think I need to divide disk into smaller parts (folders) and run it on different threads, but I do not know how.
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.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Collections;
using System.Diagnostics;
namespace failu_paieska
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
FolderBrowserDialog Folder = new FolderBrowserDialog();
Stopwatch stopwatch = new Stopwatch();
static List<string> lstFilesFound = new List<string>();
int fileCount;
int fileCount1;
//string test;
private void Form1_Load(object sender, EventArgs e)
{
//label2.Text = Environment.ProcessorCount.ToString();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = Folder.ShowDialog();
textBox2.Text = Folder.SelectedPath.ToString();
}
private void IdetiIListbox()
{
foreach (string n in lstFilesFound.ToList())
{
stopwatch.Start();
if (Path.GetFileName(n).Contains(textBox1.Text.ToString()))
{
this.BeginInvoke(new MethodInvoker(() =>
{
listBox1.Items.Add(n);
//progressBar1.Value++;
}));
}
}
stopwatch.Stop();
int paieska = listBox1.Items.Count;
this.BeginInvoke(new MethodInvoker(() =>
{
textBox3.Text = Convert.ToString(stopwatch.Elapsed);
}));
}
public void Ieskoti1()
{
foreach (string ff in Directory.EnumerateFiles(textBox2.Text.ToString(), "*.*"))
{// Paima failus is pirmo katalogo
lstFilesFound.Add(ff);
fileCount1 = lstFilesFound.Count();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync(textBox2.Text.ToString());
}
}
static void DirSearch(string sDir)
{
foreach (string d in Directory.EnumerateDirectories(sDir))
{
try
{
lstFilesFound.Add(d);
//visoFailu += 1;
foreach (string f in Directory.EnumerateFiles(d, "*.*"))
{
//visoFailu += 1;
lstFilesFound.Add(f);
}
DirSearch(d);
}
catch (Exception ee)
{
}
continue;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label4.Text = (e.ProgressPercentage.ToString() + "%");
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//DirSearch(textBox2.Text.ToString());
Ieskoti1();
DirSearch(textBox2.Text.ToString());
// IdetiIListbox();
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(100);
}
}
private void backgroundWorker1_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
{
//DirSearch(textBox2.Text.ToString());
IdetiIListbox();
if (e.Cancelled == true)
{
MessageBox.Show("Cancelled!");
}
else if (e.Error != null)
{
MessageBox.Show("Error: " + e.Error.Message);
}
else
{
MessageBox.Show("Done!");
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
fileCount = Directory.GetFiles(textBox2.Text.ToString()).Length;
}
}
}
Related
I now learning backgroundWorker with Selenium and my goal is to integrate webdriver.Close(); and webDriver.Quit() on click button STOP, following code work, but when I try to integrate webDriver.Quit() with STOP button it shows me error, the goal is, when user click STOP, to webdriver close, thanks :)
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.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace WindowsFormsApp19
{
public partial class Form1 : Form
{
private object webDriver;
public Form1()
{
InitializeComponent();
}
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ChromeDriver webDriver = new ChromeDriver();
int sum = 0;
for (int i=1; i<=100; i++)
{
Thread.Sleep(100);
sum = sum + i;
backgroundWorker1.ReportProgress(i);
webDriver.Navigate().GoToUrl("https://www.google.com");
Thread.Sleep(50000);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
e.Result = sum;
}
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = e.ProgressPercentage.ToString() + "%";
}
public void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if( e.Cancelled)
{
label1.Text = "Operation stopped ";
}
else if (e.Error != null)
{
label1.Text = e.Error.ToString();
}
else
{
label1.Text = "100% Completed";
}
}
public void Startbutton_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
public void Stopbutton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
}
}
I am developing a graphical interface that reads variables from different sensors that arrive through the serial port, so far I have managed to read all the variables with a single form but now I want to have two forms.
The first form asks the user to choose the COM and confirms whether the connection was successful or not. Once the connection is successful, the second form is opened where the variables from the sensors will be shown in "labels", the readings sent from Arduino are read by the serial port and stored in an array:
data[0], data[1], data[2] etc...
This is the first form where Serialport1 is found and the data arrives through the serialPort1_DataReceived event:
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.IO.Ports;
using System.Media;
namespace AUTOCLAVES_GUI
{
public partial class GUI_AUTOCLAVES_GENERADOR_DE_VAPOR : Form
{
/*VARIABLES GLOBALES*/
string puerto_seleccionado;
public GUI_AUTOCLAVES_GENERADOR_DE_VAPOR()
{
InitializeComponent();
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private void Salir_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Minimizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void Maximizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
Maximizar.Visible = false;
Restaurar.Visible = true;
}
private void Restaurar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
Restaurar.Visible = false;
Maximizar.Visible = true;
}
private void MenuSideBar_Click(object sender, EventArgs e)
{
if (Sidebar.Width == 270)
{
Sidebar.Visible = false;
Sidebar.Width = 68;
SidebarWrapper.Width = 90;
LineaSidebar.Width = 68;
AnimacionSidebar.Show(Sidebar);
}
else
{
Sidebar.Visible = false;
Sidebar.Width = 270;
SidebarWrapper.Width = 300;
LineaSidebar.Width = 268;
AnimacionSidebarBack.Show(Sidebar);
}
}
private void bunifuFlatButton8_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
serialPort1.Dispose();
serialPort1.Open();
CheckForIllegalCrossThreadCalls = false;
label2.Text = "CONEXIÓN EXITOSA";
label2.ForeColor = Color.Green;
label2.Font = new Font(label2.Font, FontStyle.Bold);
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
catch
{
label2.Text = "CONEXIÓN FALLIDA";
label2.ForeColor = Color.Red;
label2.Font = new Font(label2.Font, FontStyle.Bold);
MessageBox.Show("REVISE CONEXIÓN DE ARDUINO", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
puerto_seleccionado = comboBox1.Text;
serialPort1.PortName = puerto_seleccionado;
}
private void bunifuFlatButton7_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
label2.Text = "SIN CONEXIÓN";
label2.ForeColor = Color.White;
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private Form activeForm = null;
private void openChildForm(Form childForm)
{
if (activeForm != null)
activeForm.Close();
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm);
panel1.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string[] data = serialPort1.ReadLine().Split(',');
if (data.Length > 10)
{
}
else
{
MessageBox.Show("Intente nuevamente", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
}
Here is my second form:
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;
namespace AUTOCLAVES_GUI
{
public partial class MUESTREO_EN_TIEMPO_REAL : Form
{
public MUESTREO_EN_TIEMPO_REAL()
{
InitializeComponent();
}
private void MUESTREO_EN_TIEMPO_REAL_Load(object sender, EventArgs e)
{
}
private void Salir_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I hope someone can help me overcome this problem.
In this two methods GetDirectories and MyGetDirectories i'm getting recursive all the directories and sub directories. I want to display on label2 in the progresschanged event like a counter that count the number of directories until it finish.
private void _FileInformationWorker_DoWork(object sender, DoWorkEventArgs e)
{
MySubDirectories = GetDirectories(BasePath).ToArray();
}
private void _FileInformationWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
Then the GetDirectories method
private List<DirectoryInfo> GetDirectories(string basePath)
{
IEnumerable<string> str = MyGetDirectories(basePath);
List<DirectoryInfo> l = new List<DirectoryInfo>();
l.Add(new DirectoryInfo(basePath));
IEnumerable<DirectoryInfo> dirs = str.Select(a => new DirectoryInfo(a));
l.AddRange(dirs);
return l;
}
And the method MyGetDirectories
private static IEnumerable<string> MyGetDirectories(string basePath)
{
try
{
string[] dirs = Directory.GetDirectories(basePath);
return dirs.Union(dirs.SelectMany(dir => MyGetDirectories(dir)));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
What I tried is in the method MyGetDirectories I added a counter called the variable countDirectories and I checked it does count.
static int countDirectories = 0;
private static IEnumerable<string> MyGetDirectories(string basePath)
{
try
{
string[] dirs = Directory.GetDirectories(basePath);
countDirectories = countDirectories + dirs.Length;
return dirs.Union(dirs.SelectMany(dir => MyGetDirectories(dir)));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
Then in the DoWork event I did:
private void _FileInformationWorker_DoWork(object sender, DoWorkEventArgs e)
{
MySubDirectories = GetDirectories(BasePath).ToArray();
_FileInformationWorker.ReportProgress(0,countDirectories.ToString());
}
And in the progresschanged event
private void _FileInformationWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label2.Text = e.UserState.ToString();
}
But it's not reporting to the label2 anything I guess since it's still working inside the GetDirectories method. So i'm stuck here.
This is code of form with just button and label on it:
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DirectoryInfo[] MySubDirs;
BackgroundWorker w;
int count;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
count = 0;
w = new BackgroundWorker();
w.DoWork += w_DoWork;
w.ProgressChanged += w_ProgressChanged;
w.WorkerReportsProgress = true;
w.RunWorkerCompleted += w_RunWorkerCompleted;
w.RunWorkerAsync();
}
void w_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
}
void w_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.UserState.ToString();
}
void w_DoWork(object sender, DoWorkEventArgs e)
{
MySubDirs = GetDirectories("d:\\prj").ToArray();
}
private List<DirectoryInfo> GetDirectories(string basePath)
{
IEnumerable<string> str = MyGetDirectories(basePath);
List<DirectoryInfo> l = new List<DirectoryInfo>();
l.Add(new DirectoryInfo(basePath));
IEnumerable<DirectoryInfo> dirs = str.Select(a => new DirectoryInfo(a));
l.AddRange(dirs);
return l;
}
//not static so we can report progress from it
private IEnumerable<string> MyGetDirectories(string basePath)
{
try
{
string[] dirs = Directory.GetDirectories(basePath);
count += dirs.Length;
w.ReportProgress(0, count.ToString());
return dirs.Union(dirs.SelectMany(dir => MyGetDirectories(dir)));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
}
}
Make sure you have set the following to true:
_FileInformationWorker.WorkerReportsProgress = true;
Also make sure you start the work asynchronously as following:
_FileInformationWorker.RunWorkerAsync();
This example should help you with your task as well.
So I load a webpage, that has this in its html code:
<input style="margin-left: 140px;" name="e43X45asfaw4ybrZ34fi879234tg3e4eex" type="submit" id="submit" value="Begå kriminaliteten!" onmouseover="$('#ggg').fadeIn().delay(3000).fadeOut();">
and I use this to click it:
object o = webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("e43X45asfaw4ybrZ34fi879234tg3e4eex")[0].InvokeMember("click");
if (o != null)
{
MessageBox.Show("It worked!");
}
else
{
MessageBox.Show("It didnt work!");
}
and that code always leave it didn't work as well it didn't do anything to the webpage.
Here is my full code:
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;
namespace MafiaspilletRankeBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("mafiaspillet.no");
webBrowser1.ScriptErrorsSuppressed = true;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
timer1.Enabled = true;
timer1.Interval = 15000;
}
catch {
timer1.Enabled = false;
MessageBox.Show("Timer error", "Looks like there a error");
}
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
timerun.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("brukernavn")[0].SetAttribute("value", textBox1.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("passord")[0].SetAttribute("value", textBox2.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("login_buton")[0].InvokeMember("click");
timer2.Enabled = true;
timer2.Interval = 15000;
timer1.Enabled = false;
}
private void timer2_Tick(object sender, EventArgs e)
{
webBrowser1.Navigate("http://mafiaspillet.no/kriminalitet3.php");
timer3.Enabled = true;
timer3.Interval = 15000;
timer2.Enabled = false;
}
private void timer3_Tick(object sender, EventArgs e)
{
object o = webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("e43X45asfaw4ybrZ34fi879234tg3e4eex")[0].InvokeMember("click");
if (o != null)
{
MessageBox.Show("It worked!");
}
else
{
MessageBox.Show("It didnt work!");
}
MessageBox.Show("Bot finnished!", "YEEY!");
timer3.Enabled = false;
}
int i = 0;
private void runtime_Tick(object sender, EventArgs e)
{
i++;
timerun.Text = i.ToString() + " Sekunder";
}
}
}
So my problem is that the InvokeMember("click") doesn't work in my public void timer3_Tick.
It's like it can't do anything, but I can't find the problem :/
you need to processing in the function WebBrowserDocumentCompletedEventArgs
here full code
private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElementCollection inputCol = this.WebBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement el in inputCol)
{
if (el.GetAttribute("type").Equals("submit"))
{
el.InvokeMember("Click");
MessageBox.Show("It worked!");
}
}
}
i Need to open a second serialPort in my Visual C# program to read data from my arduino.
it already worked fine, but in the case you see below it does not work..
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.IO.Ports;
using CommandsPD4I;
namespace CSharpExample
{
public partial class CSharpExample : Form
{
public ComMotorCommands motor1;
public CSharpExample()
{
InitializeComponent();
motor1 = new ComMotorCommands();
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
SerialPort arduino;
delegate void InvokeLB(string Data);
InvokeLB lbRecievedDelegate;
int xPos = 0;
private void StartBtn_Click(object sender, EventArgs e)
{
// Set comm settings for motor 1
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
// Set motor address
motor1.MotorAddresse = Convert.ToInt32(Motor1ID.Value);
// Set relative positioning mode
motor1.SetPositionType(1);
// Start travel profile
if (motor1.ErrorFlag)
{
StatusLabel1.Text = "Status 1: " + motor1.ErrorMessageString;
}
else
{
StatusLabel1.Text = "Status 1: OK";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
// Stop travel profile
motor1.StopTravelProfile();
}
private void timer1_Tick(object sender, EventArgs e)
{
lblPosition.Text = Convert.ToString(motor1.GetPosition());
lblStatus.Text = motor1.ErrorMessageString;
// this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
// xPos++;**strong text**
}
private void btnHoch_Click(object sender, EventArgs e)
{
motor1.SetDirection(0);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void btnRunter_Click(object sender, EventArgs e)
{
motor1.SetDirection(1);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void numericSchritte_ValueChanged(object sender, EventArgs e)
{
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
private void numericGeschwindigkeit_ValueChanged(object sender, EventArgs e)
{
motor1.SetMaxFrequency(Convert.ToInt32(numericGeschwindigkeit.Value));
}
private void btnDiagramm_Click(object sender, EventArgs e)
{
if (timer1.Enabled)
{
timer1.Stop();
}
else
{
timer1.Start();
}
}
private void btnResetDiagramm_Click(object sender, EventArgs e)
{
this.chart1.Series["Kraft"].Points.Clear();
xPos = 0;
}
private void arduino_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string RecievedLine = " ";
while (RecievedLine != "")
{
RecievedLine = arduino.ReadLine();
lblKraft.Invoke(lbRecievedDelegate, new object[] { RecievedLine });
}
}
void Invokelabel1(string Data)
{
label1.Text = Data;
this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
xPos++;
}
private void btnArduino_Click(object sender, EventArgs e)
{
//Hier erstellen wir unseren Serialport und legen die Einstellungen fest
arduino = new SerialPort("COM7", 9600);
if (!arduino.IsOpen)
{
arduino.Open();
if (arduino.IsOpen)
{
lblArduino.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(200)))), ((int)(((byte)(0)))));
lblArduino.Text = "Verbunden mit " + arduino.PortName;
}
}
lbRecievedDelegate = new InvokeLB(Invokelabel1);
arduino.DataReceived += new SerialDataReceivedEventHandler(arduino_DataReceived); //DataRecieved Event abonnieren
}
}
}
When i leave out this:
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
then it works..
I hope you can help :)