I've made a Windows Form using C# and I'm trying to read serial DATA from RS232 serial port. But when I try to connect the device with PC through serial port. Device connected successfully but nothing is being received on the serial port through RS232.
Here is the main 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.IO;
using System.IO.Ports;
using WindowsFormsApp1;
using System.Data.SQLite;
using System.Windows.Forms.DataVisualization.Charting;
namespace Weight_Scale
{
public partial class FormWeightScale : Form
{
string weight;
string dbFile = "BundleInstances.db";
bundle bundle1 = new bundle();
int h = 0 , m = 0, s = 0 ;
public FormWeightScale()
{
InitializeComponent();
PageWeightScale();
if (!File.Exists(dbFile))
{
SQLiteConnection.CreateFile(dbFile);
}
//----------------- Queries ----------------------//
string createTable = "CREATE TABLE IF NOT EXISTS bundle" +
"(ID integer PrimaryKey AutoIncreament Unique Not Null," +
"Date VARCHAR, Time VARCHAR, Size VARCHAR, BarGrade VARCHAR," +
"Length VARCHAR, HeatNumber VARCHAR, WeightZeroLevel VARCHAR," +
"WeightReadingLevel VARCHAR, BundleMaxWeight VARCHAR, Weight integer)";
bundle1.setQueryCreateTable(createTable);
bundle.createTable();
setData();
displayData();
var ports = SerialPort.GetPortNames();
ComboBoxPort.DataSource= ports;
ProgressBarConnection.Value = 0;
}
void setData()
{
bundle1.setDateQuery(DateTimePickerWeight.Value.ToString("dd-MM-yyyy"));
}
void displayData()
{
dataGridWeightInstances.DataSource = bundle.readTable();
chartWeight.DataSource = bundle.readTable();
chartWeight.Series["Weight"].Points.Clear();
chartWeight.Series["Weight"].XValueMember = "Date";
chartWeight.Series["Weight"].XValueMember = "Time";
chartWeight.Series["Weight"].YValueMembers = "Weight";
labelPerDayProduction.Text = bundle.totalPerDayProduction.ToString("000.0");
}
private void BtnConnect_Click(object sender, EventArgs e)
{
if (ComboBoxPort.SelectedIndex > -1)
{
if(BtnConnect.Text == "Connect")
{
MessageBox.Show(String.Format("You selected port '{0}'", ComboBoxPort.SelectedItem), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Connection(ComboBoxPort.SelectedItem.ToString());
}
else
{
MessageBox.Show("Please select a port first");
}
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
serialPort1.Close();
ProgressBarConnection.Value=0;
Application.Exit();
}
private void ConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
{
PageConfiguration();
}
private void WeightScaleToolStripMenuItem_Click(object sender, EventArgs e)
{
PageWeightScale();
}
private void ComboBoxPort_TextChanged(object sender, EventArgs e)
{
string[] sport = SerialPort.GetPortNames();
toolStripComboBoxPort.Items.AddRange(sport);
}
private void FormWeightScale_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
}
//--------------------------- Function for Connecting to Serial Port ----------------------------//
private void Connection(string portName)
{
if (BtnConnect.Text == "Connect")
{
try
{
serialPort1.PortName = portName;
serialPort1.BaudRate = Convert.ToInt32(comboBoxBaudRate.Text);
serialPort1.DataBits = Convert.ToInt32(comboBoxDataBits.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBoxParity.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBoxStopBits.Text);
//serialPort1.RtsEnable= true;
//serialPort1.DtrEnable= true;
serialPort1.Open();
Console.WriteLine("Connection is open");
ProgressBarConnection.Value = 100;
BtnConnect.Text = "Disconnect";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
serialPort1.Close();
BtnConnect.Text = "Connect";
ProgressBarConnection.Value = 0;
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
weight = serialPort1.ReadLine();
this.Invoke(new EventHandler(ShowData));
if(int.Parse(weight.ToString()) >= int.Parse(textBoxReadingLevel.Text))
{
this.Invoke(new EventHandler(setBundleData));
string insertQuery = "INSERT INTO bundle (ID , Date , Time , Size , BarGrade," +
"Length , HeatNumber , WeightZeroLevel , WeightReadingLevel ," +
"BundleMaxWeight , Weight )" +
"VALUES (#ID , #date ,#time , #barSize , #barGrade , #bundleLength , #bundleHeatNumber ," +
"#bundleWeightZeroLevel , #bundleWeightReadingLevel , #bundleMaxWeight , #bundleWeight)";
bundle1.setQueryInsertRow(insertQuery);
bundle.insertRow();
this.Invoke(new EventHandler(displayDataOnGridChart));
}
}
private void displayDataOnGridChart(object sender, EventArgs e)
{
labelPerDayProduction.Text = bundle.totalPerDayProduction.ToString("000.0");
dataGridWeightInstances.DataSource = bundle.readTable();
chartWeight.DataSource = bundle.readTable();
chartWeight.Series["Weight"].Points.Clear();
chartWeight.Series["Weight"].XValueMember = "Date";
chartWeight.Series["Weight"].XValueMember = "Time";
chartWeight.Series["Weight"].YValueMembers = "Weight";
}
private void setBundleData(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
bundle1.setDateQuery(DateTimePickerWeight.Value.ToString("dd-MM-yyyy"));
bundle1.setDate(dt.ToString("dd-MM-yyyy"));
bundle1.setTime(dt.ToString("HH:mm-tt"));
bundle1.setBarSize(ComboBoxBarSize.SelectedItem.ToString());
bundle1.setBarGrade(ComboBoxBarGrade.SelectedItem.ToString());
bundle1.setBundleLength(TextBoxCutLength.Text);
bundle1.setBundleHeatNumber(textBoxHeatNumber.Text);
bundle1.setBundleWeightZeroLevel(textBoxZeroLevel.Text);
bundle1.setBundleWeightReadingLevel(textBoxReadingLevel.Text);
bundle1.setBundleMaxWeight(textBoxMaxWeight.Text);
bundle1.setBundleWeight(int.Parse(weight.ToString()));
}
private void ShowData(object sender, EventArgs e)
{
TimerWeight.Stop();
h = 0; m = 0; s = 0;
LabelWeight.Text = weight.ToString();
TimerWeight.Interval = 1000;
TimerWeight.Start();
}
private void ComboBoxBarSize_MouseEnter(object sender, EventArgs e)
{
//ComboBoxBarSize.Text = "";
}
private void ComboBoxBarSize_MouseClick(object sender, MouseEventArgs e)
{
ComboBoxBarSize.Text = "";
}
private void ComboBoxBarSize_MouseLeave(object sender, EventArgs e)
{
ComboBoxBarSize.Text = "Bar Size";
}
private void ComboBoxPort_MouseHover(object sender, EventArgs e)
{
string[] sport = SerialPort.GetPortNames();
toolStripComboBoxPort.Items.AddRange(sport);
}
//------------------------ Functions for PAGES -------------------------//
private void PageConfiguration()
{
DateTimePickerWeight.Hide();
labelBarSize.Hide();
labelBarGrade.Hide();
labelBarCutLength.Hide();
labelHeatNumber.Hide();
labelZeroLevel.Hide();
labelReadingLevel.Hide();
labelMaxWeight.Hide();
LabelWeight.Hide();
labelStableWeightCounter.Hide();
labelPerDayProduction.Hide();
ComboBoxBarSize.Hide();
ComboBoxBarGrade.Hide();
TextBoxCutLength.Hide();
textBoxHeatNumber.Hide();
textBoxZeroLevel.Hide();
textBoxReadingLevel.Hide();
textBoxMaxWeight.Hide();
checkBoxBarSize.Hide();
checkBoxBarGrade.Hide();
checkBoxBarCutLength.Hide();
checkBoxHeatNumber.Hide();
comboBoxChartType.Hide();
chartWeight.Hide();
dataGridWeightInstances.Hide();
labelPort.Show();
labelBaudRate.Show();
labelParity.Show();
labelDataBits.Show();
labelStopBits.Show();
ComboBoxPort.Show();
comboBoxBaudRate.Show();
comboBoxParity.Show();
comboBoxDataBits.Show();
comboBoxStopBits.Show();
BtnConnect.Show();
}
private void PageWeightScale()
{
DateTimePickerWeight.Show();
labelBarSize.Show();
labelBarGrade.Show();
labelBarCutLength.Show();
labelHeatNumber.Show();
labelZeroLevel.Show();
labelReadingLevel.Show();
labelMaxWeight.Show();
LabelWeight.Show();
labelStableWeightCounter.Show();
labelPerDayProduction.Show();
ComboBoxBarSize.Show();
ComboBoxBarGrade.Show();
TextBoxCutLength.Show();
textBoxHeatNumber.Show();
textBoxZeroLevel.Show();
textBoxReadingLevel.Show();
textBoxMaxWeight.Show();
checkBoxBarSize.Show();
checkBoxBarGrade.Show();
checkBoxBarCutLength.Show();
checkBoxHeatNumber.Show();
comboBoxChartType.Show();
chartWeight.Show();
dataGridWeightInstances.Show();
labelPort.Hide();
labelBaudRate.Hide();
labelParity.Hide();
labelDataBits.Hide();
labelStopBits.Hide();
ComboBoxPort.Hide();
comboBoxBaudRate.Hide();
comboBoxParity.Hide();
comboBoxDataBits.Hide();
comboBoxStopBits.Hide();
BtnConnect.Hide();
if (ComboBoxBarSize.Text == "")
{
ComboBoxBarSize.Text = "Bar Size";
}
if (ComboBoxBarGrade.Text == "")
{
ComboBoxBarGrade.Text = "Bar Grade";
}
}
private void DateTimePickerWeight_ValueChanged(object sender, EventArgs e)
{
setData();
displayData();
}
private void DateTimePickerWeight_MouseDown(object sender, MouseEventArgs e)
{
setData();
displayData();
}
private void comboBoxChartType_SelectedValueChanged(object sender, EventArgs e)
{
chartWeight.Series["Weight"].ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), comboBoxChartType.Text);
}
private void TimerWeight_Tick(object sender, EventArgs e)
{
if (int.Parse(weight.ToString()) >= int.Parse(textBoxReadingLevel.Text))
{
s += 1;
if (s == 60)
{
s = 0;
m += 1;
if (m == 60)
{
h += 1;
}
}
labelStableWeightCounter.Text = string.Format("{0}:{1}:{2}", h.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'));
}
}
}
}
Here is the Class of bundles
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
internal class bundle
{
// ------------------------- Variables for DATABASE DATA ---------------------//
public static int bundleID;
public static string date;
public static string time;
public static string barSize;
public static string barGrade;
public static string bundleLength;
public static string bundleHeatNumber;
public static string bundleWeightZeroLevel;
public static string bundleWeightReadingLevel;
public static string bundleMaxWeight;
public static int bundleWeight;
// ------------------------- Variables for Queries ---------------------//
public static double totalPerDayProduction;
public static string dateQuery;
public static string dbFile = "Data Source = BundleInstances.db; Version = 3";
public static string queryCreateTable;
public static string queryInsertRow;
public static string queryReadDataGrid;
public static SQLiteDataReader reader;
//---------------- Constructor ----------------//
public bundle() { }
//---------------- Set the Variable of the Class ----------------//
public string setDate(string dt)
{
date = dt;
return date;
}
public string setTime(string t)
{
time = t;
return time;
}
public int setbundleID(int bID)
{
bundleID = bID;
return bundleID;
}
public string setBarSize(string bSize)
{
barSize = bSize;
return barSize;
}
public string setBarGrade(string bGrade)
{
barGrade = bGrade;
return barGrade;
}
public string setBundleLength(string bLength)
{
bundleLength = bLength;
return bundleLength;
}
public string setBundleHeatNumber(string bHeatNumber)
{
bundleHeatNumber = bHeatNumber;
return bundleHeatNumber;
}
public string setBundleWeightZeroLevel(string bWeightZeroLevel)
{
bundleWeightZeroLevel = bWeightZeroLevel;
return bundleWeightZeroLevel;
}
public string setBundleWeightReadingLevel(string bWeightReadingLevel)
{
bundleWeightReadingLevel = bWeightReadingLevel;
return bundleWeightReadingLevel;
}
public string setBundleMaxWeight(string bMaxWeight)
{
bundleMaxWeight = bMaxWeight;
return bundleMaxWeight;
}
public int setBundleWeight(int bWeight)
{
bundleWeight = bWeight;
return bundleWeight;
}
public string setDateQuery(string dt)
{
dateQuery = dt;
return dateQuery;
}
//---------------- Set Query strings of Class ----------------//
public string setQueryCreateTable(string qCreateTable)
{
queryCreateTable = qCreateTable;
return queryCreateTable;
}
public string setQueryInsertRow(string qInsertRow)
{
queryInsertRow = qInsertRow;
return queryInsertRow;
}
public string setQueryReadDataGrid(string qReadDataGrid)
{
queryReadDataGrid = qReadDataGrid;
return queryReadDataGrid;
}
//---------------- Queries Section ----------------//
//---------------- Create Table ----------------//
public static void createTable()
{
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(queryCreateTable, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
//---------------- Insert Record ----------------//
public static void insertRow()
{
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand getIDcmd = new SQLiteCommand("SELECT MAX(ID) FROM bundle", dbConnection);
object maxID = getIDcmd.ExecuteScalar();
if (maxID.ToString() == "")
{
bundleID = 1;
}
else
{
bundleID = int.Parse(maxID.ToString());
bundleID++;
}
SQLiteCommand command = new SQLiteCommand(queryInsertRow, dbConnection);
command.Parameters.AddWithValue("#ID", bundleID++);
command.Parameters.AddWithValue("#date", date);
command.Parameters.AddWithValue("#time", time);
command.Parameters.AddWithValue("#barSize", barSize);
command.Parameters.AddWithValue("#barGrade", barGrade);
command.Parameters.AddWithValue("#bundleLength", bundleLength);
command.Parameters.AddWithValue("#bundleHeatNumber", bundleHeatNumber);
command.Parameters.AddWithValue("#bundleWeightZeroLevel", bundleWeightZeroLevel);
command.Parameters.AddWithValue("#bundleWeightReadingLevel", bundleWeightReadingLevel);
command.Parameters.AddWithValue("#bundleMaxWeight", bundleMaxWeight);
command.Parameters.AddWithValue("#bundleWeight", bundleWeight);
command.ExecuteNonQuery();
dbConnection.Close();
}
//---------------- Data Reader ----------------//
public static DataTable readTable()
{
DataTable dt = new DataTable();
string dbFile = "Data Source = BundleInstances.db; Version = 3";
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand getMaxWeightcmd = new SQLiteCommand("SELECT SUM(Weight) FROM bundle WHERE Date = #dateQuery", dbConnection);
getMaxWeightcmd.Parameters.AddWithValue("#dateQuery", dateQuery);
object weightSum = getMaxWeightcmd.ExecuteScalar();
if(weightSum.ToString() != "")
{
totalPerDayProduction = Convert.ToDouble(weightSum.ToString()) / 1000;
}
else
{
totalPerDayProduction = 0;
}
string readTable = "SELECT Date , Time , Size , Length, Weight FROM bundle WHERE Date = #dateQuery ORDER BY ID DESC";
SQLiteCommand command = new SQLiteCommand(readTable, dbConnection);
command.Parameters.AddWithValue("#dateQuery", dateQuery);
reader = command.ExecuteReader();
dt.Load(reader);
dbConnection.Close();
return dt;
}
}
}
Here is the picture of Form1.cs[Design]
Form1.cs[Design]
Here is Configuration Page:
Configuration
Weight Scale Page is:
Weight Scale
Picture of Connection of RS232 PC Side:
PC Side DB9 Connector
Picture of Connection of RS232 Device Side:
Device Side Connector Connection
The received value should be displayed on the LABEL. At present, 2080 is the TEXT Value.
The port setting is displayed here:
I try this code with arduino MEGA2560. This winform is receiving DATA serially when connected with Arduino.
I have SignalR ASP.NET Core project and trying to send message tp specific user which I manage to do so. The problem is same message send n time n=number of tabs or connections when ever there is change from database it send notification to that certain User but duplicate the message.
public class MessageHub: Hub
{
public MessageHub(IConfiguration cc, IHubContext<MessageHub> _mess, UserManager<ApplicationUser> rep)
{
mess = _mess;
_conf = cc;
_usermanager = rep;
RegisterNotification();
}
public void RegisterNotification()
{
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlCommand, con);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
cmd.Notification = null;
SqlDependency sqlDep = new SqlDependency(cmd);
sqlDep.OnChange += sqlDep_OnChange;
using (SqlDataReader reader = cmd.ExecuteReader())
{
// nothing need to add here now
}
}
}
static int count = 1;
private void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change )
{
SqlDependency sqlDep = sender as SqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
mess.Clients.User("64ed09d7-255f-4aae-a25f-7a50e59943b4").SendAsync("abc", "hello"+count);
count += 1;
RegisterNotification();
}
}
}
as you have mentioned, the problem is RegisterNotification is being called everytime an instance of MessageHub is created. Instead of this, you can create background service and register to SqlDependency there and send the events using IHubContext. And after every notification, you call RegisterNotification again, which might cause the duplication as well.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services
https://learn.microsoft.com/en-us/aspnet/core/signalr/hubcontext
I haven't tested this code, but here is an example:
public class EventBroadcaster : IHostedService
{
private readonly IHubContext<MessageHub> _hubContext;
private readonly string _connectionString;
public EventBroadcaster(
IConfiguration configuration,
IHubContext<MessageHub> hubContext)
{
_hubContext = hubContext;
_connectionString = // Get Connection String from configuration
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Started event broadcasting service");
RegisterNotification();
return Task.CompletedTask;
}
public void RegisterNotification()
{
using (SqlConnection con = new SqlConnection(_connectionString))
{
SqlCommand cmd = new SqlCommand(sqlCommand, con);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
cmd.Notification = null;
SqlDependency sqlDep = new SqlDependency(cmd);
sqlDep.OnChange += sqlDep_OnChange;
using (SqlDataReader reader = cmd.ExecuteReader())
{
// nothing need to add here now
}
}
}
static int count = 1;
private async void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change )
{
SqlDependency sqlDep = sender as SqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
await _hubContext.Clients.User("64ed09d7-255f-4aae-a25f-7a50e59943b4").SendAsync("abc", "hello"+count);
count += 1;
}
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Event Broadcasting Service is stopping.");
// TODO: Stop listening to SqlDependency notifications
return Task.CompletedTask;
}
I want to make button enabled, depending on what data is in SQL table. I made table with boolean type column and now I want WPF to read it and make button enabled or disabled. I made class for connection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows;
using System.Data.SqlClient;
using System.Configuration;
namespace WpfCalendar.Classes
{
class SQLconnection
{
public static string GetConnectionStrings()
{
string strConString = ConfigurationManager.ConnectionStrings["conString"].ToString();
return strConString;
}
public static string sql;
public static SqlConnection con = new SqlConnection();
public static SqlCommand cmd = new SqlCommand("",con);
public static SqlDataReader rd;
public static DataTable dt;
public static SqlDataAdapter da;
public static void openConnection()
{
try
{
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = GetConnectionStrings();
con.Open();
}
}
catch (Exception ex)
{
MessageBox.Show("Brak połaczenia" + Environment.NewLine + ex.Message.ToString(), "C# WPF connect to SQL server", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public static void closeConnection()
{
try
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
catch(Exception)
{
}
}
}
}
And my window xaml.cs
public partial class Kalendarz : Window
{
public Kalendarz()
{
InitializeComponent();
}
private void Sprawdzanko1(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Now;
bool klikniente;
SQLconnection.openConnection();
SQLconnection.cmd.CommandText = SQLconnection.sql;
SQLconnection.sql = "Select [Otwarte] FROM Okienka WHERE Dzien LIKE '1';";
SQLconnection.cmd.CommandType = CommandType.Text;
SQLconnection.da = new SqlDataAdapter(SQLconnection.cmd);
klikniente = (bool)SQLconnection.cmd.ExecuteScalar();
if (klikniente == true && dt.Day == 1 && dt.Month == 12)
{
b1.IsEnabled = true;
}
else
{
b1.IsEnabled = false;
}
SQLconnection.closeConnection();
}
I'm making a WPF advent calendar so the idea is to check if the button was clicked before and if date is correct. But the buttons don't react an I'm pretty sure the code isn't even executed...
Ok so I think I got it. It works so I'm fine with it :D
private void Sprawdzanko1()
{
bool klikniente;
using (SQLconnection.con)
{
SQLconnection.openConnection();
SqlCommand cmd = new SqlCommand("Select [Otwarte] FROM Okienka WHERE Dzien LIKE '1';", SQLconnection.con);
klikniente = (bool)cmd.ExecuteScalar();
SQLconnection.closeConnection();
}
if (klikniente == false && dt.Day == 1 && dt.Month == 12)
{
b1.IsEnabled = true;
}
else
{
b1.IsEnabled = false;
}
}
And then you call Sprawdzanko1();
Good day, friends, help to finalize this class, here's the thing:
I'm trying to make it so that if there is no connection to the database, one action will be performed in the form, there will be a connection to the database, we perform another action.
Now the problem is that if you do not connect to the database, there will be terrible lags of the application itself.
using System;
using MySql.Data.MySqlClient;
namespace Launcher.SupportClass
{
public class Web_MysqlDataBase : IDisposable
{
MySqlConnection connection = new MySqlConnection("server=127.0.0.1;port=3306;username=root;password=1234;database=test-test;");
public bool Connection_BD;
public void OpenConnect()
{
if (connection.State == System.Data.ConnectionState.Closed)
{
try
{
connection.Open();
CheckConnect();
}
catch
{
CheckConnect();
}
finally
{
CheckConnect();
closedConnection();
}
}
}
public void closedConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
public MySqlConnection getConnection()
{
return connection;
}
public void Dispose()
{
Dispose(true);
}
public void CheckConnect()
{
if (connection.State == System.Data.ConnectionState.Open)
{
Connection_BD = true;
}
if (connection.State == System.Data.ConnectionState.Closed)
{
Connection_BD = false;
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Close();
connection = null;
Dispose();
}
}
}
}
}
Next, I want to perform this simple construction, but there are already errors, what am I doing wrong?
Web_MysqlDataBase bd = new Web_MysqlDataBase();
bd.OpenConnect();
string query = "SELECT `text_update` FROM `launcher` WHERE `opened`='1'";
MySqlCommand command = new MySqlCommand(query, bd.getConnection());
if (bd.Connection_BD == true)
{
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
string name = command.ExecuteScalar().ToString();
ScrollingLeable.Text = name;
ScrollingLeable.position = 750;
ScrollsLeable.Visible = true;
ScrollingLeable.Visible = true;
}
else
{
ScrollsLeable.Visible = false;
ScrollingLeable.Visible = false;
}
}
else
{
ScrollsLeable.Visible = false;
ScrollingLeable.Visible = false;
}
I have a very basic service
using System.ServiceProcess;
using System.Timers;
using SystemTimer = System.Timers.Timer;
using System.Net;
using System.Data.SqlClient;
using System;
namespace ServiceThatConnectsToADb
{
public class LrcArchiver : ServiceBase
{
private static SystemTimer PageLoadTimer = new SystemTimer(5000);
public LrcArchiver()
{
ServiceName = "SO Archiver";
CanStop = true;
CanPauseAndContinue = true;
AutoLog = true;
PageLoadTimer.Elapsed += new ElapsedEventHandler(WritePageToDb);
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry(ServiceName + " started");
}
protected override void OnStop()
{
EventLog.WriteEntry(ServiceName + " stopped");
PageLoadTimer.Enabled = false;
}
protected void WritePageToDb(object source, ElapsedEventArgs e)
{
try
{
string html;
using(WebClient client = new WebClient())
{
html = client.DownloadString("http://stackoverflow.com");
}
EventLog.WriteEntry("html = " + html.Substring(0, 100));
using(SqlConnection connection = new SqlConnection("Data Source=DESKTOP-300NQR3\\SQLEXPRESS;Initial Catalog=SoArchive;Integrated Security=True"))
{
string nonQuery = $"INSERT INTO [dbo].[Homepage] ([Html]) VALUES ('{html}')";
using(SqlCommand command = new SqlCommand(nonQuery, connection))
{
bool succeeded = command.ExecuteNonQuery() == 1;
EventLog.WriteEntry(succeeded ? "Saved!" : "Not Saved");
}
}
}
catch(Exception ex)
{
EventLog.WriteEntry("uh-oh! " + ex.Message);
}
}
}
class Program
{
static void Main(string[] args)
{
ServiceBase.Run(new LrcArchiver());
}
}
}
which I've installed and started, but the WritePageToDb method doesn't appear to be firing as none of its WriteEntrys are showing. I see
SO Archiver started
but nothing after that.
Any idea why this is or how I can debug to find the cause?
You are only setting it to work, but you're not starting the timer.
protected override void OnStart(string[] args)
{
PageLoadTimer.Enabled = true;
EventLog.WriteEntry(ServiceName + " started");
}
Try this, i had a problem at some point in time, this works for me. The timer is set for 1 min in this part example
TimerCallback callbacktimer;
Timer IntervalCheck;
protected override void OnStart(string[] args) {
try {
callbacktimer = new TimerCallback(SomeMethode);
IntervalCheck = new Timer(callbacktimer, null, TimeSpan.Zero, new TimeSpan(0, 1, 0));
base.OnStart(args);
} catch (Exception ex) {
}
}
private void SomeMethode(object o) {
}