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?
Related
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.
I have a problem in using ProgressBar while my program does PING. Error says that "This BackgroundWorker is currently busy and cannot run multiple tasks concurrently". Can anyone help me ? These are what I have done
private void ProsesSemuaKamera()
{
Stopwatch watch = Stopwatch.StartNew();
Ping ping = new Ping();
PingReply pingreply;
BackgroundWorker BWKamera = new BackgroundWorker();
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
kon.Open();
string selecturl = "select * from datakamera";
command.CommandText = selecturl;
OleDbDataReader bacadata = command.ExecuteReader();
/* PING Kamera IP */
while (bacadata.Read())
{
pingreply = ping.Send(bacadata["ipadd"].ToString());
BWKamera.WorkerReportsProgress = true;
BWKamera.DoWork += BWKamera_DoWork;
BWKamera.ProgressChanged += BWKamera_ProgressChanged;
BWKamera.RunWorkerAsync(); //error exists here
if (pingreply.Status == IPStatus.Success)
{
listBox1.Items.Add(bacadata["namakamera"].ToString());
if (CaptureSemuaKamera == null)
{
try
{
CaptureSemuaKamera = new Capture(bacadata["urlkamera"].ToString());
}
catch (NullReferenceException ex)
{
MessageBox.Show(ex.Message);
}
}
if (CaptureSemuaKamera != null)
{
Application.Idle += new EventHandler(ProcessFrameSemuaKamera);
}
}
else if (pingreply.Status != IPStatus.Success)
{
listBox2.Items.Add(bacadata["namakamera"].ToString());
}
watch.Stop();
File.AppendAllText(#"D:\Dokumen\Alfon\TA Alfon\Waktu Eksekusi Ping.txt", "Waktu eksekusi ping " + DateTime.Now + " :" + " " + watch.Elapsed.TotalMilliseconds.ToString() + Environment.NewLine);
}
kon.Close();
}
private void BWKamera_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 1000; i++)
{
BWKamera.ReportProgress(i);
Thread.Sleep(1000);
}
}
private void BWKamera_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBarKamera.Value = e.ProgressPercentage;
StatusKamera.Text = "Please Wait...";
}
private void BWKamera_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
StatusKamera.Text = "Done !";
}
Since it is in a while loop. I will assume that the first background worker has not completed and you are telling it to run again on the same instance.
OleDbDataReader bacadata = command.ExecuteReader();
BWKamera.WorkerReportsProgress = true;
BWKamera.DoWork += BWKamera_DoWork;
BWKamera.ProgressChanged += BWKamera_ProgressChanged;
BWKamera.RunWorkerAsync(bacadata);
then the background worker code would look like this:
private void BWKamera_DoWork(object sender, DoWorkEventArgs e)
{
OleDbDataReader bacadata = (OleDbDataReader)e.Argument;
while (bacadata.Read())
{
pingreply = ping.Send(bacadata["ipadd"].ToString());
I have the code below which works fine when the Session state is InProc. However when the Session state is Sql Server, HandleCallback never gets called. How do I change the code so HandleCallBack gets called?
private void TAdata(object sender, EventArgs e)
{
if (((Form)sender).DialogResult == DialogResult.No)
{
return;
}
if (Changed)
{
MessageBox.Show(this.ParentForm, "Save Payroll Changes First", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
SqlConnection dbconnAS = new SqlConnection(strDBconnAS);
{
try
{
AsyncCallback callback = new AsyncCallback(HandleCallback);
using (SqlCommand SQLcmd = new SqlCommand("dbo.KronosTaData", dbconnAS))
{
SQLcmd.CommandType = CommandType.StoredProcedure;
dbconnAS.Open();
Changed = true;
SQLcmd.BeginExecuteNonQuery(callback, SQLcmd);
strResult = "";
ExportProgress.Visible = true;
ExportProgress.Value = 0;
ExportProgress.Maximum = 120;
ExportTimer.Start();
}
}
catch (Exception ex)
{
Changed = false;
strResult = ex.Message;
if (dbconnAS != null)
{
dbconnAS.Close();
}
}
}
}
}
private void HandleCallback(IAsyncResult result)
{
try
{
using (SqlCommand SQLcmd = (SqlCommand)result.AsyncState)
{
int rowCount = SQLcmd.EndExecuteNonQuery(result);
strResult = "OK";
SQLcmd.Connection.Close();
}
}
catch (Exception ex)
{
strResult = ex.Message;
}
}
private void ExportTimer_Tick(object sender, EventArgs e)
{
//Timer Exists on UI thread
if (strResult == "")
{
if (cmdKronos.Enabled) cmdKronos.Enabled = false;
if (ExportProgress.Value > ExportProgress.Maximum - 10) ExportProgress.Maximum += 10;
ExportProgress.Value += 1;
}
else if (strResult == "OK")
{
Changed = false;
cmdKronos.Enabled = true;
ExportProgress.Visible = false;
ExportTimer.Stop();
MessageBox.Show(ParentForm, "Kronos data succesfully imported", "Data Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
Changed = false;
cmdKronos.Enabled = true;
ExportProgress.Visible = false;
ExportTimer.Stop();
MessageBox.Show(ParentForm, Text, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
You are disposing the command as soon as you've finished starting it:
using (SqlCommand SQLcmd = new SqlCommand("dbo.KronosTaData", dbconnAS))
{
//...
SQLcmd.BeginExecuteNonQuery(callback, SQLcmd);
//...
}
that will abort everything - so indeed: it will never complete. Basically; using doesn't play nicely with Begin*/End*, so don't do that. You might find it much easier to do this using async/await, by the way (via ExecuteNonQueryAsync).
You also probably want to close and dispose the connection somewhere; again, async/await would make this much easier to get right.
The solution is to declare the variable strResult as static.
See Visual Webgui Variable Scope
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();
}
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();}
}