I think the issue here should be addressed by the
architecture of your WinForm solution. I'd try to achieve "separation of concerns" by something like this:
First, I'd have a LogEntry Class:
public class LogEntry
{
public string Entry { set; get; }
public DateTime Timestamp { set; get; }
public LogEntry(string str)
{
Entry = str;
Timestamp = DateTime.Now;
}
}
I'd use a static Log manager class:
public static class LogManager
{
public static LogForm TheLogForm { set; get; }
public static List<logentry> LogEntries { set; get; }
static LogManager()
{
TheLogForm = new LogForm();
LogEntries = new List<logentry>();
}
public static void LogEvent(string str)
{
LogEntry newEntry = new LogEntry(str);
LogEntries.Add(newEntry);
}
public static void DisplayAllLogEntries()
{
TheLogForm.Show();
}
}
How would this work in practice ? Here's a sample Main Form:
#define UseLogging // look up Preprocessor Directives
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace January_18_WithLogForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#if UseLogging
SerialPortManager.ThePort = new SerialPort("Port1");
#endif
}
private void button1_Click(object sender, EventArgs e)
{
#if UseLogging
LogManager.LogEvent("button1 click");
#else
Console.Writeline("button1 click");
#endif
}
private void button2_Click(object sender, EventArgs e)
{
#if UseLogging
LogManager.DisplayAllLogEntries();
#endif
}
}
}
Here the Preprocessor Directive #define UseLogging; controls whether code will be executed at run-time.
In the LogForm 'Load Event, I'd write code to access the LogManager.LogEntries, and do the right thing to display it in the LogForm, let the user edit it, save the changes to LogManager.LogEntries, etc.
Finally, I'd have a SerialPort manager class:
using System.IO;
using System.IO.Ports;
public static class SerialPortManager
{
public static SerialPort ThePort { set; get; }
public static void Write(byte[] buffer, int offset, int count)
{
ThePort.Write(buffer, offset, count);
}
public static void Write(string str)
{
ThePort.Write(str);
}
}
Why use Properties in the LogManager and LogEntry classes ?: imho, makes serialization "cleaner:" I predict you will want to serialize the Entries, which is very easy to do using WCF.
The key idea here is to separate your concerns out into code modules which you can then ... to some extent ... design/test in isolation before testing how they work together.