C# passing serial to class - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
namespace Datalogging
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public class ThreadExample
{
public static void ThreadJob(MainWindow mainWindow)
{
string dBConnectionString = #"Data Source = C:\Users\johnmark\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
//open connection to database
try
{
sqliteCon.Open();
SQLiteCommand createCommand = new SQLiteCommand("Select empID from EmployeeList", sqliteCon);
SQLiteDataReader reader;
reader = createCommand.ExecuteReader();
//richtextbox2.Document.Blocks.Clear();
while (reader.Read())
{
string Text = (String.Format("{0}", Object.Equals(definition.buffering, reader.GetValue(0))));
if (Convert.ToBoolean(Text))
{
mainWindow.SerialWrite('s');
Console.WriteLine(Text);
//richtextbox1.Document.Blocks.Add(new Paragraph(new Run(Text)));
}
}
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public partial class MainWindow : Window
{
//string received_data;
//Thread readThread = new Thread(Read);
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
SerialPort serial = new SerialPort();
public MainWindow()
{
InitializeComponent();
combobox1.Items.Insert(0, "Select Port");
combobox1.SelectedIndex = 0;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
if ((string)button2.Content == "Connect")
{
string myItem = combobox1.SelectedItem.ToString();
if (myItem == "Select Port")
{
MessageBox.Show("Select Port");
}
else
{
serial.PortName = myItem;
serial.Open();
button2.Content = "Disconnect";
textbox2.Text = "Serial Port Opened";
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
}
}
else
{
serial.Close();
button2.Content = "Connect";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region Receiving
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serial.BytesToRead;
byte[] buffer = new byte[bytes];
serial.Read(buffer, 0, bytes);
foreach (var item in buffer)
{
Console.Write(item.ToString());
}
definition.buffering = BitConverter.ToInt64(buffer, 0);
Console.WriteLine();
Console.WriteLine(definition.buffering);
Console.WriteLine();
Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));
thread.Start();
thread.Join();
}
#endregion
public void WriteSerial(string text)
{
serial.Write(text);
}
}
}
Hi guys. Can anyone help me what went wrong in this code? It is displaying this error:
Error 2 'Datalogging.MainWindow' does not contain a definition for 'SerialWrite' and no extension method 'SerialWrite' accepting a first argument of type 'Datalogging.MainWindow' could be found (are you missing a using directive or an assembly reference?)
Error 3 Method name expected
how can I fix that? Please edit the code and post it here as your answer thanks.

Change your method call mainWindow.SerialWrite('s'); to mainWindow.WriteSerial('s'); to fit the method name declared here :
public void WriteSerial(string text)
You inverted both words.
For your "Method name expected", I guess it's in port_DataReceived. You need to pass a delegate to the thread, but you're not doing it correctly.
Instead of
Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));
(you can't directly pass a method as a parameter, you can only use function pointers) you can use this syntax to pass a delegate :
Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
Please note that new TreadStart is redundant, new Thread(() => ThreadExample.ThreadJob(this)); will do the job.

Related

Program in c# stopped working after change of router

I tried everything I could, but nothing works. My IP address 3 first digits changed from 192.168.1 to 192.168.0. The program has to accept data from address 192.168.0.255 then in reaction, it has to open a window and play video from a folder and is set to listen to every IP address there shouldn't be a problem before the change of router everything worked as expected.
For sending data I use my own android app I tested that app with Wireshark everything works as it should.
The window doesn't open everything works, but it seems that the socket just doesn't get any data.=>condition checking for available data socket available>0 returns false.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Timers;
using System.Net.Sockets;
using System.Net;
namespace SysConf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Timer timer1;
System.Windows.Threading.DispatcherTimer dispatcherTimer;
Encoding coding = Encoding.GetEncoding("ISO-8859-2");
int ByteC;
Byte[] bytes = new byte[1024];
EndPoint rE = new IPEndPoint(IPAddress.Any, 2200);
int order = 0;
public MainWindow()
{
InitializeComponent();
Clipboard.SetText(GetLocalIPAddress());
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (ip.ToString().Split('.')[0] == "192")
{
return ip.ToString();
}
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void MainWindow1_StateChanged(object sender, EventArgs e)
{
if (MainWindow1.WindowState == WindowState.Maximized) { MainWindow1.WindowStyle = WindowStyle.None; }
else { MainWindow1.WindowStyle= WindowStyle.SingleBorderWindow; }
}
private void MainWindow1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.F11)
{
if (MainWindow1.WindowState == WindowState.Maximized)
{
MainWindow1.WindowState = WindowState.Normal;
MainWindow1.Topmost = false;
}
else
{
MainWindow1.WindowState = WindowState.Maximized;
MainWindow1.Topmost = true;
}
}
}
private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
{
// win = (SysConf.MainWindow)Application.Current.MainWindow;
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(10);
dispatcherTimer.Start();
// MainWindow1.Visibility = Visibility.Collapsed;
MainWindow1.Visibility = Visibility.Collapsed;
if (GetLocalIPAddress() != "No network adapters with an IPv4 address in the system!")
{
sck.Bind(new IPEndPoint(IPAddress.Parse(GetLocalIPAddress()), 2200));
}
else
{
MessageBox.Show("No Internet connection!");
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (player1.Position == player1.NaturalDuration & MainWindow1.Visibility == Visibility.Visible)
{
MainWindow1.Topmost = false;
MainWindow1.Visibility = Visibility.Collapsed;
}
Task.Run(() =>
{
if (sck.Available > 0)
{
MessageBox.Show("Data arrived");
ByteC = sck.ReceiveFrom(bytes, ref rE);
order = 1;
}
});
if (order == 1)
{
this.Close();
String cmd = coding.GetString(bytes);
MainWindow1.Visibility = Visibility.Visible;
MainWindow1.Topmost = true;
player1.Source = new Uri("Resources/" + (cmd.Substring(0,12)).Split('_')[1] + ".mp4", UriKind.Relative); //+ (#"\Resources\" ), UriKind.Relative);
player1.Position = TimeSpan.Zero;
MainWindow1.WindowState = WindowState.Maximized;
player1.Play();
order = 0;
bytes = null;
bytes = new byte[9024];
cmd = "";
}
dispatcherTimer.Start();
}
private void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//win.Visibility = Visibility.Visible;
timer1.Start();
}
private void player1_BufferingEnded(object sender, RoutedEventArgs e)
{
}
}
}

Background worker still freezing ui

Even tho I setup a background worker, I can't seem to make it not freeze the UI.
I looked around online but could not find a fix. I have tried creating basic threads and that worked but I need to also update UI stuff as it runs so thats why I switched to backgroundworkers, but if you could help me figure out how to use a basic thread and get that working that would be ok.
using MediaToolkit;
using MediaToolkit.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using VideoLibrary;
namespace ConsoleApp1
{
public partial class Form1 : Form
{
private List<VideoInfo> vids = new List<VideoInfo>();
private List<VideoInfo> failedVids = new List<VideoInfo>();
private int threads = 0;
BackgroundWorker worker;
private delegate void DELEGATE();
static void Main(string[] args)
{
Form1 form = new Form1();
form.ShowDialog();
}
public Form1()
{
InitializeComponent();
worker = new BackgroundWorker();
}
private void button1_Click(object sender, EventArgs e)
{
if(threads == 0)
{
progressBar1.Maximum = vids.Count;
progressBar1.Value = 0;
failedVids.Clear();
worker.DoWork += doWork;
worker.RunWorkerAsync();
//downloadVid();
}else
{
Console.WriteLine("Waiting for threads" + threads);
}
/*Thread thread1 = new Thread(new ThreadStart(downloadVid));
thread1.Start();*/
}
private void button1_Click_1(object sender, EventArgs e)
{
VideoInfo vid = new VideoInfo(tbLink.Text, tbTitle.Text, tbArtist.Text);
vids.Add(vid);
tbLink.Clear();
tbTitle.Clear();
listView1.Items.Add(vid.getLink());
}
private int downloadThread(int i)
{
Console.WriteLine(i);
var source = #"C:\Users\derri\Downloads\DownloadTest\";
var youtube = YouTube.Default;
VideoInfo vidInfo = vids[(int) i];
var vid = youtube.GetVideo(vidInfo.getLink());
Console.WriteLine(vidInfo.getLink());
try
{
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
}
catch (Exception e)
{
failedVids.Add(vids[(int)i]);
Console.WriteLine(e);
goto End;
}
var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{source + vidInfo.getArtist() + " - " + vidInfo.getTitle()}.mp3" };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
File.Exists(outputFile.Filename);
File.Delete(inputFile.Filename);
setTags(vidInfo.getArtist(), vidInfo.getTitle());
End:
threads--;
return 1;
}
private void doWork(object sender, DoWorkEventArgs e)
{
Delegate del = new DELEGATE(downloadVid);
this.Invoke(del);
}
private void downloadVid()
{
int prog = 0;
for (int i = 0; i < vids.Count; i++)
{
Console.WriteLine(i);
while ((threads > 5)) { }
Thread thread = new Thread(() => { prog += downloadThread(i); });
thread.Start();
threads++;
System.Threading.Thread.Sleep(1000);
//thread.Join();
/*ParameterizedThreadStart start = new ParameterizedThreadStart(downloadThread);
Thread t = new Thread(start);
t.Start(i);
progressBar1.Value++;
threads++;*/
}
while (threads > 0){}
foreach (VideoInfo failedVid in failedVids)
{
listView2.Items.Add(failedVid.getLink());
}
listView1.Clear();
vids.Clear();
}
private void setTags(string artist, string title)
{
TagLib.File file = TagLib.File.Create("C:\\Users\\derri\\Downloads\\DownloadTest\\" + artist + " - " + title + ".mp3");
file.Tag.Artists = (new String[] { artist });
file.Tag.Title = (title);
file.Save();
}
}
}
this.Invoke will run on the UI thread.
Look into how to use either ReportProgress or RunWorkerCompleted events of the BackgroundWorker class. The both allow you to pass data from the background thread to the UI thread.

How to run a task every n minutes

I wrote a code to update DDNS which works fine. I now need to run this code every n minutes: how would I go doing that?
I tried using:
while (true)
{
this.DoMyMethod();
Thread.Sleep(TimeSpan.FromMinutes(1));
}
and I am still having some trouble. What is the best way to run this task every n minutes?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
}
}
}
Why not using System.Threading.Timer to do so?
From the Microsoft documentation, say you have the following sample class:
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if (invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
Then you can create a Timer to run CheckStatus every n seconds, like:
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(5);
// creates a Timer to call CheckStatus() with autoEvent as argument,
// starting with 1 second delay and calling every 2 seconds.
var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 2000);
autoEvent.WaitOne();
i use timer,
the code is
using System;
using System.Net;
using System.Timers;
static void Main(string[] args)
{
Console.WriteLine("The system is start at {0}", DateTime.Now);
Timer t = new Timer(10000);
t.Enabled = true;
t.Elapsed += T_Elapsed;
Console.ReadKey();
}
private static void T_Elapsed(object sender, ElapsedEventArgs e)
{
//write your code
}
This is what fixed for me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
//Properties.Settings.Default.intervalsave = interval.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
//interval.Text = Properties.Settings.Default.intervalsave;
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
//this.Close();
}
}
}
Have a look at this. I recall a colleague using it a while ago:
FluentScheduler - [Project Site]
Usage:
// Schedule an IJob to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Minutes();
Will fulfill your need.
somwhere met this code
class Program
{
static void Main(string[] args)
{
int Interval = 5;
CancellationTokenSource cancellation = new CancellationTokenSource();
Console.WriteLine("Start Loop...");
RepeatActionEvery(() => Console.WriteLine("Hi time {0}",DateTime.Now), TimeSpan.FromMinutes(Interval), cancellation.Token).Wait();
Console.WriteLine("Finish loop!!!");
}
public static async Task RepeatActionEvery(Action action, TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
action();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
}

Why does my Outlook becomes slow and sometimes unresponsive after starting an app to clear the clipboard?

I had a requirement to disable Copy Paste and even the print screen key while a website is running. So I wrote a WPF application to keep clearing the clipboard when Open Website link is clicked and stop clearing as soon as Close website button. But the problem is that when I press Open Website button the outlook client becomes very slow and sometimes unresponsive. I know that it has something to do with the clipboard only. Is there a way to disable Outlooks clipboard until the button is pressed.
However the code is not required but is included bleow, or can be downloaded from Dropbox:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Security.Cryptography;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Net.NetworkInformation;
namespace ccb
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string docNum,qs;
int status = 0;
static string connectionstring = "SERVER=abcd.com;port=3306;DATABASE=abcd_secure;UID=abcd_sec;PASSWORD=abcd_sec";
MySqlConnection conn = new MySqlConnection(connectionstring);
private static Random random = new Random((int)DateTime.Now.Ticks);
public MainWindow()
{
InitializeComponent();
}
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
status = 1;
Thread backgroundThread = new Thread(clear);
backgroundThread.IsBackground = true;
backgroundThread.SetApartmentState(ApartmentState.STA);
backgroundThread.Start();
qs=generaterandomnumber();
insert(qs);
System.Diagnostics.Process.Start("http://abcd/login.php?osid=win&id="+qs);
}
private void clear()
{
while (status == 1)
System.Windows.Clipboard.Clear();
}
//Genrate random number and encrypt it to MD5
private string generaterandomnumber()
{
string Rand1 = RandomString(8);
string Rand2 = RandomString(8);
docNum = Rand1 + "-" + Rand2;
MD5 md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(docNum));
//get hash result after compute it
byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
//Insert the generated value to the database
protected void insert(string q)
{
try
{
conn.Open();
string ins = "insert into mgen_validation_check(md5values) values(#m)";
MySqlCommand cmd = new MySqlCommand(ins, conn);
cmd.Parameters.AddWithValue("#m", q);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://abcd/include/LogoutPage.php");
this.Close();
status = 0;
try
{
conn.Open();
string del = "delete from mgen_validation_check where md5values=#m";
MySqlCommand cmd2 = new MySqlCommand(del, conn);
cmd2.Parameters.AddWithValue("#m", qs);
cmd2.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
private void Window_Closed(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://abcd/include/LogoutPage.php");
try
{
conn.Open();
string delconf = "delete from mgen_validation_check where md5values=#m";
MySqlCommand cmd3 = new MySqlCommand(delconf, conn);
cmd3.Parameters.AddWithValue("#m", docNum);
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
}
}
The app is working properly except when running outlook becomes very slow. Other ms office apps are working properly.
Any help would be helpful.
Thanks in advance

While loop not breaking from signal given by the user in WPF (C#)

I have a WPF which executes a GUI for serial communication. I want to keep triggering the device and recoed the values till the user says stop. I have a global bool variable STOP which I set to false when user presses the stop which in turn should terminate the while loop which triggers the device continuously but the problem is that once the user selects the run button whcih runs the while loop, the WPF app freezes and doesn't accept the STOP button click.
Can someone give me an idea of what is happening here or a any suggestion on how to implement it differently.
Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using Keyence.data_class;
using Microsoft.Win32;
using System.IO;
using Keyence;
using System.Threading;
namespace Keyence
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static string filePath;
public static string fileName;
public static int baudrate = 9600;
public static string thresHold = "60";
public bool STOP = true;
public static char[] buffer = new char[256];
public static string x, y, match;
public static string value;
public static SerialPort port = new SerialPort("COM4", baudrate, Parity.None, 8, StopBits.One);
public MainWindow()
{
InitializeComponent();
//port.DataReceived
//SerialPort port = new SerialPort(COM, baudrate, Parity.None, 8, StopBits.One);
port.Open();
port.NewLine = "\r";
//*******display camera types*****
string[] cameraTypes = new string[] { "CVseries100 ", "CVseries500" , "CVseries700" };
foreach (string cam in cameraTypes)
{
camera_type.Items.Add(cam);
}
//*******select your trigger mode( default is set to NONE)*******
string[] triggerModes = new string[] { "triggerModeNone", "triggerModeDATA", "triggerModeRepeat" };
foreach(string trigger in triggerModes)
{
trigger_mode.Items.Add(trigger);
}
//*****put a default value for thresHold********
threshold_value.Text = thresHold;
//*******add values to the baudrate dropdown********
baud_rate.Items.Add("9600");
baud_rate.Items.Add("19200");
baud_rate.Items.Add("38400");
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
value = sp.ReadTo("\r");
string[] values = value.Split(new char[] { ',' });
x = values[0];
y = values[1];
match = values[2];
}
//public static void get_data()
//{
// port.Write("T");
//}
#region encapsulates all the individuals functions when the user changes settings ( UI interaction functions)
private void get_sample_Click(object sender, RoutedEventArgs e)
{
//write code to read x,y,threshold values in the text boxes
port.Write("T");
//MainWindow.get_data();
x_value.Text = string.Format("{0}", x);
y_value.Text = string.Format("{0}", y);
thresholdvalue.Text = string.Format("{0}", match);
}
#region the method opens a savefileDialog(dataFile) and lets user save the file in which data is stored
public void data_file_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog dataFile = new SaveFileDialog();
dataFile.DefaultExt = ".txt";
dataFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dataFile.RestoreDirectory = true;
dataFile.Title = "select or create a new file";
DateTime currentTime = DateTime.Now;
dataFile.Filter = " Text Document |*.txt | Excel |*.xls";
string datepatt = #"M-d-yy_hh-mm_Data";
string saveDT = currentTime.ToString(datepatt);
dataFile.FileName = saveDT;
Nullable<bool> result = dataFile.ShowDialog();
if (result == true)
{
filePath = dataFile.FileName;
fileName = dataFile.SafeFileName;
}
System.IO.FileStream fs = (System.IO.FileStream)dataFile.OpenFile();
using (StreamWriter Write = new StreamWriter(fs))
{
Write.WriteLine("Wafer Placement Data\n\n");
Write.WriteLine("File Name : {0}\n", fileName);
Write.WriteLine("Port Name : COM4\n");
Write.WriteLine("Threshold : {0}\n", threshold_value.Text);
Write.WriteLine("Date : {0}\n\n", Convert.ToString(DateTime.Now));
//************Print Header to the file******************
Write.WriteLine("\tX\tY\tcorrelation\tDate\n");
}
}
#endregion
#region function called when the threshold value is changed
private void threshold_value_TextChanged(object sender, TextChangedEventArgs e)
{
thresHold = threshold_value.Text;
}
#endregion
#region function to write individual data points on the window for checking
private void writeSample(double X, double Y, double threshold)
{
FileStream file = new FileStream(filePath, FileMode.Append, FileAccess.ReadWrite);
using (StreamWriter Writer = new StreamWriter(file))
{
Writer.WriteLine(DateTime.Now);
Writer.WriteLine("\t X \t Y\t threshold% ");
}
}
#endregion
private void run_button_Click(object sender, RoutedEventArgs e)
{
do
{
port.Write("T");
FileStream file = new FileStream(filePath, FileMode.Append, FileAccess.Write);
Thread.Sleep(500);
using (StreamWriter Writer = new StreamWriter(file))
{
Writer.WriteLine("\t{0}\t{1}\t{2}\t{3}", x, y, match, Convert.ToString(DateTime.Now));
}
port.DiscardInBuffer();
} while (STOP);
}
private void stop_button_Click(object sender, RoutedEventArgs e)
{
STOP = false;
}
private void command_TextChanged(object sender, TextChangedEventArgs e)
{
string C = command.Text;
port.WriteLine(C);
}
#endregion
}
}
You need to run your serial port code in separate thread. In your implementation GUI thread is busy w/ serial port communication that is why your window is frozen. The following article explains exactly what you need:
http://www.ryanvice.net/wpf-3-5/using-backgroundworker-with-wpf/

Categories

Resources