I have a program that ping and take all the ip address that are active in a LAN i code it with csharp console mode the problem is that when I put it in mode form an error appear in Spinwatch and a error message box appear
Here is the code and error below
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.Net.NetworkInformation;
using System.Threading;
namespace pingagediffusiontest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{ }
private static List<Ping> pingers = new List<Ping>();
private static int instances = 0;
private static object #lock = new object();
private static int result = 0;
private static int timeOut = 250;
private static int ttl = 5;
static void Mains()
{
string baseIP = "192.168.1.";
Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);
CreatePingers(255);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data= enc.GetBytes("abababababababababababababababab");
SpinWait wait = new SpinWait();
int cnt = 1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers) {
lock (#lock) {
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
cnt += 1;
}
while (instances > 0) {
wait.SpinOnce();
}
watch.Stop();
DestroyPingers();
Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
Console.ReadKey();
}
public static void Ping_completed(object s, PingCompletedEventArgs e)
{
lock (#lock) {
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success) {
Console.WriteLine(string.Concat("Active IP: ", e.Reply.Address.ToString()));
result += 1;
} else {
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
}
}
private static void CreatePingers(int cnt)
{
for (int i = 1; i <= cnt; i++) {
Ping p = new Ping();
p.PingCompleted += Ping_completed;
pingers.Add(p);
}
}
private static void DestroyPingers()
{
foreach (Ping p in pingers) {
p.PingCompleted -= Ping_completed;
p.Dispose();
}
pingers.Clear();
}
}
}
Error 1 The type or namespace name 'SpinWait' could not be found
Error 3 The type or namespace name 'Stopwatch' could not be found
Error 4 The name 'Stopwatch' does not exist in the current context
Just add the
using System.Diagnostics;
At the top of your file.
Error 3 The type or namespace name 'Stopwatch' could not be found
You need to import following namespace to use StopWatch in your program:
using System.Diagnostics;
as suggested by #CodeCaster in comments - you are missing semicolon to terminate the Console.WriteLine() statement :
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString())) //missing semicolon
Suggestion : as you have stated you converted code from Console Application to Windows Forms Application it would be nice if you can change/replace all Console.WriteLine() Statements with MessageBox.Show() as shown below:
MessageBox.Show(String.Concat("Non-active IP: ", e.Reply.Address.ToString()));
Related
I am a C # amateur I am not a professional developer and would like to ask my colleagues for help, I would like to make a C # program that connects to an SSH server. Then, depending on the selected value in combobox, the program downloads the appropriate string and I would like to send it to the ssh server to the specified path path and save the value from the string to the file;)
I tried to rewrite the code but something did not work out and I stopped in my place ;( Can anyone help me. Thanks in advance for your help.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using Renci.SshNet;
namespace FileGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SshClient sshClient = new SshClient("192.168.1.22", 22, "root", "pass");
sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
sshClient.Connect();
ShellStream shellStreamSSH = sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
Thread thread = new Thread(() => recvSSHData(shellStreamSSH));
thread.Start();
//I don't know how to get the information if it is connected correctly and change e.g. btnConnect label to Connected.
}
public static void recvSSHData(ShellStream shellStreamSSH)
{
while (true)
{
try
{
if (shellStreamSSH != null && shellStreamSSH.DataAvailable)
{
string strData = shellStreamSSH.Read();
}
}
catch
{
}
System.Threading.Thread.Sleep(200);
}
}
string data1 = "data1";
string data2 = "data2";
string data3 = "data3";
string check;
string path = "/home/test01/desktop";
string filename = "test.txt";
private void btnSend_Click(object sender, EventArgs e)
{
if (cmbData.SelectedIndex == 0)
{
check = data1;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 1)
{
check = data2;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 2)
{
check = data3;
MessageBox.Show(check);
}
else
{
MessageBox.Show("Choose a value");
}
//And now there should be an instruction that sends a string check to the server to path to file replacing its contents
}
}
}
Ok, I coped with everything but I am on the last step, how to save the contents of string to a file using client scp ??
string text= "bal bla bla bla bla"
string path = "#/home/test01/desktop/";
string filename = "test1.txt"
...
try
{
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(text));
scpClient.Upload(mStrm, path + filename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have error:
Renci.SshNet.Common.ScpException: scp: error: unexpected filename:
w Renci.SshNet.ScpClient.CheckReturnCode(Stream input)
w Renci.SshNet.ScpClient.UploadFileModeAndName(IChannelSession channel, Stream input, Int64 fileSize, String serverFileName)
w Renci.SshNet.ScpClient.Upload(Stream source, String path)
w FileGenerator.Form1.btnSend_Click(Object sender, EventArgs e) w C:\Users\backu\source\repos\FileGenerator\FileGenerator\Form1.cs:wiersz 192
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.
I have a problem. I made a service which monitoring printing jobs in real time. It didn't worked perfect, but I had no big problem. Now I need to change service into Windows Forms program. And I've got a problem with threads.
Error:
System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'
This error appears on string "PrintQueue.Refresh()".
I can't find where the other thread tries to run.
I tried to set the other thread and start it with MonitoringJobs() procedure but it doesn't 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;
using System.Collections.Concurrent;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ServiceProcess;
using System.Management;
using System.Windows;
using System.Printing;
using System.Configuration;
using System.Collections.Specialized;
using System.Threading;
namespace MonitoringPrintJobs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer.Elapsed += GetJobs;
timer.AutoReset = true;
timer.Enabled = true;
}
System.Timers.Timer timer = new System.Timers.Timer(5);
int writeInterval = 1000;
int DefaultWriteInterval = 1000;
bool Logging;
SelectPrinter fSelectPrinter = new SelectPrinter();
ConcurrentDictionary<string, string> QueueJobs = new ConcurrentDictionary<string, string>();//declaration printers jobs dictionary
ConcurrentDictionary<string, DateTime> PrintedJobs = new ConcurrentDictionary<string, DateTime>();
PrintServer printServer = null;
PrintQueueCollection QueuesOnLocalServer = null;
List<PrintQueue> queues = new List<PrintQueue>();
public void MonitoringJobs()
{
//if(queues != null)
foreach (var PrintQueue in queues)
{
PrintQueue.Refresh();
using (var jobs = PrintQueue.GetPrintJobInfoCollection())//wait until collection updates!!!
foreach (var job in jobs)
{
if (!QueueJobs.ContainsKey(job.Name))//if list with printer jobs doesn't contain found job (name)
{//then put name in list with printer jobs
QueueJobs.TryAdd(job.Name, job.JobStatus.ToString());
if (Logging == true)
{
File.AppendAllText(#"D:\Logs\Logging.txt", String.Format("{0} - {1} - {2}{3}", DateTime.Now, job.Name, job.JobStatus, Environment.NewLine));
}
}
else//if list with printer jobs contains found job name
{
if (QueueJobs[job.Name] != job.JobStatus.ToString() && !QueueJobs[job.Name].ToLower().Contains("error"))//if status for this job doesn't exist
{
QueueJobs[job.Name] = job.JobStatus.ToString();//replace job's status
if (Logging == true)
{
File.AppendAllText(#"D:\Logs\Logging.txt", String.Format("{0} - {1} - {2}{3}", DateTime.Now, job.Name, job.JobStatus, Environment.NewLine));
}
}
if (job.JobStatus.ToString().ToLower().Contains("error") && PrintedJobs.ContainsKey(job.Name))
{
var someVar = new DateTime();
PrintedJobs.TryRemove(job.Name, out someVar);
}
}
if (QueueJobs[job.Name].ToLower().Contains("print") && !QueueJobs[job.Name].ToLower().Contains("error"))//if successfully printed
{
PrintedJobs.TryAdd(job.Name, DateTime.Now);
}
}
}
}
private void GetJobs(Object source, System.EventArgs e)
{
writeInterval--;
MonitoringJobs();
if (writeInterval <= 0)
{
writeInterval = DefaultWriteInterval;
PrintedJobs.Clear();
QueueJobs.Clear();
}
}
protected void OnStart()
{
QueuesOnLocalServer = printServer.GetPrintQueues();
writeInterval = 120000;
foreach (var item in fSelectPrinter.SelectetPrinters)
Logging = true;
foreach (var printer in fSelectPrinter.SelectetPrinters)
{
if (string.IsNullOrEmpty(printer))
{
timer.Stop();
Environment.Exit(0);
}
var queue = QueuesOnLocalServer.FirstOrDefault(o => o.FullName.ToUpper() == printer.ToUpper());
if (queue == null)
{
timer.Stop();
Environment.Exit(0);
}
queues.Add(queue);
}
timer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
fSelectPrinter.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
printServer = new PrintServer();
foreach (PrintQueue pq in printServer.GetPrintQueues())
fSelectPrinter.listBox1.Items.Add(pq.Name);
}
private void button1_Click_1(object sender, EventArgs e)
{
bool StartPrinting = button2.Enabled = false;//turn of select printers form button
if (StartPrinting == false)//StartPrinting == monitoring == true
{
OnStart();
}
else
{
StartPrinting = true;//StartPrinting == monitoring == false
timer.Stop();
}
}
}
}
In this program I tried to get printing jobs statuses and output them in listbox1 and write results with string.Format in file.
On Form1_Load event you are adding things to your fSelectedPrinter.Listbox.
If you items you are adding are coming from a different thread, that will cause an error. Only UI thread can update objects on a form without using SynchornizationContext.
private readonly SynchronizationContext synchronizationContext;
InitializeComponent();
synchronizationContext = SynchronizationContext.Current;
Here is an example:
private async void btnListFiles1_Click(object sender, EventArgs e)
{
if (txtDirectory1.Text == "")
{
MessageBox.Show(InfoDialog.SELECT_DIRECTORY,PROGRAM_NAME);
return;
}
if (!Directory.Exists(txtDirectory1.Text))
{
MessageBox.Show(InfoDialog.DIRECTORY_NOT_EXIST, PROGRAM_NAME);
return;
}
try
{
string fileTypes = (txtFileTypes1.Text == "") ? "" : txtFileTypes1.Text;
string[] files = Directory.GetFiles(txtDirectory1.Text.TrimEnd(),
(fileTypes == "") ? "*.*" : fileTypes,
(chkSub1.Checked) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
listBoxFiles.Items.Clear();
progressBar.Step = 1;
progressBar.Value = 1;
progressBar.Maximum = files.Length + 1;
listBoxFiles.BeginUpdate();
if (txtSearchPattern1.Text != "")
{
string searchPattern = txtSearchPattern1.Text.ToLower();
await System.Threading.Tasks.Task.Run(() =>
{
foreach (string file in files)
{
if (file.ToLower().Contains(searchPattern))
{
AddToListBox(file);
}
}
});
}
else
{
await System.Threading.Tasks.Task.Run(() =>
{
foreach(string file in files)
{
AddToListBox(file);
}
});
}
listBoxFiles.EndUpdate();
progressBar.Value = 0;
}
private void AddToListBox(string item)
{
synchronizationContext.Send(new SendOrPostCallback(o =>
{
listBoxFiles.Items.Add((string)o);
progressBar.Value++;
}), item);
}
New to WinForms but not ASP.NET or C#. Trying to make client/server app. Successfully received data from client on server but having troubles displaying it on server program winform. Codes are:
Server App code:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace Server_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
TcpListenerEx listener = new TcpListenerEx(ep); //set host to listen
if (!listener.Active)
{
listener.Start();
}
while (true)
{
const int byteSize = 1024 * 1024;
byte[] message = new byte[byteSize];
var s = listener.AcceptTcpClient();
s.GetStream().Read(message, 0, byteSize); //obtaining network stream and receiving data through .Read()
message = cleanMessage(message);
string g = System.Text.Encoding.UTF8.GetString(message);
addMessage(g);
}
}
private void addMessage(string m)
{
this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;
}
private byte[] cleanMessage(byte[] rawMessageByte)
{
byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
return cleanMessage;
}
}
}
Client App code:
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClientApp
{
public partial class ClientApp : Form
{
public ClientApp()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var message = System.Text.Encoding.UTF8.GetBytes(txtFromClient.Text);
using (var client = new TcpClient("127.0.0.1", 1234))//make connection with the host
{
NetworkStream stream = client.GetStream();/*obtain network stream*/
stream.Write(message, 0, message.Length);
}
}
private void textBox1_Click(object sender, EventArgs e)
{
txtFromClient.Text = "";
}
}
}
Everything is happening as planned except for displaying received data on server program's Form1's textbox. On debugging, I confirmed the correct value received in variable m of line this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;. Only problem is that this value cannot be displayed and hence seen on the Form1 of server program.
With the help and guidance from #AdrianoRepetti, solution to the given problem was furnished through the following code:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Linq;
namespace Server_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync(ep); //called to start a process on the worker thread and send argument (listener) to our workerprocess.
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
IPEndPoint ep = e.Argument as IPEndPoint;
TcpListenerEx listener = new TcpListenerEx(ep);
if (!listener.Active)
{
listener.Start();
}
while (true)
{
try
{
const int byteSize = 1024 * 1024;
byte[] message = new byte[byteSize];
using (var s = listener.AcceptTcpClient())
{
s.GetStream().Read(message, 0, byteSize);//obtaining network stream and receiving data through .Read()
message = cleanMessage(message);
string g = System.Text.Encoding.UTF8.GetString(message);
backgroundWorker1.ReportProgress(0, g);
}
}
catch (Exception ex)
{
backgroundWorker1.ReportProgress(0, ex.Message);
}
finally
{
listener.Stop();
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
textBox1.AppendText(Environment.NewLine + ">> " + e.UserState);
}
private byte[] cleanMessage(byte[] rawMessageByte)
{
byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
return cleanMessage;
}
}
}
Hope it helps.
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.