Getting client information in C# - c#

I have an application that scans the local network for connected PC's.
I want to get the client information (IP address, MAC address, Host name...) and the connection state (download rate, upload rate), and put them in the ListView, but the problem is that this information is not constant!
How could I get this information in real time? The info in the ListView changes every time the info of the client changes?
My current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Text;
using System.Windows.Forms;
using NetUtils;
using System.Net;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
private IPScanner _scanner;
private class HostSorterByIP : IComparer
{
public int Compare(object x, object y)
{
byte[] bytes1 = ((IPScanHostState)((ListViewItem)x).Tag).Address.GetAddressBytes();
byte[] bytes2 = ((IPScanHostState)((ListViewItem)y).Tag).Address.GetAddressBytes();
int i = bytes1.Length - 1;
for (; i > 0 && bytes1[i] == bytes2[i]; i--)
;
return bytes1[i] - bytes2[i];
}
}
public Form1()
{
InitializeComponent();
_scanner = new IPScanner((int)_spnConcurrentPings.Value, (int)_spnPingsPerScan.Value, _cbContinuousScan.Checked,
(int)_spnTimeout.Value, (int)_spnTTL.Value, _cbDontFragment.Checked, (int)_spnBufferSize.Value);
_scanner.OnAliveHostFound += new IPScanner.AliveHostFoundDelegate(_scanner_OnAliveHostFound);
_scanner.OnStartScan += new IPScanner.ScanStateChangeDelegate(_scanner_OnStartScan);
_scanner.OnStopScan += new IPScanner.ScanStateChangeDelegate(_scanner_OnStopScan);
_scanner.OnRestartScan +=new IPScanner.ScanStateChangeDelegate(_scanner_OnRestartScan);
_scanner.OnScanProgressUpdate +=new IPScanner.ScanProgressUpdateDelegate(_scanner_OnScanProgressUpdate);
_lvAliveHosts.ListViewItemSorter = new HostSorterByIP();
_cmbRangeType.SelectedIndex = 0;
}
private void _scanner_OnAliveHostFound(IPScanner scanner, IPScanHostState host)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.AliveHostFoundDelegate(_scanner_OnAliveHostFound), scanner, host);
return;
}
ListViewItem item = new ListViewItem();
item.Tag = host;
item.BackColor = Color.GreenYellow;
item.SubItems.Add(host.Address.ToString());
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
_lvAliveHosts.Items.Add(item);
_lvAliveHosts.Sort();
host.OnHostNameAvailable += new IPScanHostState.HostNameAvailableDelegate(host_OnHostNameAvailable);
host.OnStateChange += new IPScanHostState.StateChangeDelegate(host_OnStateChange);
if (!host.IsTesting())
{
item.ImageIndex = (int)host.QualityCategory;
item.SubItems[2].Text = host.AvgResponseTime.ToString("F02") + " ms";
item.SubItems[3].Text = ((float)(host.LossCount) / host.PingsCount).ToString("P");
item.SubItems[4].Text = host.HostName;
}
//AddLogEntry("Host [" + host.Address.ToString() + "] is alive.");
Timer newTimer = new Timer();
newTimer.Tag = item;
newTimer.Interval = 2000;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Enabled = true;
}
void host_OnHostNameAvailable(IPScanHostState host)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanHostState.HostNameAvailableDelegate(host_OnHostNameAvailable), host);
return;
}
ListViewItem item = FindListViewItem(host);
if (item != null)
item.SubItems[4].Text = host.HostName;
}
private ListViewItem FindListViewItem(IPScanHostState host)
{
foreach (ListViewItem item in _lvAliveHosts.Items)
{
if (item.Tag == host)
return item;
}
return null;
}
private void host_OnStateChange(IPScanHostState host, IPScanHostState.State oldState)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanHostState.StateChangeDelegate(host_OnStateChange), host, oldState);
return;
}
if (!host.IsTesting())
{
ListViewItem item = FindListViewItem(host);
if (item != null)
{
if (host.IsAlive())
{
item.ImageIndex = (int)host.QualityCategory;
item.SubItems[2].Text = host.AvgResponseTime.ToString("F02") + " ms";
item.SubItems[3].Text = ((float)(host.LossCount) / host.PingsCount).ToString("P");
}
else
{
//AddLogEntry("Host [" + host.Address.ToString() + "] died.");
host.OnStateChange -= host_OnStateChange;
host.OnHostNameAvailable -= host_OnHostNameAvailable;
item.BackColor = Color.IndianRed;
Timer removeTimer = new Timer();
removeTimer.Tag = item;
removeTimer.Interval = 2000;
removeTimer.Tick += new EventHandler(removeTimer_Tick);
removeTimer.Enabled = true;
}
}
}
}
void newTimer_Tick(object sender, EventArgs e)
{
Timer timer = (Timer)sender;
timer.Stop();
timer.Tick -= newTimer_Tick;
ListViewItem item = (ListViewItem)timer.Tag;
item.BackColor = Color.White;
}
void removeTimer_Tick(object sender, EventArgs e)
{
Timer timer = (Timer)sender;
timer.Stop();
timer.Tick -= newTimer_Tick;
ListViewItem item = (ListViewItem)timer.Tag;
_lvAliveHosts.Items.Remove(item);
}
private void _scanner_OnStartScan(IPScanner scanner)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanStateChangeDelegate(_scanner_OnStartScan), scanner);
return;
}
foreach (ListViewItem item in _lvAliveHosts.Items)
{
((IPScanHostState)item.Tag).OnStateChange -= host_OnStateChange;
((IPScanHostState)item.Tag).OnHostNameAvailable -= host_OnHostNameAvailable;
}
_lvAliveHosts.Items.Clear();
_prgScanProgress.Value = 0;
EnableSettings(false);
}
private void EnableSettings(bool enable)
{
_cmbRangeType.Enabled = _tbRangeStart.Enabled = _tbRangeEnd.Enabled = _spnTimeout.Enabled = _spnTTL.Enabled = _spnBufferSize.Enabled = _cbDontFragment.Enabled =
_spnConcurrentPings.Enabled = _spnPingsPerScan.Enabled = _cbContinuousScan.Enabled = enable;
_btnStartStop.Text = enable ? "&Start" : "&Stop";
if (enable)
_prgScanProgress.Text = "Scanner is not running!";
}
private void _btnStartStop_Click(object sender, EventArgs e)
{
if (!_scanner.Active)
{
try
{
_scanner.Start(_cmbRangeType.SelectedIndex == 0
? new IPScanRange(IPAddress.Parse(_tbRangeStart.Text), IPAddress.Parse(_tbRangeEnd.Text))
: new IPScanRange(IPAddress.Parse(_tbRangeStart.Text), int.Parse(_tbRangeEnd.Text)));
}
catch (FormatException)
{
MessageBox.Show(this, "Cannot parse IP range or subnetmask!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
_scanner.Stop(false);
}
private void _scanner_OnStopScan(IPScanner scanner)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanStateChangeDelegate(_scanner_OnStopScan), scanner);
return;
}
EnableSettings(true);
_prgScanProgress.Value = 0;
}
void _scanner_OnRestartScan(IPScanner scanner)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanStateChangeDelegate(_scanner_OnRestartScan), scanner);
return;
}
_prgScanProgress.Value = 0;
}
void _scanner_OnScanProgressUpdate(IPScanner scanner, IPAddress currentAddress, ulong progress, ulong total)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanProgressUpdateDelegate(_scanner_OnScanProgressUpdate), scanner, currentAddress, progress, total);
return;
}
int prog = (int)((100 * progress) / total);
_prgScanProgress.Value = prog;
_prgScanProgress.Text = prog.ToString() + "%" + " [" + currentAddress.ToString() + "]";
}
private void _cmbRangeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (_cmbRangeType.SelectedIndex == 0)
{
_lRangeSep.Text = "-";
_lRangeEnd.Text = "Range &End:";
_tbRangeEnd.Size = new Size(130, _tbRangeEnd.Size.Height);
}
else
{
_lRangeSep.Text = "/";
_lRangeEnd.Text = "Subnet &Mask:";
_tbRangeEnd.Size = new Size(32, _tbRangeEnd.Size.Height);
}
}
//private void _lvAliveHosts_DoubleClick(object sender, EventArgs e) { _btnAddHost_Click(sender, e); }
private void IPScanForm_FormClosing(object sender, FormClosingEventArgs e) { _scanner.Stop(true); }
private ListViewItem.ListViewSubItem _activeTooltipSubitem = null;
private static string[] QualityCategoryNames = { "Very Poor", "Poor", "Fair", "Good", "Very Good", "Excellent", "Perfect" };
private void _lvAliveHosts_MouseMove(object sender, MouseEventArgs e)
{
ListViewItem item = _lvAliveHosts.HitTest(e.Location).Item;
if (item != null)
{
ListViewItem.ListViewSubItem subitem = _lvAliveHosts.HitTest(e.Location).SubItem;
if (subitem != null && item.SubItems.IndexOf(subitem) == 0)
{
if (_activeTooltipSubitem != subitem)
{
_ttQuality.Show("Quality: " + QualityCategoryNames[item.ImageIndex], _lvAliveHosts, item.SubItems[1].Bounds.X, subitem.Bounds.Y);
_activeTooltipSubitem = subitem;
}
return;
}
}
_activeTooltipSubitem = null;
_ttQuality.Hide(_lvAliveHosts);
}
}
}

I would create the list of clients and show them in the listview.
Than, in a background thread, every X seconds, poll all of the current clients.
Next , compare the list of updated clients to a list of clients from last update.
What remain to do is to add any new client to the list, and remove any client which no longer exists.
Pay attention to the context, use InvokeRequired() to get access to the UI control from the background thread.
EDIT:
here is how to run a background thread:
static void Main(string[] args)
{
Thread worker = new Thread(DoBackgroundWork);
}
public static void DoBackgroundWork()
{
while (true)
{
//Sleep 10 seconds
Thread.Sleep(10000);
//Do some work and than post to the control using Invoke()
}
}

Related

When I minimize to notifyicon and after that maximize it for 2-3 times, Form freezes and sometime gives an error

When I minimize my form application and maximize it from notifyicon, When I repeat minimize and maximize action over and over again, after 2-3 times , My froms is freezing. There is no problem till I add switch case block but now when I remove the block, it goes on giving error.Why ? Can You Help me? Error is Here :
System.ArgumentException
HResult=0x80070057
Message=Döngüsel denetim başvurusu yapıldı. Denetim kendi kendisinin sahibi olamaz veya kendisi tarafından üstü olarak atanamaz.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.CheckParentingCycle(Control bottom, Control toFind)
at System.Windows.Forms.Form.set_Owner(Form value)
at MetroFramework.Forms.MetroForm.RemoveShadow()
at MetroFramework.Forms.MetroForm.OnClosed(EventArgs e)
at System.Windows.Forms.Form.WmClose(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at MetroFramework.Forms.MetroForm.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Security.Cryptography;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
namespace webService_Synchronization
{
public partial class Form1 : MetroFramework.Forms.MetroForm
{
domainService.controlService nsService = new domainService.controlService();
DataTable dt = new DataTable();
cryptography cryptography = new cryptography();
static SemaphoreSlim semaphore = new SemaphoreSlim(1);
System.Timers.Timer aTimer = new System.Timers.Timer();
int succeed, error, attention;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
double timerIntervali = calcInterval();
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = timerIntervali;
aTimer.Enabled = true;
controlService.demodata demodata = new controlService.demodata();
dt = demodata.domains("test.com");
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string Domain = dt.Rows[i][0].ToString();
string Folder = dt.Rows[i][1].ToString();
MD5 md5Hash = MD5.Create();
string md5hashDomain = cryptography.GetMd5Hash(md5Hash, Domain);
string sha1hashDomain = cryptography.GetSHA1(Domain);
syncIT(i, Domain, Folder, md5hashDomain, sha1hashDomain);
if (i==2) { break; }
}
aTimer.Interval = calcInterval();
}
public double calcInterval()
{
DateTime nowTime = Convert.ToDateTime(DateTime.Now.ToLongTimeString());
if (0 > (DateTime.Compare(nowTime, Convert.ToDateTime("12:00"))))
{
TimeSpan differenceMillisecond = Convert.ToDateTime("12:00:00") - nowTime;
return differenceMillisecond.TotalMilliseconds;
}
else
{
TimeSpan differenceMillisecond = Convert.ToDateTime("23:59:59") - nowTime;
return differenceMillisecond.TotalMilliseconds;
}
}
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == WindowState)
{
ntfytestSenkronizasyon.Visible = true;
this.ShowInTaskbar = false;
this.Visible = false;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (ntfytestSenkronizasyon != null)
{
if (ntfytestSenkronizasyon.Visible)
{
ntfytestSenkronizasyon.Visible = false;
}
}
}
private void ntfytestSenkronizasyon_MouseClick(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Right:
testSenk.Show();
break;
case MouseButtons.Left:
ShowInTaskbar = true;
Show();
WindowState = FormWindowState.Normal;
break;
}
}
private void show_Click(object sender, EventArgs e)
{
ShowInTaskbar = true;
Show();
WindowState = FormWindowState.Normal;
}
private void close_Click(object sender, EventArgs e)
{
ntfytestSenkronizasyon.Visible = false;
Environment.Exit(0);
}
private void btnsyncIT_Click(object sender, EventArgs e)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string Domain = dt.Rows[i][0].ToString();
string Folder = dt.Rows[i][1].ToString();
MD5 md5Hash = MD5.Create();
string md5hashDomain = cryptography.GetMd5Hash(md5Hash, Domain);
string sha1hashDomain = cryptography.GetSHA1(Domain);
syncIT(i, Domain, Folder, md5hashDomain, sha1hashDomain);
if (i == 2) { break; }
}
}
public async Task syncIT(int a, string _domain, string _filePath, string _md5Domain, string _sha1Domain)
{
lblattention.Invoke(new Action(() => lblattention.Text = "attention: "));
lblerror.Invoke(new Action(() => lblerror.Text = "error: "));
lblsucceed.Invoke(new Action(() => lblsucceed.Text = "succeeded: "));
attention = 0; error = 0; succeed = 0;
dgwHistory.Rows.Clear();
dgwHistory.Refresh();
if (!(_domain.ToLower()).Contains("localhost"))
{
await semaphore.WaitAsync();
btnsyncIT.Invoke(new Action(() => btnsyncIT.Enabled = false));
try
{
metroLabel1.Invoke(new Action(() => metroLabel1.Text = _domain + " Your process is continuing"));
nsService.Url = "http://www." + _domain + "/Api/controlService.asmx";
nsService.Timeout = -1;
domainService.ServiceResult senk = await Task.Run(() => nsService.Senkronizasyon(_domain, _filePath, _md5Domain, _sha1Domain));
metroLabel1.Invoke(new Action(() => metroLabel1.Text = "Completed..."));
bool status = senk.Status;
string durum = "Attention";
if (status) { durum = "succeeded"; }
string statusMessage = senk.StatusMsg;
if (durum == "succeeded")
{
dgwHistory.Invoke(new Action(() => dgwHistory.Rows.Add(_domain, durum, statusMessage, DateTime.Now)));
dgwHistory.Invoke(new Action(() => dgwHistory.Rows[dgwHistory.Rows.Count - 2].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#baffc9")));
++succeed;
lblsucceed.Invoke(new Action(() => lblsucceed.Text = "succeeded: " + succeed));
}
else
{
dgwHistory.Invoke(new Action(() => dgwHistory.Rows.Add(_domain, durum, statusMessage, DateTime.Now)));
dgwHistory.Invoke(new Action(() => dgwHistory.Rows[dgwHistory.Rows.Count - 2].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#ffffba")));
++attention;
lblattention.Invoke(new Action(() => lblattention.Text = "attention: " + attention));
}
}
catch (Exception e)
{
dgwHistory.Invoke(new Action(() => dgwHistory.Rows.Add(_domain, "Attention", "We cannot access this domain!", DateTime.Now)));
dgwHistory.Invoke(new Action(() => dgwHistory.Rows[dgwHistory.Rows.Count - 2].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#ffb3ba")));
++error;
lblerror.Invoke(new Action(() => lblerror.Text = "error: " + error));
}
finally
{
btnsyncIT.Invoke(new Action(() => btnsyncIT.Enabled = true));
ntfytestSenkronizasyon.Visible = true;
ntfytestSenkronizasyon.ShowBalloonTip(360000000, "Program is Running", "succeeded: " + succeed + " attention: " + attention + " error: " + error, ToolTipIcon.Info);
semaphore.Release();
}
}
}
}
}

Multithread using backgroundworker and event handler

I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response

how to release thread is required in multiple thread?

As title, how to release thread is required in multiple thread ?
Ex : I have 5 thread is waiting. I only want thread position 3 is released
I use autoresetevent/manualresetevent/monitor.wait and monitor.pulse but all release thread follow FIFO
help me !!!
UPDATED:
This is form1:
private BackgroundWorker[] threadArray;
public static ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
private void btn_Start_Scraping_Click(object sender, EventArgs e)
{
threadArray = new BackgroundWorker[listView_Site.Items.Count];
for (var f = 0; f < listView_Site.Items.Count; f++)
{
threadArray[f] = new BackgroundWorker();
threadArray[f].DoWork += new DoWorkEventHandler(BackgroundWorkerFilesDoWork);
threadArray[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerFilesRunWorkerCompleted);
threadArray[f].ProgressChanged += new ProgressChangedEventHandler(BackgroundWorkerFilesProgressChanged);
threadArray[f].WorkerReportsProgress = true;
threadArray[f].WorkerSupportsCancellation = true;
threadArray[f].RunWorkerAsync(listView_Site.Items[f].Tag.ToString());
}
}
private void BackgroundWorkerFilesDoWork(object sender, DoWorkEventArgs e)
{
....// all above code is fine
requestCaptcha = (HttpWebRequest)WebRequest.Create(uriCaptchaPage);
requestCaptcha.Pipelined = true;
requestCaptcha.KeepAlive = true;
requestCaptcha.AllowAutoRedirect = false;
//request.Proxy = null;
requestCaptcha.Timeout = 60000;
requestCaptcha.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
requestCaptcha.CookieContainer = sessionID;
request.ServicePoint.Expect100Continue = false;
requestCaptcha.Method = "GET";
requestCaptcha.Referer = uriloginPage.AbsoluteUri;
//get response.
responseCaptcha = (HttpWebResponse)requestCaptcha.GetResponse();
Stream imagestream = responseCaptcha.GetResponseStream();
if (imagestream != null)
{
Image image = Image.FromStream(imagestream);
if (Directory.Exists(Application.StartupPath + "\\Captcha") == false)
{
Directory.CreateDirectory(Application.StartupPath + "\\Captcha");
}
switch (responseCaptcha.ContentType)
{
case "image/jpeg":
{
saveLocation += ".jpg";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation,ImageFormat.Jpeg);
break;
}
case "image/gif":
{
saveLocation += ".gif";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation, ImageFormat.Gif);
break;
}
case "image/png":
{
saveLocation += ".png";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation, ImageFormat.Png);
break;
}
}
//show form2 to enter captcha
lock (_lockObj)
{
if (Application.OpenForms.OfType<frmCaptchaQuestion>().Any() == false)
{
DoOnUIThread(delegate()
{
_formCaptchaQuestion.CreatePanelCaptcha(uriloginPage, saveLocation,idHomePage);
_formCaptchaQuestion.Show();
});
}
else
{
DoOnUIThread(() => _formCaptchaQuestion.CreatePanelCaptcha(uriloginPage, saveLocation,idHomePage));
}
}
//wait and get captcha from form2 and only run thread is required
//this is my problem <<<<========================================
lock (_lockObj)
{
//_manualResetEvent.WaitOne(30000);
//_manualResetEvent.Reset();
//if (clsValueStatic.CaptchaText != null)
//{
// foreach (var id in clsValueStatic.CaptchaText)
// {
while (!_go)
{
Monitor.Wait(_lockObj);
}
// }
//}
}
requestCaptcha = (HttpWebRequest)WebRequest.Create(uriActionLoginPage);
requestCaptcha.Pipelined = true;
requestCaptcha.KeepAlive = true;
requestCaptcha.AllowAutoRedirect = false;
//request.Proxy = null;
requestCaptcha.Timeout = 60000;
requestCaptcha.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
requestCaptcha.CookieContainer = sessionID;
request.ServicePoint.Expect100Continue = false;
requestCaptcha.Method = "GET";
}
Form2:
private void textBoxCaptcha_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBox = sender as TextBoxX;
if (textBox != null)
{
clsValueStatic.CaptchaText = textBox.Text.Trim();
textBox.Parent.Parent.Dispose();
frmScrapingAnalysis._manualResetEvent.Set();
}
}
}
PS : Form1 have 1 button to start multiple backgroundworker and show form2 then all backgroundworker wait to get text captcha of textbox from form2
my way want when user enter text of backgroundworker is shown on form2 then only the backgroundworker is released. All other backgroundworker still wait

C# Getting Serial Port In use error and can't understand why

Basically I need to communicate with a COM serial printer. There are 2 timers, one will print one ticket at time, and the others will hang up checking for errors and resuming the printing when the errors are gone.
For example: Printer is printing but if I press the pause button an error (read in the buffer) will get some booleans to 1 and after I read them I am able to tell what the error is and stop the printing.
My problem is in the method ErrorTimer_Elapsed() which is the timer elapsed event and probably is linked to the ErrorCheck and SendToCom (which is the printing method). The problem is that program detects errors well, but when in ErrorTimer_Elapsed() I try to repeatdly check for error status changes, I get IO errors like:
-Can't acces COM PORT
-The resource you required is in use
and so on.
Can you help me? Thanks, here's the code (about 180 lines), I'm bumping my head on this since 3 days :( :
using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
#region Variabili di istanza
private ArrayList _filesToPrint = new ArrayList();
private static SerialPort _serialPort1 = new SerialPort();
private string _portName = ConfigurationSettings.AppSettings["COM"];
private string FilesPath = ConfigurationSettings.AppSettings["Path"];
private System.Timers.Timer PrintTimer = new System.Timers.Timer(2000);
private System.Timers.Timer ErrorTimer = new System.Timers.Timer(3500);
private bool PrintTimerIsActive = true;
private string HsCOMerrorStrings, PrintErrors;
#endregion
public Form1()
{
_serialPort1.PortName = _portName;
_serialPort1.ReadTimeout = 1000;
_IfFileExistsPrint();
}
private void _IfFileExistsPrint()
{
foreach (string file in Directory.GetFiles(FilesPath))
_filesToPrint.Add(file);
FileSystemWatcher SysWatch = new FileSystemWatcher(FilesPath, "*.*");
SysWatch.Created += new FileSystemEventHandler(SysWatch_Created);
SysWatch.EnableRaisingEvents = true;
PrintTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
PrintTimer.Start();
ErrorTimer.Elapsed += new System.Timers.ElapsedEventHandler(ErrorTimer_Elapsed);
}
private void SysWatch_Created(object Sender, FileSystemEventArgs w)
{
_filesToPrint.Add(w.FullPath);
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_filesToPrint.Count > 0 && PrintTimerIsActive)
{
PrintTimer.Stop();
SendFilesToCom(_filesToPrint[0].ToString());
MessageBox.Show("Printing file :" + _filesToPrint[0].ToString());
File.Delete(_filesToPrint[0].ToString());
_filesToPrint.RemoveAt(0);
_filesToPrint.TrimToSize();
Console.Write(HsCOMerrorStrings);
PrintTimer.Start();
PrintErrors = ErrorCheck(HsCOMerrorStrings);
}
}
private void ErrorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs d)
{
if (!_serialPort1.IsOpen)
{
try
{
_serialPort1.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Data);
}
}
try
{
HsCOMerrorStrings = _serialPort1.ReadExisting();
_serialPort1.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Data);
}
Console.WriteLine(ErrorCheck(HsCOMerrorStrings));
}
private string ErrorCheck(string COMHostStatusReturn)
{
string ErrorsReturn = System.String.Empty;
string[] COMCode = COMHostStatusReturn.Split(',');
if (COMCode[1] == "1") { ErrorsReturn += "Carta Esaurita" + Environment.NewLine; }
if (COMCode[2] == "1") { ErrorsReturn += "Stampante in Pausa" + Environment.NewLine; }
if (COMCode[5] == "1") { ErrorsReturn += "Memoria Stampante Esaurita" + Environment.NewLine; }
if (COMCode[9] == "1") { ErrorsReturn += "Memoria RAM corrotta" + Environment.NewLine; }
if (COMCode[10] == "1") { ErrorsReturn += "Temperatura troppo bassa" + Environment.NewLine; }
if (COMCode[11] == "1") { ErrorsReturn += "Temperatura troppo alta" + Environment.NewLine; }
if (COMCode[7] == "1") { ErrorsReturn += "Partial Format Flag" + Environment.NewLine; }
if (ErrorsReturn != System.String.Empty)
{
if (PrintTimerIsActive == true)
{
PrintTimer.Stop();
if (!ErrorTimer.Enabled)
ErrorTimer.Start();
MessageBox.Show(ErrorsReturn);
}
PrintTimerIsActive = false;
}
else
{
if (PrintTimerIsActive == false)
{
ErrorTimer.Stop();
PrintTimer.Start();
PrintTimerIsActive = true;
}
}
return ErrorsReturn;
}
private void SendFilesToCom(string filePath)
{
if (!_serialPort1.IsOpen)
{
try
{
_serialPort1.Open();
}
catch (Exception ex)
{
}
}
try
{
using (System.IO.TextReader reader = File.OpenText(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_serialPort1.WriteLine(line);
}
HsCOMerrorStrings = _serialPort1.ReadLine();
reader.Close();
_serialPort1.Close();
}
}
catch (Exception ex)
{
}
}
}
}

Report progress using BackgroundWorker report only for the first time

I want my application will show on my form my class properties so I started my class with BackgroundWorker and create ProgressChanged.
my class:
public class DumpFile
{
PacketDevice _device;
public int _packetsCount;
public double _bitsPerSecond;
public double _packetsPerSecond;
public DateTime _lastTimestamp;
public delegate void dlgPackProgress(int progress);
public event dlgPackProgress evePacketProgress;
public DumpFile(PacketDevice device, string pcapPath)
{
_device = device;
_pcapPath = pcapPath;
_packetsCount = 1;
}
public void startCapturing()
{
OnPacketProgress(_packetsCount++);
using (PacketCommunicator communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the device
{
ThreadStart starter = delegate { openAdapterForStatistics(_device); };
new Thread(starter).Start();
using (PacketDumpFile dumpFile = communicator.OpenDump(_pcapPath)) //open the dump file
{
communicator.ReceivePackets(0, dumpFile.Dump); //start the capture
}
}
}
private void OnPacketProgress(int packet)
{
var handler = evePacketProgress;
if (handler != null)
{
handler(packet);
}
}
public void openAdapterForStatistics(PacketDevice selectedOutputDevice)
{
using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter
{
ThreadStart start = delegate { test(selectedOutputDevice); };
new Thread(start).Start();
statCommunicator.SetFilter("tcp"); //compile and set the filter
statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode
statCommunicator.ReceiveStatistics(0, StatisticsHandler);
}
}
public void test(PacketDevice selectedOutputDevice)
{
using (PacketCommunicator communicator = selectedOutputDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.ReceivePackets(0, PacketHandler);
}
}
private void PacketHandler(Packet packet)
{
string result = _packetsCount.ToString() + ". " + packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length;
_packetsCount++;
}
private void StatisticsHandler(PacketSampleStatistics statistics)
{
DateTime currentTimestamp = statistics.Timestamp; //current sample time
DateTime previousTimestamp = _lastTimestamp; //previous sample time
_lastTimestamp = currentTimestamp; //set _lastTimestamp for the next iteration
if (previousTimestamp == DateTime.MinValue) //if there wasn't a previous sample than skip this iteration (it's the first iteration)
{
return;
}
double delayInSeconds = (currentTimestamp - previousTimestamp).TotalSeconds; //calculate the delay from the last sample
_bitsPerSecond = statistics.AcceptedBytes * 8 / delayInSeconds; //calculate bits per second
_packetsPerSecond = statistics.AcceptedPackets / delayInSeconds; //calculate packets per second
}
}
start button who start capturing:
private void btnStartCapture_Click(object sender, EventArgs e)
{
timerSniffer.Start();
btnStartTabSniffer.Enabled = false;
btnStopTabSniffer.Enabled = true;
groupBoxSelectTabSniffer.Enabled = false;
bgWorker = new BackgroundWorker();
bgWorker.WorkerReportsProgress = true;
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWSniffer_ProgressChanged);
bgWorker.DoWork += new DoWorkEventHandler(
(s3, e3) =>
{
DumpFile dumpFile = new DumpFile(deviceForCapturing, pcapFilePathSniffer);
tshark.evePacketProgress += new DumpFile.dlgPackProgress(
(packet) =>
{
bgWorker.ReportProgress(packet, dumpFile);
});
dumpFile.startCapturing();
});
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
groupBoxSelectTabSniffer.Enabled = true;
});
bgWorker.RunWorkerAsync();
}
ProgressChanged:
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var dumpFile = (DumpFile)e.UserState;
lblNumberOfPacketsTabSniffer2.Text = dumpFile._packetsCount.ToString("#,##0");
lblTrafficRateTabSniffer2.Text = (dumpFile._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + dumpFile._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRateTabSniffer2.Text = dumpFile._packetsPerSecond.ToString("#,##0") + " Packets/sec";
}
the problem is that my application "get into" ProgressChanged functions but only in one time.
I think I missed something in my class.
I can only find one call to OnPacketProgress(), and it's outside of any loop.
public void startCapturing()
{
OnPacketProgress(_packetsCount++);
....
}
So Yes, that will only be called once.
You need something inside ReceivePackets()

Categories

Resources