I did a little WPF window with a button and a textBox.
When I click on the button, there is some stuff, then I add some lines to my TextBox.
I often did this kind of apps with Winform and when I did them, the UI refreshed each time the textbox was updated, but not in my WPF application.
So I read about and did binding and used the INotifyPropertyChanged.
public partial class MainWindow : MetroWindow, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private string myValue;
public string MyValue
{
get { return myValue; }
set
{
myValue = value;
RaisePropertyChanged("MyValue");
}
}
private void RaisePropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
//
//.......
//
}
Then my XAML :
<TextBox x:Name="TxtBox_result" Text="{Binding Path=MyValue}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" Margin="30,332,0,0" VerticalAlignment="Top" Width="868" Height="285" TextChanged="TxtBox_result_TextChanged" />
I know there is probably cleaner code to do with MVVM approach but I don't know MVVM but would like to try first to have a simple method to refresh my UI. It's a shame because it was easier in Win32.
Here is the code executed when i click on the button, i update the MyValue on these code but the TextBox only show value when the treatment is over :
private void GenererBases (string DirectoryStd, string DirectorySur)
{
int cpt = 0;
bool bSignatureBaseFound = false;
bool bFirst = true;
string strDirectoryOut = string.Empty;
var files = Directory.GetFiles(DirectorySur, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".txt") || s.EndsWith(".dat"));
MyValue = " ";
MyValue = " > Recherche des fichiers ...." + Environment.NewLine;
foreach (string fileName in files)
{
string line = string.Empty;
string FileNameStandard = string.Empty;
bSignatureBaseFound = false;
MyValue = MyValue + Environment.NewLine + " > Extraction de la signature du fichier base pour : " + System.IO.Path.GetFileName(fileName);
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
while ((line = file.ReadLine()) != null)
{
if (line.Contains("SetModuleInfo('$Id:"))
{
bSignatureBaseFound = true;
int posDebFichier = line.IndexOf("'$Id:") + 6;
int posFinFichier = line.IndexOf(" ", (line.IndexOf("'$Id:") + 6));
FileNameStandard = line.Substring(posDebFichier, posFinFichier-posDebFichier);
if (File.Exists(DirectoryStd+#"\"+FileNameStandard))
{
MyValue = MyValue + Environment.NewLine + " > Fichier base : " + FileNameStandard + " localisé ! > Copie vers le dossier de destination !";
if (bFirst)
{
strDirectoryOut = DirectorySur + #"\Generated_bases_" + DateTime.Now.ToString("yyyyMMddHHmm");
Directory.CreateDirectory(strDirectoryOut);
bFirst = false;
}
cpt++;
if (File.Exists(strDirectoryOut + #"\" + System.IO.Path.GetFileNameWithoutExtension(FileNameStandard) + "_base" + System.IO.Path.GetExtension(FileNameStandard)))
{
File.Delete(strDirectoryOut + #"\" + System.IO.Path.GetFileNameWithoutExtension(FileNameStandard) + "_base" + System.IO.Path.GetExtension(FileNameStandard));
}
File.Copy(DirectoryStd + #"\" + FileNameStandard, strDirectoryOut + #"\" + System.IO.Path.GetFileNameWithoutExtension(FileNameStandard) + "_base" + System.IO.Path.GetExtension(FileNameStandard),true);
File.SetAttributes(strDirectoryOut + #"\" + System.IO.Path.GetFileNameWithoutExtension(FileNameStandard) + "_base" + System.IO.Path.GetExtension(FileNameStandard), File.GetAttributes(strDirectoryOut + #"\" + System.IO.Path.GetFileNameWithoutExtension(FileNameStandard) + "_base" + System.IO.Path.GetExtension(FileNameStandard)) | FileAttributes.Hidden);
}
else
{
MyValue = MyValue + Environment.NewLine + "!!! WARNING!!" + Environment.NewLine + "!!! Fichier base non localisé : " + FileNameStandard + Environment.NewLine;
}
break;
}
}
file.Close();
if (bSignatureBaseFound==false)
{
MyValue = MyValue + Environment.NewLine + "!!! WARNING!!" + Environment.NewLine + "!!! Aucune signature de base localisée pour : " + fileName + Environment.NewLine;
}
}
MyValue = MyValue + Environment.NewLine + "***************************" + Environment.NewLine + "***************************" + Environment.NewLine + " >> Fin du traitement !" + cpt + " fichiers bases générés pour " + files.Count() + " sources surchargés !" + Environment.NewLine + ">> Fichiers bases copiés dans le dossier :" + strDirectoryOut + Environment.NewLine;
}
Thanks a lot
A simple example.
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace Core2022.SO.WalterFabioSimoni
{
public partial class InpcWindow : Window, INotifyPropertyChanged
{
protected bool Set<T>(ref T propertyField, T newValue, [CallerMemberName] string? propertyName = null)
{
if (string.IsNullOrWhiteSpace(propertyName))
throw new ArgumentNullException(nameof(propertyName));
bool notEquals = !Equals(propertyField, newValue);
if (notEquals)
{
propertyField = newValue;
RaisePropertyChanged(propertyName);
}
return notEquals;
}
protected void RaisePropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName ?? string.Empty));
}
public event PropertyChangedEventHandler? PropertyChanged;
}
public partial class AsyncUpdateWindow : InpcWindow
{
public AsyncUpdateWindow()
{
InitializeComponent();
}
private string _myValue = string.Empty;
public string MyValue
{
get => _myValue;
set => Set(ref _myValue, value ?? string.Empty);
}
private static readonly Random random= new Random();
private async void OnRestartAsync(object sender, RoutedEventArgs e)
{
UIElement button = (UIElement)sender;
button.SetCurrentValue(IsEnabledProperty, false);
for (int i = 0; i < 10; i++)
{
MyValue = random.Next(int.MinValue, int.MaxValue).ToString();
await Task.Delay(500);
}
button.InvalidateProperty(IsEnabledProperty);
}
}
}
<local:InpcWindow x:Class="Core2022.SO.WalterFabioSimoni.AsyncUpdateWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Core2022.SO.WalterFabioSimoni"
mc:Ignorable="d"
Title="AsyncUpdateWindow" Height="300" Width="400"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<UniformGrid Columns="1">
<Viewbox>
<TextBlock Text="{Binding MyValue}" Margin="10"/>
</Viewbox>
<Button Content="Restart" Click="OnRestartAsync"/>
</UniformGrid>
</local:InpcWindow>
There are no calls to UI elements in your method code - this is very good.
For your code, you just need to add the following method:
private async void GenererBasesAsync(string DirectoryStd, string DirectorySur)
=> await Task.Run(() => GenererBases(DirectoryStd, DirectorySur));
In the clicker, call this async method.
Related
I have a list made by user input which is bound to a datasource class, I also have a datagridview where the data is supposed to be put into the datagrid.
private void ViewMemo_Load(object sender, EventArgs e)
{
dgvMemo.DataSource = Datasources.memorecorders;
}
this is the AddMemo class
private void btAdd_Click(object sender, EventArgs e)
{
int SerialId;
SerialId = int.Parse(txtSerialId.Text);
decimal price;
price = decimal.Parse(txtPrijs.Text);
MemoRecorder m1 = new MemoRecorder(SerialId);
m1.make = txtMerk.Text;
m1.model = txtModel.Text;
m1.priceExBtw = price;
m1.creationDate = dtProductie.Value;
foreach (MemoCartridgeType mem in Enum.GetValues(typeof(MemoCartridgeType)))
{
if (cbCartridge.SelectedValue.ToString() == mem.ToString())
{
m1.maxCartridgeType = mem;
}
}
Datasources.memorecorders.Add(m1);
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
txtMerk.Text = String.Empty;
txtModel.Text = String.Empty;
txtPrijs.Text = String.Empty;
}
but when I view the datagridview the data is not in there, what did I do wrong?
Datasources.memorecorders.Add(m1);
dgvMemo.DataSource = Datasources.memorecorders;
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
I Have tried many ways to get this to return these values for a project, but I keep getting these problems no matter what way. help please
using System;
using System.Collections.Generic;
namespace MpaintV2.Customer
{
public class Trade : Utilities.Helper
{
//public static List<String> TradeFiles(String TradeName, String TradeAddress, String TradePhone, Double PaintCoverage = 0.0)
//{
public override string ToString(String TradeName, String TradeAddress, String TradePhone, String TradeShape, double PaintCoverage)
{
List<string> FileData = Utilities.Helper.get_file_data();
for (int counter = 0; counter < FileData.Count; counter++)
{
String[] SplitRecord = FileData[counter].Split(',');
if (SplitRecord[0].Equals("Trade"))
{
TradeName = SplitRecord[1];
TradeAddress = SplitRecord[2];
TradePhone = SplitRecord[3];
PaintCoverage = (double.Parse(SplitRecord[4]) / 10.00);
}
//Console.WriteLine(" " + TradeName + " " + TradeAddress + " " + TradePhone + " " + PaintCoverage + "Paints");
}
return TradeName + TradeAddress + TradePhone + TradeShape + PaintCoverage;
}
}
}
I just want to log important things to a logfile just like a .txt.
I created a class ErrorHandling for this. I read error codes from CSV file and add the Text to Console / GUI. Now is the problem, i want to write to the error file from different UserControls, but the console is in the MainWindow. How can i just add the text to my output console from my Class?
This is my ErrorHandling class.
public class ErrorHandling
{
public static Action WriteErrorLog;
private static object writeLock = new object();
public enum errorState
{
INFO, WARNING, CRIT
}
public string getErrorString(int ErrorCode)
{
var errorString = string.Empty;
var reader = new StreamReader(File.OpenRead(#"errorCodes.csv"));
List<string> Codes = new List<string>();
List<string> Error = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
Codes.Add(values[0]);
Error.Add(values[3]);
}
var index = Codes.FindIndex(p => p == ErrorCode.ToString());
if (index == -1)
return "Unbekannter Fehler aufgetreten!";
else
return Error[index] + " (" + Codes[index] + ")";
}
public void addToLogFile(errorState error, int errorCode = 0, string errorText = null)
{
var errorTextResult = error.ToString();
if (errorCode == 0 && errorText == null)
{
return;
}
else if (errorCode != 0 && errorText != null)
{
errorTextResult += " - " + DateTime.Now.ToString();
errorTextResult += " : " + getErrorString(errorCode) + "\n";
errorTextResult += errorText;
}
else if (errorCode != 0 && errorText == null)
{
errorTextResult += " - " + DateTime.Now.ToString();
errorTextResult += " : " + getErrorString(errorCode);
}
else if ( errorCode == 0 && errorText != null)
{
errorTextResult += " - " + DateTime.Now.ToString() + " : ";
errorTextResult += errorText;
}
ThreadPool.QueueUserWorkItem(writeToLogFile, errorTextResult);
}
#region LogDatei schreiben
public static void writeToLogFile(object text)
{
try
{
if (!File.Exists(Properties.Settings.Default.LogFilePath))
{
using(var writer = File.AppendText(Properties.Settings.Default.LogFilePath))
writer.WriteLine(Properties.Settings.Default.LogFilePath, "LatikeManager Logfile " + DateTime.Now.ToString());
}
using (var writer = File.AppendText(Properties.Settings.Default.LogFilePath))
writer.WriteLine(Properties.Settings.Default.LogFilePath, text + "\n");
WriteErrorLog();
}
catch (Exception ex)
{
MessageBox.Show("Fehler beim schreiben der Log Datei : \n" + text + "\n" + ex.ToString());
}
}
#endregion
}
When i just add text from another UserControl, the Action does not fire because it is a new instance from ErrorHandling.
I just found an working resolution.
I am now using the trace method.
Just added this code to my App.conf
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="myTrace" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\LogFile\mytrace.log"></add>
</listeners>
</trace>
</system.diagnostics>
And then used
public static void writeToLogFile(object text)
{
Trace.Write(string.Format("{0}\r\n",text));
}
this Code in my ErrorHandling method. This worked great for me.
I have a code for serial communication, with this code im sending values from textboxes to an device or when im testing to another PC. But when I press my "Program" button I get this error.
System.NullReferenceException was unhandled
Object reference not set to an instance of an object.
And i can catch the exception with an try catch but then i wont send my values to the device connected to my port.
This is my code:
public partial class MainForm : Form
{
private Settings _settings;
private SettingsIniFile _settingsIniFile = new SettingsIniFile();
private StringList _baudratelist = new StringList();
private StringList _systemPorts = new StringList();
private StringList _comportList = new StringList();
private Timer _comtimer = new Timer();
private ComPort _comport;
public MainForm()
{
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
//var portname = GetCurrentComPort();
}
private String GetCurrentComPort()
{
int index = _comPortComboBox.SelectedIndex;
if (index < 0)
return null;
return _comportList[index];
}
private void OnComtimerOnTick(object sender, EventArgs args)
{
foreach (var item in SerialPort.GetPortNames())
{
if (!_systemPorts.Contains(item))
{
_comtimer.Stop();
_systemPorts.Add(item);
LoadComportName();
//MessageBox.Show("The new device is connected to" + item);
_comtimer.Start();
}
}
}
private void LoadSettings(bool defaults)
{
SettingsIniFile iniFile = new SettingsIniFile();
_settings = iniFile.LoadSettings(defaults);
}
private void SaveSettings()
{
SaveTextBoxes();
_settingsIniFile.Save(_settings);
}
private void LoadTextBoxes()
{
//ACR
_startRemovalTextBox.Text = _settings.AcrStartRemoval11;
_removalTimeTextBox.Text = _settings.AcrRemovalTime12;
_removalDelayTextBox.Text = _settings.AcrRemovalDelay13;
//CLEANING
_durCleaningTextbox.Text = _settings.CleanDurCleaning21;
_timeValveOnTextbox.Text = _settings.CleanTimeValveOn22;
_timeValveOffTextBox.Text = _settings.CleanTimeValveOff23;
//CALIBRATE
_contentLeftTextBox.Text = _settings.CalibrateContentLeft31;
_calibrateLeftTextBox.Text = _settings.CalibrateCalibrateLeft33;
_contentRightTextBox.Text = _settings.CalibrateContentRight32;
_calibrateRightTextBox.Text = _settings.CalibrateCalibrateRight34;
//CONDUCTIVITY
_factorLeftTextBox.Text = _settings.ConductFactorLeft41;
_offsetLeftTextBox.Text = _settings.ConductOffsetleft42;
_factorRightTextBox.Text = _settings.ConductFactorRight43;
_offsetRightTextBox.Text = _settings.ConductOffsetRight44;
_levelLeftTextBox.Text = _settings.ConductLevelLeft45;
_levelRightTextBox.Text = _settings.ConductLevelRight46;
//GENERAL
_typeOfValveTextBox.Text = _settings.GeneralTypeOfValve51;
_indicatorTextBox.Text = _settings.GeneralIndicator52;
_inverseOutputTextBox.Text = _settings.GeneralInverseOutput53;
_restartTimeTextBox.Text = _settings.GeneralRestartTime54;
_waterTimeTextBox.Text = _settings.GeneralWaterTime55;
_gateDelayTextbox.Text = _settings.GeneralGateDelay56;
//PULSATION
_pulsationTextBox.Text = _settings.PulsationPulsationPm61;
_ratioFrontTextBox.Text = _settings.PulsationSrRatioFront62;
_ratioBackTextBox.Text = _settings.PulsationSrRatioBack63;
_stimulationTextBox.Text = _settings.PulsationStimulationPm64;
_stimFrontTextBox.Text = _settings.PulsationSrStimFront65;
_stimBackTextBox.Text = _settings.PulsationSrStimBack66;
_stimulationDurTextBox.Text = _settings.PulsationStimulationDur67;
//return _settings;
}
private void SaveTextBoxes()
{
//ACR
_settings.AcrStartRemoval11 = _startRemovalTextBox.Text;
_settings.AcrRemovalTime12 = _removalTimeTextBox.Text;
_settings.AcrRemovalDelay13 = _removalDelayTextBox.Text;
//CLEANING
_settings.CleanDurCleaning21 = _durCleaningTextbox.Text;
_settings.CleanTimeValveOn22 = _timeValveOnTextbox.Text;
_settings.CleanTimeValveOff23 = _timeValveOffTextBox.Text;
//CALIBRATE
_settings.CalibrateContentLeft31 = _contentLeftTextBox.Text;
_settings.CalibrateCalibrateLeft33 = _calibrateLeftTextBox.Text;
_settings.CalibrateContentRight32 = _contentRightTextBox.Text;
_settings.CalibrateCalibrateRight34 = _calibrateRightTextBox.Text;
//CONDUCTIVITY
_settings.ConductFactorLeft41 = _factorLeftTextBox.Text;
_settings.ConductOffsetleft42 = _offsetLeftTextBox.Text;
_settings.ConductFactorRight43 = _factorRightTextBox.Text;
_settings.ConductOffsetRight44 = _offsetRightTextBox.Text;
_settings.ConductLevelLeft45 = _levelLeftTextBox.Text;
_settings.ConductLevelRight46 = _levelRightTextBox.Text;
//GENERAL
_settings.GeneralTypeOfValve51 = _typeOfValveTextBox.Text;
_settings.GeneralIndicator52 = _indicatorTextBox.Text;
_settings.GeneralInverseOutput53 = _inverseOutputTextBox.Text;
_settings.GeneralRestartTime54 = _restartTimeTextBox.Text;
_settings.GeneralWaterTime55 = _waterTimeTextBox.Text;
_settings.GeneralGateDelay56 = _gateDelayTextbox.Text;
//PULSATION
_settings.PulsationPulsationPm61 = _pulsationTextBox.Text;
_settings.PulsationSrRatioFront62 = _ratioFrontTextBox.Text;
_settings.PulsationSrRatioBack63 = _ratioBackTextBox.Text;
_settings.PulsationStimulationPm64 = _stimulationTextBox.Text;
_settings.PulsationSrStimFront65 = _stimFrontTextBox.Text;
_settings.PulsationSrStimBack66 = _stimBackTextBox.Text;
_settings.PulsationStimulationDur67 = _stimulationDurTextBox.Text;
}
private void DefaultSettingButtonClick(object sender, System.EventArgs e)
{
LoadSettings(true);
LoadTextBoxes();
SaveSettings();
LoadComportName();
}
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void LoadComportName()
{
var availablePorts = _systemPorts;
_comPortComboBox.DataSource = null;
if (availablePorts != null && availablePorts.Any())
{
_comPortComboBox.DataSource = availablePorts;
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void SetBaudrate()
{
_baudratelist.Add("4600");
_baudratelist.Add("9600");
_baudratelist.Add("19200");
}
private void SendMessageTest()
{
var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
+ _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
_removalDelayTextBox.Text + "\r\n";
var Cleaningcontent ="["+ _cleaningNamelLabel.Text+"]" +"\r\n"+_cleaningIdLabel21.Text+
_durCleaningTextbox.Text + "\r\n"+ _cleaningLabelId22.Text+
_timeValveOnTextbox.Text + "\r\n"+ _cleaningLabelId23.Text+_timeValveOffTextBox.Text+"\r\n";
var Calibratecontent = "[" +_calibrateNameLabel.Text+ "]"+"\r\n"+_calibrateIDLabel31.Text+_contentLeftTextBox.Text+
"\r\n"+ _calibrateIDLabel32.Text+_calibrateLeftTextBox.Text+"\r\n"+_calibrateIDLabel33.Text+_contentRightTextBox.Text+
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
try
{
_comport.WriteBytes(array);
}
catch(Exception exc)
{
MessageBox.Show("Error {1}: "+ exc);
}
try
{
_comport.ReadBytes(array, array.Length, 1000);
}
catch(Exception exc)
{
MessageBox.Show("Error {2}" + exc);
}
//string result = Encoding.ASCII.GetString(array);
//MessageBox.Show(result);
}
}
This is my code for the communication:
namespace Communication
{
public class ComPort
{
private readonly SerialPort _serialPort;
public ComPort(string portname, int baudRate)
{
_serialPort = new SerialPort();
_serialPort.PortName = portname; <-----
_serialPort.BaudRate = baudRate;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.Handshake = Handshake.None;
// _serialPort.WriteBufferSize = 1;
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
_serialPort.Open();
_serialPort.ReadTimeout = 20000;
_serialPort.WriteTimeout = 20000;
}
public void Clear()
{
while (ReadByte() != -1)
continue;
}
private byte[] _array = new byte[] {0};
public void WriteByte(byte value)
{
_array[0] = value;
_serialPort.Write(_array, 0, 1);
// _serialPort.BaseStream.WriteByte(value);
_serialPort.BaseStream.Flush();
}
public void WriteBytes(byte[] array)
{
_serialPort.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length )
{
_serialPort.Write(array, index, length);
}
private int _readTimeOut = -1;
public int ReadByte(int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
return _serialPort.ReadByte();
// _serialPort.Read(array, 0, 1);
// return array[0];
}
catch (TimeoutException)
{
return -1;
}
}
public int ReadBytes(byte[] array, int length, int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
int bytesRead = 0;
while ( bytesRead < length )
bytesRead += _serialPort.Read(array, bytesRead, length - bytesRead);
// _serialPort.Read(array, 0, 1);
// return array[0];
return bytesRead;
}
catch (TimeoutException)
{
return -1;
}
}
/// <summary>
/// sends string followed by CR - LF
/// </summary>
/// <param name="line"></param>
public void WriteLine(String line)
{
WriteBytes(StringToBytes(line + "\r\n"));
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
public void Close()
{
try
{
_serialPort.DtrEnable = false;
_serialPort.RtsEnable = false;
_serialPort.Close();
}
catch(IOException)
{
}
}
public bool Dtr
{
get { return _serialPort.DtrEnable; }
set { _serialPort.DtrEnable = value; }
}
public bool Rts
{
get { return _serialPort.RtsEnable; }
set { _serialPort.RtsEnable = value; }
}
}
}
Can someone explain to me what the problem is?
Thanks in advance
Possible anwser:
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
_comport = new ComPort("COM6", 9600);
But when i do this another error comes around the corner:
Value cannot be null.
Parameter name: PortName
This comes in the second piece of code where the arrow is.
Probably there is not comport selected at startup, so the _comport never gets created, you should check if the comport is created before you use is: if (_comport != null) ...
Update:
I think you should create a button instead of default connecting on a combobox selection change.
public void buttonConnect_Click(object sender, EventArgs e)
{
// check if the comport is created, else show a message and return,
TryDisconnect();
var portname = GetCurrentComPort();
if (portname == null)
return;
try
{
_comport = new ComPort(portname, 9600);
}
catch(Exception exception)
{
// try to create a better message here :-)
MessageBox.Show("Something went wrong....");
}
}
public void buttonDisconnect_Click(object sender, EventArgs e)
{
TryDisconnect();
}
public void TryDisconnect()
{
if( _comport != null)
{
_comport.Dispose();
_comport = null;
}
}
Also for this:
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
// check the _comPort instance first, if not assigned, leave a message..
if(_comPort == null)
{
MessageBox.Show("The comport is not initialized");
return;
}
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
I got a tip for you, try to separate the markup/construction of the message, here how you could do.
I did not change all the code, only some examples:
I would create a struct/class to hold all information
public struct AcrContentInfo
{
public string AcrName;
public string AcrId11;
public string StartRemoval;
public string AcrId12;
public string RemovalTime;
public string AcrId13;
public string RemovalDelay;
// markup the information:
public override string ToString()
{
return string.Format(
"[{0}]\r\n{1}{2}\r\n{3}{4}\r\n{5}{6}\r\n",
AcrName,
AcrId11, StartRemoval,
AcrId12, RemovalTime,
AcrId13, RemovalDelay);
}
}
private void SendMessageTest()
{
// Instead of:
//var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
// + _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
// _removalDelayTextBox.Text + "\r\n";
// I would use this instead, this way it wil be easier to maintain different versions.
// The code using the struct isn't responsible for markup
// Create the struct and fillin the fields.
AcrContentInfo acrContentInfo = new AcrContentInfo
{
AcrName = _acrNameLabel.Text,
AcrId11 = _acrIdLabel11.Text,
StartRemoval = _startRemovalTextBox.Text,
AcrId12 = _acrIdLabel12.Text,
RemovalTime = _removalTimeTextBox.Text,
AcrId13 = _acrIdLabel13.Text,
RemovalDelay = _removalDelayTextBox.Text
};
// if there is a new version of the protocol, you can create something like this
// AcrContentInfoV2 acrContentInfo = new AcrContentInfoV2
// call the tostring, (create a markup)
var Acrcontent = acrContentInfo.ToString();
// --- old code ---
var Cleaningcontent = "[" + _cleaningNamelLabel.Text + "]" + "\r\n" + _cleaningIdLabel21.Text +
_durCleaningTextbox.Text + "\r\n" + _cleaningLabelId22.Text +
_timeValveOnTextbox.Text + "\r\n" + _cleaningLabelId23.Text + _timeValveOffTextBox.Text + "\r\n";
var Calibratecontent = "[" + _calibrateNameLabel.Text + "]" + "\r\n" + _calibrateIDLabel31.Text + _contentLeftTextBox.Text +
"\r\n" + _calibrateIDLabel32.Text + _calibrateLeftTextBox.Text + "\r\n" + _calibrateIDLabel33.Text + _contentRightTextBox.Text +
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
// instad of:
//byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
// I always try not to make very long lines of code.
// A stringbuilder is much more efficient building strings.
// I would:
StringBuilder sb = new StringBuilder();
sb.AppendLine("2");
sb.AppendLine("Acrcontent");
sb.AppendLine("Cleaningcontent");
sb.AppendLine("Calibratecontent");
sb.AppendLine("Conductcontent");
sb.AppendLine("Generalcontent");
sb.AppendLine("Pulsationcontent");
sb.AppendLine("3");
// why make the comport class responsible for the encoding type. _ComPort.StringToBytes_
byte[] array = Encoding.UTF8.GetBytes(sb.ToString());
try
{
_comport.WriteBytes(array);
// only read when write was succeed?
_comport.ReadBytes(array, array.Length, 1000);
}
catch (Exception exc)
{
MessageBox.Show("Error {1}: " + exc);
}
}
These are only my ideas, and meant to be constructive. (other point of view) Happy codeing..
You have to instantiate _comport before calling a method or accessing a property on it.
maybe in
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
portname is null then _comport not instantiated. you can trace it and check that if it has a value or not.
Yes assign a value to _comport like
_comport=null;
Hi i am working on pdf to xhtml conversion using pdf clown library(C#).I am extracting the pdf content,the images which i extracted is inverted image.I want the real images,please any suggestions?..
The code is pasted 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 it.stefanochizzolini.clown.documents;
using it.stefanochizzolini.clown.files;
using it.stefanochizzolini.clown.documents.contents;
using it.stefanochizzolini.clown.documents.contents.objects;
using it.stefanochizzolini.clown.tools;
using it.stefanochizzolini.clown.documents.contents.composition;
using it.stefanochizzolini.clown.documents.contents.fonts;
using System.IO;
using it.stefanochizzolini.clown.bytes;
using it.stefanochizzolini.clown.objects;
namespace Test1
{
public partial class Form1 : Form
{
public int index;
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files|*.pdf";
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnProcess_Click(object sender, EventArgs e)
{
InitiateProcess(txtFileName.Text.Trim());
}
private void InitiateProcess(string FileName)
{
it.stefanochizzolini.clown.files.File file;
Document document;
try
{
// Open the PDF file!
file = new it.stefanochizzolini.clown.files.File(FileName);
// Get the PDF document!
document = file.Document;
//file.Dispose();
}
catch
{
MessageBox.Show("Sorry. Error in File");
return;
}
//Page stamper is used to draw contents on existing pages.
PageStamper stamper = new PageStamper();
foreach (Page page in document.Pages)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + "\nScanning page " + (page.Index + 1) + "...\n";
stamper.Page = page;
// Wraps the page contents into a scanner.
Extract(new ContentScanner(page), stamper.Foreground, page );
stamper.Flush();
this.Refresh();
}
}
private void Extract(ContentScanner level, PrimitiveFilter builder, Page page)
{
string ctype = string.Empty;
if (level == null)
return;
while (level.MoveNext())
{
ContentObject content = level.Current;
//TextExtractor extractor = new TextExtractor();
string aa = content.GetType().ToString();
/*if(content is Text)
{
txtOutput.Text = txtOutput.Text + aa + Environment.NewLine;
List<ITextString> textStrings = extractor.Extract(page)[TextExtractor.DefaultArea];
foreach(ITextString textstring in textStrings)
{
RectangleF textstringbox=textstring.Box.Value;
txtOutput.Text = txtOutput.Text + "x:" + Math.Round(textstringbox.X);
txtOutput.Text = txtOutput.Text + "y:" + Math.Round(textstringbox.Y) + ",";
txtOutput.Text = txtOutput.Text + "w:" + Math.Round(textstringbox.Width) + ",";
txtOutput.Text = txtOutput.Text + "h:" + Math.Round(textstringbox.Height);
txtOutput.Text=txtOutput.Text+ "]: " + textstring.Text.ToString();
}
}*/
if (content is Text)
{
ContentScanner.TextWrapper text = (ContentScanner.TextWrapper)level.CurrentWrapper;
//ContentScanner.GraphicsState test = level.getState();
foreach (ContentScanner.TextStringWrapper textString in text.TextStrings)
{
RectangleF rf = (RectangleF)textString.Box;
/*txtOutput.Text = txtOutput.Text + Environment.NewLine + "Text [font size: " + textString.Style.FontSize + " ],[font Name: " +
textString.Style.Font.Name + " ]: " + textString.Text + "[position = left :" + rf.Left.ToString() + " & Top: " + rf.Top.ToString() + "X:" + rf.X.ToString() + "Y:" + rf.Y.ToString();*/
txtOutput.Text = txtOutput.Text + Environment.NewLine + textString.Text;
}
}
//else if (content is MarkedContent)
//{
// //MarkedContent mc = (MarkedContent) content
//}
else if (content is ShowText)
{
it.stefanochizzolini.clown.documents.contents.fonts.Font font = level.State.Font;
txtOutput.Text = txtOutput.Text + (font.Decode(((ShowText)content).Text));
}
else if (content is ContainerObject)
{
// Scan the inner level!
Extract(level.ChildLevel, builder, page);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.InlineImage)
{
ContentScanner.InlineImageWrapper img = (ContentScanner.InlineImageWrapper)level.CurrentWrapper;
ExportImage(
img.InlineImage.Body.Value,
txtOutputPath.Text.Trim() + System.IO.Path.DirectorySeparatorChar + "ImageExtractionSample_" + (index++) + ".jpg"
);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.GraphicsObject)
{
/*=============================================================================
* TO EXTRACT THE GRAPHICAL OBJECT WITHIN THE PDF
=============================================================================*/
ContentScanner.GraphicsObjectWrapper objectWrapper = level.CurrentWrapper;
if (objectWrapper == null)
{
continue;
}
/*
NOTE: Images can be represented on a page either as
external objects (XObject) or inline objects.
*/
SizeF? imageSize = null; // Image native size.
/*if (objectWrapper is PdfDataObject)
{
ContentScanner.GraphicsObjectWrapper gobjectwrapper=(ContentScanner.GraphicsObjectWrapper)gobjectwrapper;
it.stefanochizzolini.clown.objects.PdfDataObject pdobjt=gobjectwrapper
}*/
//if(objectWrapper is Image)
//{
// }
if (objectWrapper is ContentScanner.XObjectWrapper)
{
ContentScanner.XObjectWrapper xObjectWrapper = (ContentScanner.XObjectWrapper)objectWrapper;
it.stefanochizzolini.clown.documents.contents.xObjects.XObject Xobject = xObjectWrapper.XObject;
// Is the external object an image?
if (Xobject is it.stefanochizzolini.clown.documents.contents.xObjects.ImageXObject)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine +
"External Image '" + xObjectWrapper.Name + "' (" + Xobject.BaseObject + ")"; // Image key and indirect reference.
imageSize = Xobject.Size; // Image native size.
PdfDataObject dataObject = Xobject.BaseDataObject;
;
PdfDictionary header = ((PdfStream)dataObject).Header;
if (header.ContainsKey(PdfName.Type) && header[PdfName.Type].Equals(PdfName.XObject) && header[PdfName.Subtype].Equals(PdfName.Image))
{
if (header[PdfName.Filter].Equals(PdfName.Image)) // JPEG image.
{
// Get the image data (keeping it encoded)!
IBuffer body1 = ((PdfStream)dataObject).GetBody(false);
//object h1 = PdfName.ColorSpace;
// Export the image!
ExportImage(
body1,
txtOutputPath.Text + System.IO.Path.DirectorySeparatorChar + "Image_" + (index++) + ".png"
);
}
}
}
else if (content is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
Dictionary<RectangleF?, List<ITextString>> textStrings = null;
PageAnnotations annotations = page.Annotations;
TextExtractor extractor = new TextExtractor();
if (annotations == null)
{
Console.WriteLine("No annotations here.");
continue;
}
foreach (it.stefanochizzolini.clown.documents.interaction.annotations.Annotation annotation in annotations)
{
if (annotation is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
if (textStrings == null)
{ textStrings = extractor.Extract(page); }
it.stefanochizzolini.clown.documents.interaction.annotations.Link link = (it.stefanochizzolini.clown.documents.interaction.annotations.Link)annotation;
RectangleF linkBox = link.Box;
StringBuilder linkTextBuilder = new StringBuilder();
foreach (ITextString linkTextString in extractor.Filter(textStrings, linkBox))
{ linkTextBuilder.Append(linkTextString.Text); }
string bb = linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + "Link '" + linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + " Position: "
+ "x:" + Math.Round(linkBox.X) + ","
+ "y:" + Math.Round(linkBox.Y) + ","
+ "w:" + Math.Round(linkBox.Width) + ","
+ "h:" + Math.Round(linkBox.Height);
}
}
}
else if (objectWrapper is ContentScanner.InlineImageWrapper)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + "Inline Image";
InlineImage inlineImage = ((ContentScanner.InlineImageWrapper)objectWrapper).InlineImage;
imageSize = inlineImage.Size; // Image native size.
}
if (imageSize.HasValue)
{
RectangleF box = objectWrapper.Box.Value; // Image position (location and size) on the page.
txtOutput.Text = txtOutput.Text + Environment.NewLine +
" on page " + (page.Index + 1) + " (" + page.BaseObject + ")"; // Page index and indirect reference.
txtOutput.Text = txtOutput.Text + Environment.NewLine + " Coordinates:";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " x: " + Math.Round(box.X);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " y: " + Math.Round(box.Y);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " width: " + Math.Round(box.Width) + " (native: " + Math.Round(imageSize.Value.Width) + ")";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " height: " + Math.Round(box.Height) + " (native: " + Math.Round(imageSize.Value.Height) + ")";
}
/*=============================================================================*/
}
}
}
}
private void ExportImage(IBuffer data, string outputPath)
{
FileStream outputStream;
try
{ outputStream = new FileStream(outputPath, FileMode.CreateNew); }
catch (Exception e)
{ throw new Exception(outputPath + " file couldn't be created.", e); }
try
{
BinaryWriter writer = new BinaryWriter(outputStream);
//ImageConverter ic = new ImageConverter();
//Image img = (Image)ic.ConvertFrom(data);
writer.Write(data.ToByteArray());
writer.Close();
outputStream.Close();
}
catch (Exception e)
{ throw new Exception(outputPath + " file writing has failed.", e); }
Console.WriteLine("Output: " + outputPath);
}
private void txtOutputPath_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnBrowseOutput_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
txtOutputPath.Text = folderBrowserDialog1.SelectedPath;
}
private void btnsave_Click(object sender, EventArgs e)
{
if(txtOutput.Text=="")
{
MessageBox.Show("text box is empty");
}
else
{
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter yaz = new StreamWriter(saveFileDialog1.FileName.ToString());
string yasoutput = txtOutput.Text;
yaz.Write(yasoutput);
}
}
}
private void btncancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnclear_Click(object sender, EventArgs e)
{
txtFileName.Text = "";
txtOutput.Text = "";
txtOutputPath.Text = "";
}
}
}
You would need to invert the image buffer i.e copy the image buffer that you receive to a new buffer starting from the last byte of the image buffer to the first byte of the image buffer. This should take care of the inverted image. The for each pixel data, assuming 24-bit RGB values, swap the R and B values such that RGB becomes BGR. This should get rid of the 'negative' effect and save this new buffer.
Pass your bitmap image to the below function...
private byte[] BmpToBytes_Unsafe (Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0,0,IMAGE_WIDTH,IMAGE_HEIGHT),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
int lineSize = bData.Width * 3;
int byteCount = lineSize * bData.Height;
byte[] bmpBytes = new byte[byteCount];
byte[] tempLine = new byte[lineSize];
int bmpIndex = 0;
IntPtr scan = new IntPtr(bData.Scan0.ToInt32() + (lineSize * (bData.Height-1)));
for (int i = 0; i < bData.Height; i++)
{
Marshal.Copy(scan, tempLine, 0, lineSize);
scan = new IntPtr(scan.ToInt32()-bData.Stride);
tempLine.CopyTo(bmpBytes, bmpIndex);
bmpIndex += lineSize;
}
bmp.UnlockBits(bData);
return bmpBytes;
}
Happy coding...:)