Message Box Pops up more than once - c#

I have the following code, the timerStart method that will call some functions every second, the problem is when the condition is true in checkSigning method, the pop up appears more than once.. How can i possibly fix this? Can someone help me :<
public void timerStart()
{
DispatcherTimer updaterTimer = new DispatcherTimer();
updaterTimer.Tick += new EventHandler(updaterTimer_Tick);
updaterTimer.Interval = new TimeSpan(0, 0, 1);
updaterTimer.Start();
}
private void updaterTimer_Tick(object sender, EventArgs e)
{
Time.Content = "Time : " + DateTime.Now.ToLongTimeString();
exist = saved_settings();
if (exist)
{
settingForToday();
checkSigningAvailable();
setSigning(signingAvailable = getSigning());
}
else
{
ongoing.Content = "Event : No Event";
sign_in.Content = "Sign-in Time : ";
sign_out.Content = "Sign-out Time : ";
}
}
public void checkSigningAvailable()
{
if (dt_signing_in.CompareTo(DateTime.Now) < 0)
{
if ((!InisOver && signing.Equals("in")) || (!InisOver && signing.Equals("in_out") && !OutisOver))
{
disableSigningIn(OutisOver.ToString(),this.event_id);
}
}
if (dt_signing_out.CompareTo(DateTime.Now) < 0)
{
if ((!OutisOver && signing.Equals("out")) || (!OutisOver && signing.Equals("in_out") && InisOver))
{
disableSigningOut(InisOver.ToString(),this.event_id);
}
}
}
public void disableSigningOut(string In,string event_id)
{
MessageBox.Show("Signing out is over!", "No more signing out!", MessageBoxButton.OK, MessageBoxImage.Information);
connection.Open();
string sign = In + ",True";
string query = "update data_storage set data_details = '" + sign + "' where data_name = 'Signing';";
NpgsqlCommand command = new NpgsqlCommand(query, connection);
NpgsqlDataReader dr = command.ExecuteReader();
dr.Close();
connection.Close();
sign_out.Content = "Sign-out Time : Over";
string query2 = concatQuery(getIDnumberAttendance(event_id));
updateAbsences(query2);
}

You can Stop the timer while you execute the tick and start it again on the end. The only down side you will have is that the time will be measure form the moment you finish you updaterTimer_Tick execution - but you may also consider it as a benefit.
private void updaterTimer_Tick(object sender, EventArgs e)
{
updaterTimer.Stop();
Time.Content = "Time : " + DateTime.Now.ToLongTimeString();
exist = saved_settings();
if (exist)
{
settingForToday();
checkSigningAvailable();
setSigning(signingAvailable = getSigning());
}
else
{
ongoing.Content = "Event : No Event";
sign_in.Content = "Sign-in Time : ";
sign_out.Content = "Sign-out Time : ";
}
updaterTimer.Start();
}

Related

How to know when SQL query has finished

I´m trying to create a logic to update massively the column "Prices" from table "Products".
This logic is made, but in my C# code I send the command to the MS Access DB, and immediately I want to show the new results.
The problem is that the update query takes a few seconds to finish, and my C# instantaneously asks for the Select from Products, showing no changes.
The main question is how I can know when the update has finished to show the new results in the grid.
Here my code:
private void btnAceptar_Click(object sender, EventArgs e)
{
string operator;
int code = Convert.ToInt32(cmbcode .SelectedValue);
int material = Convert.ToInt32(cmbMaterial.SelectedValue);
int productType= Convert.ToInt32(cmbproductType.SelectedValue);
if (cmboperating.SelectedIndex == 0){ operator= "+"; }
else if (cmboperating.SelectedIndex == 1) { operator= "-"; }
else if (cmboperating.SelectedIndex == 2) { operator= "*"; }
else { operator= "/"; }
if(txtValoroperating.Text != "") { txtValoroperating.Text = (txtValoroperating.Text).Replace(",", "."); }
string operating = txtValoroperating.Text;
if(rdPrecioDeLista.Checked == true & cbTodasPiezas.Checked == true)
{
//Here is my problem
oProductsDAL.modifyPricesMassively(operating, operator);
txtValoroperating.Text = null;
fillGridProducts();
}
}
And oProductsDAL.modifyPricesMassively(operating, operator) does this:
public bool modifyPricesMassively(operating, operator)
{
if (operating!= "" & operator!= "")
{
return conexion.executeMethod("UPDATE Piezas SET Precio = Precio " +operator+" " +operating);
}
else
{
return false;
}
}
conexion.executeMethod does this:
public bool conexion.executeMethod(string strComando)
{
try
{
OleDbCommand Comando = new OleDbCommand();
Comando.CommandText = strComando;
Comando.Connection = this.establecerConexion();
Conexion.Open();
Comando.ExecuteNonQuery();
Conexion.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show("No se pudo establecer conexion con la base de datos" +ex);
return false;
}
}
I wish to show a progress bar or a gif loading icon.

How Stop the timer after check rows in a database in c#?

I have a method that check for records in a database and a timer that starts the method every 10 seconds. I check if a new record was inserted in a table and get these values to send emails.
The problem is, if has sended the email 1 time, it is no stop the timer and sends email every 10 seconds. To "solve" this i used an IF to check if the ID of the table was different, and partially i "resolved" the problem. And now, there is a new problem, because the result of the Select with joins query, returns much values and only the ID of that table is repeated, but the other fields are not, like this image:
As you can see, the ID of the table is 16, but the other ID are 2, 3, 4.
With my first solution, only sends email to the first row and ignore the others rows. Thats my problem, because i need to sends emails to the other rows. How can i do that?
This is my code (i use Windows Service):
public partial class GaxTankAlerts : ServiceBase
{
private string conn = "Data Source=.;Initial Catalog=DBCatalog;Integrated Security=false;User ID=GAX;Password=****;";
private Timer scheduleTimer = null;
private bool bandera;
private string id = "";
private string estatusAlerta = "";
private DateTime fechaAlerta;
public GaxTankAlerts()
{
InitializeComponent();
if (!EventLog.SourceExists("AlertService"))
{
EventLog.CreateEventSource("AlertService", "AlertLog");
}
eventLogEmail.Source = "AlertService";
eventLogEmail.Log = "AlertLog";
scheduleTimer = new Timer();
scheduleTimer.Interval = 10000;
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
bandera = true;
scheduleTimer.Start();
eventLogEmail.WriteEntry("El servicio ha iniciado");
//GetAlerts();
}
protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//if (bandera == true) {
// GetAlerts();
// //lastRun = DateTime.Now;
// bandera = false;
//}
eventLogEmail.WriteEntry("Comprobando si hay registros nuevos...");
if (bandera == true)
{
GetAlerts();
}
}
public void GetAlerts()
{
var path = AppDomain.CurrentDomain.BaseDirectory + "EmailTemplate\\Email.html";
string body = File.ReadAllText(path);
try
{
using (SqlConnection con = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("[General].[GetAlertas]", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
{
if (dr.HasRows)
{
while (dr.Read())
{
if (dr["ID"].ToString() != id)
{
id = dr["ID"].ToString();
if (dr["EstatusAlerta"].ToString() != estatusAlerta)
{
estatusAlerta = dr["EstatusAlerta"].ToString();
using (MailMessage mm = new MailMessage())
{
//Sends emails
}
}
}
//if (dr["EstatusAlerta"].ToString() != idReg)
//{
// idReg = dr["EstatusAlerta"].ToString();
// bandera = true;
//}
//else {
// bandera = false;
//}
}
}
}
dr.Close();
con.Close();
}
}
catch (Exception ex)
{
eventLogEmail.WriteEntry(ex.Message.ToString());
}
}
Thank you.

c# BeginInvoke doesn't work

I have this code
private delegate void InvokeDelegate();
private void OpenFormNewNote(object sender, FileSystemEventArgs e)
{
if(loop == 2)
{
string service = null;
if (currentServiceName != null)
{
service = currentServiceName.Replace(" ", "");
}
NewNotePanel newNote = new NewNotePanel(e.FullPath, service, listOfService, Path, MyConn, ipAddress, imgFolder, Utente_id);
newNote.TopMost = true;
watcher.EnableRaisingEvents = false;
var result = newNote.ShowDialog();
if(result == DialogResult.OK || result == DialogResult.Cancel)
{
watcher.EnableRaisingEvents = true;
if(result == DialogResult.OK)
{
this.BeginInvoke(new InvokeDelegate(Refresh));
}
}
loop = 0;
}
else
{
loop++;
}
}
And this is the Refresh() Function:
public void Refresh()
{
noteContainer.Controls.Clear();
page = 0;
try
{
string Query = "SELECT a, v, b, cFROM note Where Servizio_ID = " + asd+ " AND Visibile = 1 order by ID desc limit 15 OFFSET " + (pageIndex * page) + " ;";
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MySqlDataReader MyReader;
if (MyConn.State == ConnectionState.Open)
{
MyReader = MyCommand.ExecuteReader();// Here our query will be executed and data saved into the database.
while (MyReader.Read())
{
CreateNotePreview(MyReader.GetString("a"), MyReader.GetString("b"), MyReader.GetString("c"), MyReader.GetString("d"));
}
MyReader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Since OpenFormNewNote is called when the "Change" event of FileSystemWatcher is triggered.. of course it runs on a separated thread. Instead Refresh() does some UI stuff and it can't be called directly from OpenFormNewNote() otherwise it gives a Cross-Thread exception. So I tried with delegate but when the codeflow arrives on the BeginInvoke part.. Nothing happens and the Refresh function is not called.
What should I do?

Multithread using backgroundworker and event handler

I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response

textbox and dropdown values inserted should store in database using c# asp.net

I got a tab container which has 4 tabs in it. In one of the tab named ADD TASK I got few fields like
(Task Name: --txtbox
Client Name:--drpdwn
Begin Date:--txtbox wid calendar
Due Date:--txtbox wid calendar
Description:--txtbox
Assign To:--drpdown
Status:--drpdown
% Complete:--drpdown)
and an ADD and CANCEL button in the end.
On running the project and inserting the values to those above mentioned fields i will click the add button and after clicking the button the values should store in my DATABASE. i have table named TASK in my DB already.
Please help me with the back end code.
here is my code
protected void BtnAdd_Click(object sender, EventArgs e)
{
MTMSDTO objc = new MTMSDTO();
int Flag = 0;
objc.TaskName = Session["TaskName"].ToString();
objc.ClientName = DrpClientName.SelectedItem.Text;
objc.BeginDate = Convert.ToDateTime(TxtBeginDate.Text);
objc.DueDate = Convert.ToDateTime(TxtDueDate.Text);
objc.Description = Session["Description"].ToString();
objc.AssignTo = DrpAssignTo.SelectedItem.Text;
objc.Status = DrpStatus.SelectedItem.Text;
objc.PercentageComplete = Convert.ToInt32(DrpPercentageComplete.Text);
int X = obj.InsertTask(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Data Added Successfully";
Panel2.Visible = false;
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Add Data!!!";
}
}
im using layered architecture and i have this code on my ACCESS file of DAL CLASS
public int InsertTask(MTMSDTO M)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#TaskID", M.TaskID);
objParam.Direction = ParameterDirection.Output;
db.Parameters.Add(new SqlParameter("#TaskName", M.TaskName));
db.Parameters.Add(new SqlParameter("#ClientName", M.ClientName));
db.Parameters.Add(new SqlParameter("#BeginDate", M.BeginDate));
db.Parameters.Add(new SqlParameter("#DueDate", M.DueDate));
db.Parameters.Add(new SqlParameter("#Description", M.Description));
db.Parameters.Add(new SqlParameter("#AssignTo", M.AssignTo));
db.Parameters.Add(new SqlParameter("#Status", M.Status));
db.Parameters.Add(new SqlParameter("#PercentageComplete", M.PercentageComplete));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("InsertTask");
if (retval >= 1)
{
return int.Parse(objParam.Value.ToString());
}
else
{
return -1;
}
}
the code is edited now but im getting error as "object reference not set to an instance of an object. " for the line (objc.TaskName = Session["TaskName"].ToString();) which is in BtnAdd_Cick.
Shouldn't your BtnAdd_Click function be something like this instead? You don't currently seem to be calling the InsertTask() function.
protected void BtnAdd_Click(object sender, EventArgs e) {
MTMSDTO m = new MTMSDTO();
m.TaskName = TxtTaskName.Text;
m.ClientName = DrpClientName.Text;
m.BeginDate = TxtBeginDate.Text;
m.DueDate = TxtDueDate.Text;
m.Description = TxtDescription.Text;
m.AssignTo = DrpAssignTo.Text;
m.Status = DrpStatus.Text;
m.PercentageComplete = DrpPercentageComplete.Text;
InsertTask(m);
}
get all values in back end and pass to this function
public bool InsertRecord(string strTableName, string strColumn_Name, string strValues)
{
SqlConnection OBJCONNECTION;
StringBuilder strbQuery;
SqlCommand cmd;
try
{
OBJCONNECTION= new SqlConnection();
OBJCONNECTION.ConnectionString = ConfigurationManager.ConnectionStrings["Basic_ADO"].ConnectionString;//get connection string from web.config file
OBJCONNECTION=
strbQuery = new StringBuilder();
strbQuery.Append("INSERT INTO ");
strbQuery.Append(strTableName);
strbQuery.Append("(" + strColumn_Name + ")");
//strbQuery.Append(" VALUES");
strbQuery.Append("(" + strValues + ")");
cmd = new SqlCommand(strbQuery.ToString(), OBJCONNECTION);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex) { throw ex; }
finally { strbQuery = null; cmd = null;OBJCONNECTION.close();}
}

Categories

Resources