Threads in for cycle - javafx

I am getting system out println of variable "j" up to ten times in a row, but I don't see any reason for it.
Here is my code:
copyFolderButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String dateStart = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
j = 0.00;
ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
s.schedule(new Runnable() {
#Override
public void run() {
List<String> finallist = copyList.getItems();
totalComputersCopy = copyList.getItems().size();
successRateCopy = 0;
double a = 1.00;
double i = (1.00 / finallist.size());
ArrayList<String> selectedIDs = new ArrayList<String>();
try {
for (String row : finallist) {
a++;
j = j + i;
if (a % 10 == 0) {
Thread.sleep(1500);
}
System.out.println(a);
copythread = new Thread("" + a) {
public void run() {
try {
System.out.println(j);
javafx.application.Platform.runLater(() -> copyGauge.setValue(j * 100));
} catch (Exception ex) {
}
Process p;
try {
String pathRaw = copyFolderPath.getText();
pathRaw = pathRaw.replace(":", "$");
if (pathRaw != null && pathRaw.length() > 0 && pathRaw.charAt(pathRaw.length() - 1) == '\\') {
pathRaw = pathRaw.substring(0, pathRaw.length() - 1);
}
String source = copyFolderSource.getText();
if (source != null && source.length() > 0 && source.charAt(source.length() - 1) == '\\') {
source = source.substring(0, source.length() - 1);
}
InetAddress ia = InetAddress.getByName("172.217.23.206");
boolean b = ia.isReachable(2000);
if (b) {
//System.out.println(j*100);
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "powershell -Command \"Copy-Item '" + source + "' -Destination '" + "\\\\" + row + "\\" + pathRaw + "' -Recurse -Verbose\"");
p = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuilder builders = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builders.append(line);
builders.append("\n");
}
String DeleteLog = builders.toString();
if (DeleteLog.trim().isEmpty()) {
successRateCopy++;
javafx.application.Platform.runLater(() -> copyFolderLog.appendText(row + ": " + "Succesfully copied" + "\n"));
} else {
javafx.application.Platform.runLater(() -> copyFolderLog.appendText(row + ": " + DeleteLog + "\n"));
}
p.waitFor(15, TimeUnit.SECONDS);
p.destroy();
} else {
javafx.application.Platform.runLater(() -> copyFolderLog.appendText("Cannot reach " + row + "\n"));
System.out.println("Cannot reach " + row + "\n");
}
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.toString());
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
Thread.currentThread().interrupt();
}
}
};
copythread.start();
}
} catch (Exception e) {
} finally {
while (copythread.getState() != Thread.State.TERMINATED) {
}
String successRateLog = String.valueOf(successRateCopy);
String failedRateLog = String.valueOf(totalComputersCopy - successRateCopy);
String dateStop = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
if ((diff / (60 * 60 * 1000) % 24) != 0) {
deleteTime = "Total time: " + String.valueOf(diffHours) + " hours, " + String.valueOf(diffMinutes) + " minutes, " + String.valueOf(diffSeconds) + " seconds";
} else {
if ((diff / (60 * 1000) % 60) != 0) {
deleteTime = "Total time: " + String.valueOf(diffMinutes) + " minutes, " + String.valueOf(diffSeconds) + " seconds";
} else {
if ((diff / 1000 % 60) != 0) {
deleteTime = "Total time: " + String.valueOf(diffSeconds) + " seconds";
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Platform.runLater(() -> {
VBox container = new VBox();
container.setPadding(new Insets(10, 10, 10, 10));
Label icon = new Label();
Image image = new Image(getClass().getResourceAsStream("img/copyicon.png"));
icon.setGraphic(new ImageView(image));
container.getChildren().add(icon);
Notifications.create()
.darkStyle()
.title("Copy Folder")
.text("Workcomplete!" + "\n" + deleteTime + "\n" + "Success: " + successRateLog + "\n" + "Failed: " + failedRateLog)
.hideAfter(Duration.seconds(30))
.graphic(container)
.show();
}
);
}
}
}, 1, TimeUnit.SECONDS);
}
});
I am not sure that this is the best way on how to play with threads. It's working good, but I am aware what's wrong with printing variables in my code, it looks like this:
2.0
3.0
4.0
5.0
6.0
0.03333333333333333
7.0
0.04
0.04
0.04
0.04666666666666667
8.0
9.0
0.060000000000000005
0.060000000000000005
0.060000000000000005
10.0
11.0
12.0
13.0
14.0
15.0
16.0
17.0
18.0
19.0
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
0.12666666666666668
"A" is printing ok, but "j" grows to ten lines and keeps on them.

Related

Issue while working in server asp.net web application

I have an web application name travel. Every thing is working fine while working in test database even if i connect it to live database it works fine in local server but not working in live server.for ex.. I have a grid view to show the details where i can insert,delete,update and view but its working fine in my local server but in live server, my file are updating for the first time but if i try to update for the second time its not working. I have no idea whats happening can any one help me in this.
travel.cs
protected void gv_food_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_food.ShowFooter = true;
gv_food.EditIndex = -1;
Loadgv_food();
}
protected void gv_food_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AddConfirmDelete((GridView)sender, e);
hdnAmtvalue.Value = Convert.ToString((e.Row.RowIndex + 1) + (gv_food.PageSize * gv_food.PageIndex));
hdnAmtvalue.Value = Convert.ToString(Convert.ToInt16(hdnAmtvalue.Value) + 3);
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList drp = (DropDownList)e.Row.FindControl("drpfood");
sqlq = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sqlq += "\n UNION";
sqlq += "\n select DESCRIPTION,regionid from regionmaster";
ds = db.fillDataset(sqlq);
drp.DataSource = ds.Tables[0];
drp.DataTextField = "description";
drp.DataValueField = "regionid";
drp.DataBind();
DropDownList drpC = (DropDownList)e.Row.FindControl("drp_currency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = 2;
Load_CurrencyRate();
DropDownList ddlcurrency = (DropDownList)e.Row.FindControl("drp_currency");
int foodamt = Convert.ToInt32(hdnAmtvalue.Value);
TextBox ticketamount = (TextBox)e.Row.FindControl("txtamount");
TextBox inrate = (TextBox)e.Row.FindControl("txt_inrrate");
TextBox dollarrate = (TextBox)e.Row.FindControl("txt_dollarrate");
TextBox inramount = (TextBox)e.Row.FindControl("txt_inramount");
TextBox dollaramount = (TextBox)e.Row.FindControl("txt_dollaramount");
TextBox txtdate = (TextBox)e.Row.FindControl("txtfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ticketamount.Attributes.Add("ontextchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ddlcurrency.Attributes.Add("onchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
//inrate.Text = hdnAdvInrRate.Value.ToString();
inrate.Text = hdnAdvUsdRate.Value.ToString();
dollarrate.Text = hdnAdvUsdRate.Value.ToString();
//ddlcurrency.SelectedIndex = ddlcurrency.Items.IndexOf(ddlcurrency.Items.FindByText(hdnAdvCurrency.Value));
drp.SelectedIndex = drp.Items.IndexOf(drp.Items.FindByText(hdnRegion.Value));
}
}
protected void gv_food_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
sql = "delete from tmpintfoodexpenses where detailid=" + gv_food.DataKeys[e.RowIndex].Values[0].ToString() + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully deleted');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully deleted";
}
protected void gv_food_RowEditing(object sender, GridViewEditEventArgs e)
{
lblFoodException.Text = string.Empty;
try
{
gv_food.ShowFooter = false;
gv_food.EditIndex = e.NewEditIndex;
Loadgv_food();
//changes made on 25/jan/2012
DropDownList drp1 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEhr1");
DropDownList drp2 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEmin1");
DropDownList drp3 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEahr1");
DropDownList drp4 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEamin1");
sql = "select ARRIVALTIME,DEPATURETIME from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
//ds1 = db.fillDataset(sql);
DataTable dt = new DataTable();
dt = db.fillTable(sql);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["DEPATURETIME"].ToString().Contains(":"))
{
string[] _dhhmm = dt.Rows[0]["DEPATURETIME"].ToString().Trim().Split(new char[] { ':' });
if (_dhhmm[0].Trim() != null)
{
drp1.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[0].ToString()));
drp2.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[1].ToString()));
}
if (dt.Rows[0]["ARRIVALTIME"].ToString().Contains(":"))
{
string[] _ahhmm = dt.Rows[0]["ARRIVALTIME"].ToString().Trim().Split(new char[] { ':' });
if (_ahhmm[0].Trim() != null)
{
drp3.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[0].ToString()));
drp4.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[1].ToString()));
}
}
}
}
//End
sql = "select currencydescription,foodorperdiems from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds1 = db.fillDataset(sql);
currflag = ds1.Tables[0].Rows[0].ItemArray[0].ToString();
DropDownList drp = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpefood");
sql = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sql += "\n UNION";
sql += "\n select description,regionid from regionmaster";
setDataSource(drp, sql);
DropDownList ddlFood = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("ddlFoodOrPerdiems");
ddlFood.SelectedValue = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Label lblregion = (Label)gv_food.Rows[e.NewEditIndex].FindControl("lblf");
lblregion.Visible = false;
drp.SelectedIndex = (drp.Items.IndexOf(drp.Items.FindByText(lblregion.Text.ToString())));
DropDownList drpC = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = drpC.Items.IndexOf(drpC.Items.FindByText(currflag));
indexrow = gv_food.Rows[e.NewEditIndex].RowIndex.ToString();
rowindex = int.Parse(indexrow);
rowindex = rowindex + 2;
DropDownList ddlcurrency = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
TextBox ticketamount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUamount");
TextBox inrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einrrate");
TextBox dollarrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollarrate");
TextBox inramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einramount");
TextBox dollaramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollaramount");
TextBox txtdate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ddlcurrency.Attributes.Add("onchange", "Calculatefoodedit(" + rowindex + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
}
catch (Exception ex)
{
}
}
protected void gv_food_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
indexrow = "";
rowindex = 0;
GridViewRow row1 = gv_food.Rows[e.RowIndex];
TextBox tfromdate = row1.FindControl("txtUfromdate") as TextBox;
TextBox ttodate = row1.FindControl("txtUtodate") as TextBox;
DropDownList ddlfood = (DropDownList)row1.FindControl("ddlFoodOrPerdiems");
DropDownList ddl = (DropDownList)row1.FindControl("drpefood");
TextBox txtdescription = row1.FindControl("txtUdescription") as TextBox;
TextBox txtreference = row1.FindControl("txtUreference") as TextBox;
TextBox tAmt = row1.FindControl("txtUAmount") as TextBox;
//DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
Label tid = row1.FindControl("lblEid") as Label;
DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
DropDownList eddl_curr = (DropDownList)row1.FindControl("drp_ecurrency");
TextBox edcurrentrate = (TextBox)row1.FindControl("txt_edollarrate");
TextBox edamount = (TextBox)row1.FindControl("txt_edollaramount");
TextBox eicurrentrate = (TextBox)row1.FindControl("txt_einrrate");
TextBox eiamount = (TextBox)row1.FindControl("txt_einramount");
//changes made on 25/jan/2012
TextBox txtENoOfDays = row1.FindControl("txtENoOfDays") as TextBox;
DropDownList drpEhr1 = row1.FindControl("drpEhr1") as DropDownList;
DropDownList drpEmin1 = row1.FindControl("drpEmin1") as DropDownList;
DropDownList drpEahr1 = row1.FindControl("drpEahr1") as DropDownList;
DropDownList drpEamin1 = row1.FindControl("drpEamin1") as DropDownList;
//End
if (tfromdate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the From Date');</script>");
lblFoodException.Text = "* Enter the From Date";
tfromdate.Focus();
return;
}
//changes made on 25/jan/2012
if (drpEhr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Hours.";
drpEhr1.Focus();
return;
}
if (drpEmin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Minute.";
drpEmin1.Focus();
return;
}
//End
if (ttodate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the To Date');</script>");
lblFoodException.Text = "* Enter the To Date";
ttodate.Focus();
return;
}
if (drpEahr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Hours.";
drpEahr1.Focus();
return;
}
if (drpEamin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Minue.";
drpEahr1.Focus();
return;
}
//End
if (ddlfood.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the Food or Perdiems');</script>");
lblFoodException.Text = "* Select the Food or Perdiems";
ddl.Focus();
return;
}
if (ddl.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the region');</script>");
lblFoodException.Text = "* Select the region";
ddl.Focus();
return;
}
if (txtdescription.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Description');</script>");
lblFoodException.Text = "* Enter the Description";
txtdescription.Focus();
return;
}
if (txtreference.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Reference');</script>");
lblFoodException.Text = "* Enter the Reference";
txtreference.Focus();
return;
}
if (eddl_curr.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Currencyid');</script>");
lblFoodException.Text = "* Successfully Updated";
eddl_curr.Focus();
return;
}
if (edcurrentrate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edcurrentrate.Focus();
return;
}
if (edamount.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edamount.Focus();
return;
}
if (eicurrentrate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eicurrentrate.Focus();
return;
}
if (eiamount.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eiamount.Focus();
return;
}
//changes made on 25/jan/2012
if (Convert.ToInt32(drpEhr1.SelectedItem.Text) >= 12)
{
Ehh = "PM";
}
else
{
Ehh = "AM";
}
if (Convert.ToInt32(drpEahr1.SelectedItem.Text) >= 12)
{
Emm = "PM";
}
else
{
Emm = "AM";
}
DateTime t1 = Convert.ToDateTime(tfromdate.Text.ToString() + " " + drpEhr1.SelectedItem.Text.ToLower() + ":" + drpEmin1.SelectedItem.Text.ToString() + " " + Ehh);
DateTime t2 = Convert.ToDateTime(ttodate.Text.ToString() + " " + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + " " + Emm);
tp1 = t2.Subtract(t1);
string[] EgetInfo = Convert.ToString(tp1).Split(new char[] { '.' });
if (EgetInfo.Length > 1) // Day calculating
{
Enodays = EgetInfo[0];
string[] EgetHours = EgetInfo[1].ToString().Split(new char[] { ':' });
if (Convert.ToInt32(EgetHours[0].ToString()) >= 6 && Convert.ToInt32(EgetHours[0].ToString()) < 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 0.50;
}
else if (Convert.ToInt32(EgetHours[0].ToString()) >= 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 1;
}
else
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString());
}
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " PM";
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " AM";
}
else//Hours Calculating
{
string[] EgetHours = EgetInfo[0].ToString().Split(new char[] { ':' });
Enodays = "0";
hh = EgetHours[0];
mm = EgetHours[1];
if (Convert.ToInt32(hh.ToString()) >= 6 && Convert.ToInt32(hh.ToString()) < 12)
{
EtotalDays = 0.50;
}
else if (Convert.ToInt32(hh.ToString()) >= 12)
{
EtotalDays = 1;
}
if (Convert.ToInt32(hh.ToString().Length) > 12)
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " PM";
}
else
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " AM";
}
}
txtENoOfDays.Text = Convert.ToString(EtotalDays);
//End
sqlq = "select min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds3 = db.fillDataset(sqlq);
if (ds3.Tables[0].Rows.Count > 0)
{
fromdate = ds3.Tables[0].Rows[0].ItemArray[0].ToString();
todate = ds3.Tables[0].Rows[0].ItemArray[1].ToString();
}
string from = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
string to = Convert.ToDateTime(ttodate.Text).ToString("dd/MMM/yyyy");
//string date = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
bool x = ((Convert.ToDateTime(from) >= Convert.ToDateTime(fromdate)) && (Convert.ToDateTime(to) <= Convert.ToDateTime(todate)));
if (x == false)
{
//ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('Date should be between departure date and arrival date '); </script>");
lblFoodException.Text = "* Date should be between departure date and arrival date";
tfromdate.Text = "";
return;
}
bool y = (Convert.ToDateTime(from) <= Convert.ToDateTime(todate));
if (y == false)
{
// ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('invalid date '); </script>");
tfromdate.Text = "";
lblFoodException.Text = "Invalid Date";
return;
}
int curr8 = 1;
//Poovaragavan P changes made on 25/jan/2012
sqlq = "select min(DEPATURETIME),max(ARRIVALTIME),min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds5 = db.fillDataset(sqlq);
if (ds5.Tables[0].Rows.Count > 0)
{
EDepTime = ds5.Tables[0].Rows[0].ItemArray[0].ToString();
EArrTime = ds5.Tables[0].Rows[0].ItemArray[1].ToString();
EDepDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[2].ToString()).ToString("dd/MM/yyy");
EArrDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[3].ToString()).ToString("dd/MM/yyyy");
}
if (EDepDate == Convert.ToDateTime(from.ToString()).ToString("dd/MM/yyyy") && EArrDate.ToString() == Convert.ToDateTime(to.ToString()).ToString("dd/MM/yyy"))
{
if ((EDepTime != drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString()) || (EArrTime != drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString()))
{
lblFoodException.Text = "Time should be Equal to departure Time and arrival Time";
lblFoodException.ForeColor = System.Drawing.Color.Red;
drpEhr1.SelectedIndex = 0;
drpEmin1.SelectedIndex = 0;
drpEahr1.SelectedIndex = 0;
drpEamin1.SelectedIndex = 0;
drpEhr1.Focus();
return;
}
}
//End
sql = " Update tmpintfoodexpenses set Expensedate=to_Date('" + tfromdate.Text + "','dd/mon/yyyy'),";
sql += " Expensetodate=to_Date('" + ttodate.Text + "','dd/mon/yyyy'),";
sql += " FOODORPERDIEMS='" + ddlfood.SelectedItem.Value.ToString() + "',";
sql += " region=" + ddl.SelectedItem.Value.ToString() + ",";
sql += " DESCRIPTION='" + mod.checkforapostrophe(txtdescription.Text) + "',";
sql += " REFERENCE='" + mod.checkforapostrophe(txtreference.Text) + "',";
sql += " amount=" + mod.checkforapostrophe(tAmt.Text) + ",";
sql += " Currencyid=" + eddl_curr.SelectedItem.Value + ",";
sql += " currencydescription='" + mod.checkforapostrophe(eddl_curr.SelectedItem.Text) + "',";
sql += " dollarcurrentrate=" + mod.checkforapostrophe(edcurrentrate.Text) + ",";
sql += " dollaramount=" + mod.checkforapostrophe(edamount.Text) + ",";
sql += " inrcurrentrate=" + mod.checkforapostrophe(eicurrentrate.Text) + ",";
sql += " inramount=" + mod.checkforapostrophe(eiamount.Text) + ",";
//Poovaragavan P changes made on 25/jan/2012
sql += " NOOFDAYS='" + mod.checkforapostrophe(txtENoOfDays.Text) + "',";
sql += " ARRIVALTIME='" + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + "',";
sql += " DEPATURETIME='" + drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString() + "',";
sql += " TOTALTIME='" + EtotTime.ToString() + "'";
//End
sql += " where detailid =" + mod.checkforapostrophe(tid.Text) + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_halting();
Loadgv_ticket();
Loadgv_local();
Loadgv_other();
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully Updated');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully Updated";
}

Error: Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation

I want to display Agendas from table "tblAgenda" using Asp.net here is the query:
public static List<int> SelectByYear()
{
DbManager db = new DbManager();
try
{
List<int> list = new List<int>();
var result = from p in db.tblAgenda
group p by p.News.Value.Year
into g
select new { Year = g.Key, Releases = g };
foreach (var obj in result)
{
list.Add(obj.Year);
}
list.Reverse();
return list.ToList<int>();
}
catch
{
return null;
}
finally
{
db.Dispose();
}
}
and here I am calling the above method:
public partial class edd_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["id"]))
{
RecentData();
}
}
}
private void RecentData()
{
List<tblAgenda> agd = new List<tblAgenda>();
StringBuilder sbHeadings = new StringBuilder();
StringBuilder sbData = new StringBuilder();
List<int> list1 = AgendaManager.SelectByYear();
if (list1 != null)
{
List<int> list = list1.Take(3).ToList<int>();
int Row = 0;
string RowCss = "";
foreach (tblAgenda ob in agd)
{
strYears = "";
if (list.Count > 0)
{
Table tblHead = new Table();
TableRow trHead = new TableRow();
TableCell tcDvHead = new TableCell();
TableCell tcLnkHead = new TableCell();
for (int i = 0; i < list.Count; i++)
{
Row = 0;
List<clsAgenda> listData = new List<clsAgenda>();
listData = null;
DateTime dt = DateTime.Now.AddYears(1);
string stryr = strYears;
int intyr = Convert.ToInt32(list[i]);
diff = Convert.ToInt32(dt.Year) - Convert.ToInt32(intyr);
if (diff == 0 || diff == 1 || diff == 2)
{
if (drpDepartments.SelectedValue == "-1")
{
strYears += list[i] + ",";
sbHeadings.Append("<div id='dv" + list[i] + "' style='float:left;width:60px;cursor:pointer;' class='btnclass11'>" + list[i] + "</div><div style='float:left;'> </div>");
listData = AgendaManager.SelectAllByYear(Convert.ToInt32(list[i]));
}
else
{
if (AgendaManager.IsAgendExistForDeptartment(Convert.ToInt32(list[i]), Convert.ToInt64(drpDepartments.SelectedValue)))
{
strYears += list[i] + ",";
sbHeadings.Append("<div id='dv" + list[i] + "' style='float:left;width:60px;cursor:pointer;' class='btnclass11'>" + list[i] + "</div><div style='float:left;'> </div>");
}
listData = AgendaManager.SelectAllByYear(Convert.ToInt32(list[i]), Convert.ToInt64(drpDepartments.SelectedValue));
}
sbData.Append("<table id='tbl" + list[i] + "' cellspacing='1' cellpadding='4' width='885' style='display:none;margin-top:10px;' class='GridBorder' >");
sbData.Append("<tr class='GridViewHeaderStyle' >");
sbData.Append("<th style='width:380px;height:22px;text-align:left;'>Meeting</th><th style='height:22px;text-align:left;'>Date</th><th style='width:70px;height:22px;text-align:left;'>Time</th><th style='width:70px;height:22px;text-align:left;'>Agenda</th><th style='height:22px;text-align:left;width:120px;'>Web Cast</th><th style='height:22px;text-align:left;width:100px;'>Minutes</th>");
sbData.Append("</tr>");
foreach (clsAgenda obj in listData)
{
RowCss = "";
if (Row == 1)
{
RowCss = "class='GridRow'";
}
sbData.Append("<tr " + RowCss + ">");
sbData.Append("<td >" + obj.Title + "</td>");
sbData.Append("<td >" + string.Format("{0:MMM dd, yyyy}", obj.AgendaDate) + "</td>");
sbData.Append("<td >" + obj.Time + "</td>");
sbData.Append("<td ><a style='color:black;' href='agenda.aspx?id=" + obj.ID + "'>View</a></td>");
if (string.IsNullOrEmpty(obj.WebCast))
{
sbData.Append("<td >---</td>");
}
else
{
sbData.Append("<td ><a style='color:black;' href='" + obj.WebCast + "'>" + obj.WebCastTitle + "</a></td>");
}
if (string.IsNullOrEmpty(obj.MinutesFile))
{
sbData.Append("<td >---</td>");
}
else
{
if (ob.showThroughBroswer == 1)
{
sbData.Append("<td ><a href='downloadfile.aspx?AgendaMinuteId=" + obj.ID + "' target='_blank'>View</a></td>");
}
else
{
sbData.Append("<td ><a href='showpdf.aspx?AgendaMinuteId=" + obj.ID + "' target='_blank'>View</a></td>");
}
}
sbData.Append("</tr>");
Row++;
if (Row == 2)
{
Row = 0;
}
}
sbData.Append("</table>");
}
else
break;
}
if (strYears.Length > 0)
{
strYears = strYears.Substring(0, strYears.Length - 1);
}
strFirstYear = list[0].ToString();
tcDvHead.Text = sbHeadings.ToString();
if (diff == 1 || diff == 2)
{
tcLnkHead.Text = "<div class='dvhrfclass'><a href='listagendas.aspx?id=pre' class='link1'>Previous Meetings >></a></div>";
}
else
{
tcLnkHead.Text = "";
}
trHead.Cells.Add(tcDvHead);
trHead.Cells.Add(tcLnkHead);
tblHead.Rows.Add(trHead);
StringWriter sW = new StringWriter();
HtmlTextWriter hW = new HtmlTextWriter(sW);
tblHead.RenderControl(hW);
letHeading.Text = sW.ToString();
letData.Text = sbData.ToString();
}
}
}
}
now the issue is I am getting no values in list1, I have tried using the debugger on the query and found that I can't access the "tblAgenda", its giving an error that: " Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation". I have searched alot but didn't find anything good, my connection string is totally fine because all the other tables are working fine even in "tblAgenda" I can store new agenda from admin panel but I can't retrieve the agendas on front end, what is the issue here?
Thanks.

Java servlet - export to an excell using string buffer

I am new to JAVA. I am trying to export Excel through servlet from resultset.
When i am trying to store data in String buffer the it is not actually saving it.
Testfirst.java
String assingee_name = req.getParameter("firstName");
String track_name = req.getParameter("track");
String sla_id = req.getParameter("sla");
StringBuffer sb = new StringBuffer();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Databasethree");
stmt = con.createStatement();
//pw.println("'" +assingee_name + "'");
length = track_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where track =" + "'" + track_name + "'");
}
length = sla_id.length();
if (length > 0) {
//rs = stmt.executeQuery("SELECT* FROM casedetails where case_age >"+"'" +sla_id + "'");
rs = stmt.executeQuery("SELECT* FROM cdoscase where Incident_Submit_Fiscal_Year=" + "'" + sla_id + "'");
}
length = assingee_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where Assingee_name =" + "'" + assingee_name + "'");
}
pw.println("<html><body>");
pw.println("<H1> CDOS Case Management Version 1.1 </H1>");
pw.println("<Head><style>table,th,td{border:1px solid black;}</style></head>");
pw.println("<table>");
ResultSetMetaData rm = rs.getMetaData();
int clm = rm.getColumnCount();
StringBuffer sb1 = new StringBuffer();
String sb2 = new String();
for (int j = 1; j <= clm; j++) {
sb2 = rm.getColumnName(j);
pw.println("<th>");
pw.println(sb2);
pw.println("</th>");
}
ArrayList Rows = new ArrayList();
ArrayList row = new ArrayList();
Object a = new Object();
int jj = 0; // to find out the number rows
while (rs.next()) {
jj = jj + 1;
pw.println("<tr>");
for (int i = 1; i <= clm; i++) {
//data1[i]=rs.getString(i);
pw.println("<td>");
//pw.println(rs.getObject(i).toString());
pw.println(rs.getString(i));
pw.println("</td>");
sb2.append(rs.getString(i);
//row.add(rs.getString(i));
//sb2=sb2+rs.getObject(i).toString();
}
pw.println("</tr>");
} sb1.append("fd");
//Rows.add(row);
pw.println("Total Records found" + sb1);
pw.println("</table>");
//sb2=sb2+rs.getObject(clm).toString();
//sb1.append(sb2);
//sb1.append(sb2);
a = rs.getString(4).toString();
pw.println("this is data " + a);
pw.println("<p>");
pw.println("<td>Do you want to download report </td>");
req.setAttribute("data", Rows);
pw.println("<input type=\"submit\" name =\"submit1\" value=\"Export To Excel\">");
pw.println("</form>");
} catch (SQLException e) {
pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
pw.println(e.getException());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
pw.close();
}
}
}
Any help on this is highly appreciated.
Thanks,
SR

Devexpress MessageBox is closing automatically

I have a Devexpress form which is having Progress bar and MessageBox.
When i click search button on my form,the progress bar displays percentage and then grid will be bind with records.
and when it returns no records, message box will appear after progress bar like "No Records Found"
but after showing No records found,it is closing automatically with out clicking OK or CANCEL button on messagebox
Code for Progress Bar
namespace DMS
{
public partial class ProgressBar : WaitForm
{
public ProgressBar()
{
InitializeComponent();
}
#region Overrides
public override void SetCaption(string caption)
{
base.SetCaption(caption);
this.progressPanel1.Caption = caption;
}
public override void SetDescription(string description)
{
base.SetDescription(description);
this.progressPanel1.Description = description;
}
public override void ProcessCommand(Enum cmd, object arg)
{
base.ProcessCommand(cmd, arg);
}
#endregion
private void progressBarControl1_EditValueChanged(object sender, EventArgs e)
{
try
{
int i = int.Parse(Math.Floor(double.Parse(this.progressBarControl1.EditValue.ToString())).ToString());
if (i.ToString().EndsWith("0"))
{
//satya
//i += 5;
i += 0;
}
this.Opacity = 100;
SetCaption("Please Wait...");
SetDescription(i.ToString() + "% Completed...");
Application.DoEvents();
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString() + " " + ex.Source.ToString());
}
}
}
}
Code for Showing Message Box
private void btnshow_Click(object sender, EventArgs e)
{
try
{
if (dtstartdate.DateTime.Date > dtEnddate.DateTime.Date)
{
XtraMessageBox.Show("Start date should be less than End date", Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
dtstartdate.Focus();
return;
}
string CommandText = "select * from DMS_View_Payments where v_Paymentdate between '" + General.DateToDatabase(this.dtstartdate.DateTime.ToShortDateString())
+ "' and '" + General.DateToDatabase(this.dtEnddate.DateTime.ToShortDateString()) + "'";
if (ccbeForClient.EditValue.ToString() != string.Empty)
{
CommandText += " and v_clientid in (" + this.ccbeForClient.EditValue.ToString() + ")";
}
else if (Logs.UserLimitedClients != "0")
{
CommandText += " and v_clientid in (" + Logs.UserLimitedClients + ")";
}
if (ccbeForBatch.Text.Trim() != "" && ccbeForBatch.Text.Trim() != "--")
{
string selected_client_list = "";
if (ccbeForBatch.Text.Trim() != "" && ccbeForBatch.Text.Trim() != "--")
{
//selected_client_list = ccbe_client_list.Text.Replace(" ", "").Replace(",", "','");
string source = ccbeForBatch.Text;
string[] split = source.Split(',');
string changed = "";
for (int i = 0; i < split.Length; i++)
{
changed += "," + split[i].Trim();
}
//string output = changed.Trim(',').Replace(",", "','");
selected_client_list = changed.Trim(',').Replace(",", "','");
}
else
{
selected_client_list = "";
}
CommandText += " and v_Batch in ('" + selected_client_list + "') ";
}
if (ccbeForBranch.EditValue.ToString() != string.Empty)
{
CommandText += " and v_BRANCH_ID in (" + ccbeForBranch.EditValue.ToString() + ")";
}
if (ccbeForCollector.EditValue.ToString() != string.Empty)
{
CommandText += " and V_CollectorId in (" + ccbeForCollector.EditValue.ToString() + ")";
}
else if (DevXCharts.EmpIdsForHierarchey != "")
{
CommandText += " and V_CollectorId in (" + DevXCharts.EmpIdsForHierarchey.ToString() + ")";
}
if (ccbeForAccountType.Text.Trim() != "" && ccbeForAccountType.Text.Trim() != "--")
{
string selected_client_list = "";
if (ccbeForAccountType.Text.Trim() != "" && ccbeForAccountType.Text.Trim() != "--")
{
//selected_client_list = ccbe_client_list.Text.Replace(" ", "").Replace(",", "','");
string source = ccbeForAccountType.Text;
string[] split = source.Split(',');
string changed = "";
for (int i = 0; i < split.Length; i++)
{
changed += "," + split[i].Trim();
}
//string output = changed.Trim(',').Replace(",", "','");
selected_client_list = changed.Trim(',').Replace(",", "','");
}
else
{
selected_client_list = "";
}
CommandText += " and v_AccountType in ('" + selected_client_list + "') ";
}
if (radioPayment.SelectedIndex == 0)
{
CommandText += " and v_Confirmed='Y'";
}
else if (radioPayment.SelectedIndex == 1)
{
CommandText += " and v_Confirmed='N'";
}
if (radioCases.SelectedIndex == 0)
{
CommandText += " and v_flagabort='0'";
}
else if (radioCases.SelectedIndex == 1)
{
CommandText += " and v_flagabort='1'";
}
CommandText += " order by v_debtorname";
Application.DoEvents();
if (objPB != null)
{
objPB.Close();
objPB = null;
}
objPB = new ProgressBar();
objPB.StartPosition = FormStartPosition.CenterScreen;
objPB.progressBarControl1.EditValue = 20;
objPB.TopMost = true;
objPB.ShowInTaskbar = false;
Application.DoEvents();
objPB.Show();
Application.DoEvents();
SqlDataAdapter sql_for_debtors = new SqlDataAdapter(CommandText, DBConString.ConnectionString());
DataSet ds_for_rhb = new DataSet();
sql_for_debtors.SelectCommand.CommandTimeout = 0;
sql_for_debtors.Fill(ds_for_rhb, "DMS_View_Payments");
sql_for_debtors.Dispose();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 40;
Application.DoEvents();
if (ds_for_rhb.Tables["DMS_View_Payments"].Rows.Count > 0)
{
XrtPaymentsDevx obj_report = new XrtPaymentsDevx();
obj_report.xrlReportHeader.Text = "Payments From " + this.dtstartdate.DateTime.ToString("dd/MM/yyyy") + " To " + this.dtEnddate.DateTime.ToString("dd/MM/yyyy");
string SelectionCriteria = "";
if (this.ccbeForClient.Text != "" && this.ccbeForClient.Text != "--")
{
SelectionCriteria += " Client: " + this.ccbeForClient.Text + " , ";
}
if (this.ccbeForBatch.Text != "" && this.ccbeForBatch.Text != "--")
{
SelectionCriteria += " Batch: " + this.ccbeForBatch.Text + " , ";
}
if (this.ccbeForBranch.Text != "" && this.ccbeForBranch.Text != "--")
{
SelectionCriteria += " Branch: " + this.ccbeForBranch.Text + " , ";
}
if (this.ccbeForCollector.Text != "" && this.ccbeForCollector.Text != "--")
{
SelectionCriteria += " Collector: " + this.ccbeForCollector.Text + " , ";
}
if (this.ccbeForAccountType.Text != "" && this.ccbeForAccountType.Text != "--")
{
SelectionCriteria += " AccType: " + this.ccbeForAccountType.Text + " , ";
}
if (radioPayment.SelectedIndex == 0)
{
SelectionCriteria += " Payment Confirmed='Y'" + " , ";
}
else if (radioPayment.SelectedIndex == 1)
{
SelectionCriteria += " Payment Confirmed='N'" + " , ";
}
else if (radioPayment.SelectedIndex == 2)
{
SelectionCriteria += " Payment Confirmed='Y' And 'N'" + " , ";
}
if (radioCases.SelectedIndex == 1)
{
SelectionCriteria += " Abort Cases" + " , ";
}
else if (radioCases.SelectedIndex == 0)
{
SelectionCriteria += " Active Cases" + " , ";
}
else if (radioCases.SelectedIndex == 2)
{
SelectionCriteria += " Both Active And Abort Cases" + " , ";
}
obj_report.xrlSelectionCriteria.Text = SelectionCriteria;
obj_report.DataSource = ds_for_rhb;
obj_report.DataMember = "DMS_View_Payments";
Application.DoEvents();
objPB.progressBarControl1.EditValue = 60;
Application.DoEvents();
obj_report.CreateDataBindings();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 80;
Application.DoEvents();
//obj_report.bind_data();
obj_report.ShowPreview();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 90;
Application.DoEvents();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 100;
Application.DoEvents();
objPB.Close();
Application.DoEvents();
}
else
{
XtraMessageBox.Show("No Records(s) Found", Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
objPB.progressBarControl1.EditValue = 100;
//objPB.progressBarControl1.EditValue = 100;
Application.DoEvents();
objPB.Close();
//Application.DoEvents();
//objPB.progressBarControl1.EditValue = 100;
//Application.DoEvents();
//objPB.Close();
//XtraMessageBox.Show("No Records(s) Found", Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString() + " " + ex.Source.ToString(), Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The reason of the issue is incorrect usage of WaitForm instance.
You should'not show/hide the WaitForm directly rather then use the SplashScreenManager API to show/hide and interact with WaitForm.
Here i'll try to get you correct approach:
At first, the code for running search operation with WaitForm showing should looks like this:
void OnRunSearchOperation_ButtonClick(object sender, EventArgs e) {
bool success = false;
SplashScreenManager.ShowForm(this, typeof(ProgressWaitForm), false, false);
try {
// here you can run some long time operations
success = SearchOperation();
}
finally { SplashScreenManager.CloseForm(); }
if(!success) {
XtraMessageBox.Show(this, "No entries found");
}
}
bool SearchOperation() {
// THIS IS SEARCH OPERATION IMITATION
const int count = 70000000;
int stepThreshold = count / 100;
decimal dec = 1.41M;
for(int i = 0; i < count; i++) {
dec /= 2;
if((i % stepThreshold) == 0)
SplashScreenManager.Default.SendCommand(WaitFormCommand.PerformStep, null);
}
return false; // result
}
Here are the WaitFormCommand and 'ProgressWaitForm' implementation:
public enum WaitFormCommand {
PerformStep
}
public partial class ProgressWaitForm : WaitForm {
public ProgressWaitForm() {
InitializeComponent();
}
#region Overrides
public override void ProcessCommand(Enum cmd, object arg) {
base.ProcessCommand(cmd, arg);
WaitFormCommand wfCmd = (WaitFormCommand)cmd;
if(wfCmd == WaitFormCommand.PerformStep)
progressBarControl1.PerformStep();
}
#endregion
}

How to stop adding the same item in array while browser reload in asp.net?

In my ASP.NET project, I add a new array item with the help of query string. once the array item added, my client reload the browser,. so the same item add another time. It happens each reload timing.
but i don't want this. any possible to stop this browser reload or stop the same array item?
my url is -
51402/ItemGrid.aspx?id=3035
then id=3035 item added to the array.
My Code in page load event
string query ="";
int array_no;
if (Convert.ToUInt32(GlobalClass.GlobalarrayNo.ToString()) == 0)
{
array_no = 0;
Array.Clear(roomno, 0, roomno.Length);
}
else
{
array_no = Convert.ToInt32(GlobalClass.GlobalarrayNo.ToString());
}
id = Convert.ToInt32(Request.QueryString["id"]);
if (!Page.IsPostBack)
{
// ******* Happy Status ************
decimal happyfromtime = 0;
string happyper="";
string happytotime = "";
query = "SELECT Parameters_Parameter3,Parameters_Parameter2,Parameters_Parameter1,Parameters_Parameter4 FROM MCS_Parameters WHERE Parameters_TYPE ='HAPHOU'";
MySqlConnection connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
happyfromtime= Convert.ToDecimal(Reader[0].ToString());
happyper=Reader[1].ToString();
happystatus= Convert.ToInt32(Reader[2].ToString());
happytotime = Reader[3].ToString();
}
connection.Close();
string t = GlobalClass.GlobalserverTime.ToString();
t= t.Substring(0,5);
t = t.Replace(":",".");
//ALLTRIM(CurCate.Fb_Item_Creation_HappyhoursStatus)='Yes'
if ((Convert.ToDecimal(t) > Convert.ToDecimal(happyfromtime)) && (Convert.ToDecimal(t) < Convert.ToDecimal(happytotime)) && (happystatus == 1))
{
tHappy_Status = 1;
}
if (GlobalClass.GlobalservedAt == "RST")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RestaurantPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else if (GlobalClass.GlobalservedAt == "BAR")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_BarPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RoomPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
command = new MySqlCommand(query, connection);
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
roomno[array_no, 0] = Reader[0].ToString(); // Fb_Item_Creation_ItemDescription
if (GlobalClass.GlobalopenCode == "OPEN")
{
roomno[array_no, 0] = GlobalClass.GlobalopenDes.ToString(); // Fb_Item_Creation_ItemDescription
roomno[array_no, 1] = GlobalClass.GlobalopenRate.ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = GlobalClass.GlobalopenQty.ToString(); // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
array_no++;
GlobalClass.GlobalarrayNo = array_no;
}
else if (roomno[array_no, 0] == "OPEN")
{
Response.Redirect("OpenItem.aspx" + "?id=" + id);
}
else
{
roomno[array_no, 1] = Reader[1].ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = "1"; // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
if ((tHappy_Status == 1) && (roomno[array_no, 16].ToString()=="Yes"))
{
roomno[array_no, 8] = "Yes";
}
array_no++;
GlobalClass.GlobalarrayNo = array_no;
//var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
//nameValues.Set("sortBy", "4");
//string url = Request.Url.AbsolutePath;
//string updatedQueryString = "?" + nameValues.ToString();
//Response.Redirect(url + updatedQueryString);
}
}
connection.Close();
ViewState["btn"] = "1";
ViewState["tot"] = "0";
ViewState["happystatus"] = happystatus;
btn_click = Convert.ToInt32(ViewState["btn"].ToString());
int len = array_no;
while (len > 8)
{
len = len - 8;
tot++;
}
if (len != 0) tot++;
ViewState["tot"] = tot;
fun();
//CreatingTmpModdbf1();
// Modifier Text
int seq = Convert.ToInt32(Request.QueryString["seq"]);
string text = Request.QueryString["text"];
if (text != null)
{
roomno[seq - 1, 15] = text;
}
}
!postback is not help to avoid my problem.
static class GlobalClass
{
private static string myConnString1 = "";
private static int userId = 0;
private static string userName = "";
private static int outletId = 0;
private static int itemGroupId = 0;
private static DateTime serverDate;
private static string serverTime = "";
private static string tableName = "";
private static string serverdAt = "";
private static int arrayNo = 0;
private static int waiterId = 0;
private static int covers = 0;
private static string kotno = "";
public static string GlobalConnString
{
get { return myConnString1; }
set { myConnString1 = value; }
}
public static int GlobaluserId
{
get { return userId;}
set { userId = value; }
}
public static string GlobaluserName
{
get { return userName; }
set { userName = value; }
}
public static int GlobaloutletId
{
get { return outletId; }
set { outletId = value; }
}
public static DateTime GlobalserverDate
{
get { return serverDate; }
set { serverDate = value; }
}
public static string GlobalserverTime
{
get { return serverTime; }
set { serverTime = value; }
}
public static string GlobaltableName
{
get { return tableName; }
set { tableName = value; }
}
public static int GlobalitemGroupId
{
get { return itemGroupId; }
set { itemGroupId = value; }
}
public static string GlobalservedAt
{
get { return serverdAt; }
set { serverdAt = value; }
}
public static int GlobalarrayNo
{
get { return arrayNo; }
set { arrayNo = value; }
}
public static int GlobalwaiterId
{
get { return waiterId; }
set { waiterId = value; }
}
public static int Globalcovers
{
get { return covers; }
set { covers = value; }
}
public static string GlobalkotNo
{
get { return kotno ; }
set { kotno = value; }
}
public static string staffId = "";
public static string staffCategoryId = "";
public static string GlobalstaffId
{
get { return staffId; }
set { staffId = value; }
}
public static string GlobalstaffCategoryId
{
get { return staffCategoryId; }
set { staffCategoryId = value; }
}
public static string openCode = "";
public static string openDes = "";
public static string GlobalopenCode
{
get { return openCode; }
set { openCode = value; }
}
public static string GlobalopenDes
{
get { return openDes; }
set { openDes = value; }
}
public static string openQty = "";
public static string openRate = "";
public static string GlobalopenQty
{
get { return openQty; }
set { openQty = value; }
}
public static string GlobalopenRate
{
get { return openRate; }
set { openRate = value; }
}
}
I assume that your array is static/shared. Static variables are shared across the whole app domain and all threads. Hence every user uses the same variable.
Don't use static variables therefor, instead of persisting the array you should use the querystring again.
If this was a wrong assumption you should show us your code
After adding item you can redirect to another page. For example 51402/ItemGrid.aspx
Also using get request to save/edit/delete data is not good idea, better use post.
If you are adding the item to the Array within Page_Load, you may want to wrap the code that adds the item in the following:
If Not Page.IsPostBack Then
//Your array item adding code here
End If
This will prevent the item adding again if the user refreshes the page. Though, I'd like to echo Tim and say that if I assumed incorrectly, you should post your code.

Resources