Related
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";
}
In Asp.net mvc 4 / mvc 5 how to handle unauthorised url to redirect to error page.
Please any one give suggestion
private GetDataModel ModelEmpty(GetDataModel model)
{
ShowData data = new ShowData();
data.SRNO = model.Id;
if (model.Name != null)
data.Name = model.Name;
if (model.Res != null)
data.Res = model.Res;
if (model.Tel != null)
data.Tel = model.Tel;
if (model.Ch != null)
data.Ch = model.Ch;
if (model.Res_Off != null)
data.Res_Off = model.Res_Off;
if (model.Off != null)
data.Off_Address = model.Off;
if (model.Email != null)
data.Email = model.Email;
if (model.Mobile != null)
data.Mobile = model.Mobile;
if (model.EnrolmentNoofBarCouncil != null)
data.EnrolmentNoofBarCouncil = model.EnrolmentNoofBarCouncil;
if (model.DHCBAMembershipNo != null)
data.DHCBAMembershipNo = model.DHCBAMembershipNo;
if (model.Fax != null)
data.Fax = model.Fax;
db.ShowDatas.Add(data);
db.SaveChanges();
model.Id = 0;
model.Name = "";
model.Mobile = "";
model.Off = "";
model.Res_Off = "";
model.Res = "";
model.Tel = "";
model.Fax = "";
model.Email = "";
model.DHCBAMembershipNo = "";
model.EnrolmentNoofBarCouncil = "";
model.Ch = "";
return model;
}
public ActionResult About()
{
GetDataModel model2 = new GetDataModel();
//string path = HttpContext.Server.MapPath("~/HtmlFiles/A1.htm");
// string path = HttpContext.Server.MapPath("~/HtmlFiles/B.htm");
string directoryPath = HttpContext.Server.MapPath("~/HtmlFiles");
string[] fileEntries = Directory.GetFiles(directoryPath);
//get the page
foreach (var fileName in fileEntries)
{
var web = new HtmlWeb();
var document = web.Load(fileName);
var page = document.DocumentNode;
var count = page.QuerySelectorAll("span").Count();
var htmlArray = page.QuerySelectorAll("span").ToArray();
for (int i = 0; i < count; i++)
{
var item = htmlArray[i];
if (item.InnerText!="" && item.FirstChild.Name != "img" && item.FirstChild.Name != "hr")
{
if (item.Attributes["class"].Value != "ft1" && item.Attributes["class"].Value != "ft2" && item.Attributes["class"].Value != "ft3")
{
if (item.Attributes["class"].Value == "ft0" && item.InnerText != " ")
{
int value;
if (int.TryParse(item.InnerText, out value))
{
var id = Convert.ToInt32(item.InnerText);
model2.Id = id;
}
else
{
var Name = item.InnerText;
if (Name != "Name & Address")
model2.Name = Name.Trim();
}
}
if (item.Attributes["class"].Value == "ft4" && item.InnerText != " ")
{
if (item.InnerText == "Res:")
{
int value;
string Res = htmlArray[i + 1].InnerHtml.Contains(":") ? htmlArray[i - 1].InnerHtml : htmlArray[i + 1].InnerHtml;
if (!int.TryParse(htmlArray[i + 2].InnerText, out value) && !htmlArray[i + 2].InnerHtml.Contains("skype_c2c_print_container notranslate"))
{
if (htmlArray[i + 2].InnerText.Trim().Length > 6)
{
if (!int.TryParse(htmlArray[i + 2].InnerText.Trim().Substring(0, 4), out value))
Res = Res + (htmlArray[i + 2].InnerHtml.Contains(":") ? "" : htmlArray[i + 2].InnerHtml);
}
else
Res = Res + (htmlArray[i + 2].InnerHtml.Contains(":") ? "" : htmlArray[i + 2].InnerHtml);
}
if (!htmlArray[i + 3].InnerHtml.Contains(":") && !int.TryParse(htmlArray[i + 3].InnerText.Trim().Substring(0, 4), out value) && !htmlArray[i + 3].InnerHtml.Contains("skype_c2c_print_container notranslate"))
Res = Res + (htmlArray[i + 3].InnerHtml.Contains(":") ? "" : htmlArray[i + 3].InnerHtml);
model2.Res = Res.Trim();
}
if (item.InnerText == "Ch:")
{
string CH = htmlArray[i + 1].InnerHtml.Contains(":") ? htmlArray[i - 1].InnerHtml : htmlArray[i + 1].InnerHtml;
CH = CH + (htmlArray[i + 2].InnerHtml.Contains(":") ? "" : htmlArray[i + 2].InnerHtml);
if (!(htmlArray[i + 2].InnerHtml.Contains(":")))
CH = CH + (htmlArray[i + 3].InnerHtml.Contains(":") ? "" : htmlArray[i + 3].InnerHtml);
model2.Ch = CH.Trim();
}
if (item.InnerText.Trim() == "Res/Off.:")
{
string Res_Off =string.Empty;//htmlArray[i + 1].InnerHtml.Contains(":") ? htmlArray[i - 1].InnerHtml.Contains(":")?"":htmlArray[i - 2].InnerHtml.Contains(":") ? htmlArray[i - 1].InnerHtml :htmlArray[i - 3].InnerHtml.Contains(":")?htmlArray[i - 2].InnerHtml+""+htmlArray[i - 1].InnerHtml:"" : htmlArray[i + 1].InnerHtml;
if (htmlArray[i - 3].Attributes["class"].Value!="ft0")
Res_Off = Res_Off + htmlArray[i - 3].InnerText;
if (htmlArray[i - 2].Attributes["class"].Value != "ft0")
Res_Off =Res_Off+htmlArray[i - 2].InnerText;
if (htmlArray[i - 1].Attributes["class"].Value != "ft0")
Res_Off = Res_Off + htmlArray[i - 1].InnerText;
// Res_Off = Res_Off + (htmlArray[i + 2].InnerHtml.Contains(":") ? "" : htmlArray[i + 2].InnerHtml);
//if (!(htmlArray[i + 2].InnerHtml.Contains(":")))
// Res_Off = Res_Off + (htmlArray[i + 3].InnerHtml.Contains(":") ? "" : htmlArray[i + 3].InnerHtml);
model2.Res_Off = Res_Off.Trim();
}
if (item.InnerText == "Tel:")
{
string Tel = (htmlArray[i + 1].InnerHtml.Contains(":") ? htmlArray[i - 1].InnerHtml : htmlArray[i + 1].InnerHtml).Trim();
if (Tel.Contains("skype_c2c_print_container notranslate"))
{
string html="<span class='skype_c2c_print_container notranslate'>";
var vals = Tel.Substring(html.Length+1,12);
model2.Tel = model2.Tel + vals + ",";
}
if (!Tel.Contains("skype_c2c_print_container notranslate") && Tel.Contains(",")&& Tel.Length>4)
{
string []telArr = Tel.Split(',');
int value;
if (telArr[0].Length > 4)
model2.Tel = model2.Tel + (int.TryParse(telArr[0].Trim().Substring(0, 4), out value) ? int.TryParse(telArr[0].Trim().Substring(0, 4), out value) ? Tel.Trim() : "" : "") + ",";
}
else
if (!Tel.Contains("skype_c2c_print_container notranslate") && Tel.Contains("/") && Tel.Length>4)
{
string[] telArr = Tel.Split('/');
int value;
model2.Tel = model2.Tel + (int.TryParse(telArr[0].Trim().Substring(0, 4), out value) ? int.TryParse(telArr[0].Trim().Substring(0,4), out value) ? Tel : "" : "") + ",";
}
//else
// if (!Tel.Contains("skype_c2c_print_container notranslate") && Tel.Contains(" "))
// {
// string[] telArr = Tel.Split(' ');
// int value;
// model2.Tel = model2.Tel + (int.TryParse(telArr[0].Trim().Substring(0, 4), out value) ? int.TryParse(telArr[0].Trim().Substring(0,4), out value) ? Tel : "" : "") + ",";
// }
else
{
int value;
model2.Tel = model2.Tel+(int.TryParse(Tel, out value) ? Tel.Trim() : "")+",";
}
// model2.Tel =model2.Tel+ Tel+",";
}
if (item.InnerText == "Fax:")
{
model2.Fax = htmlArray[i + 1].InnerText;
}
if (item.InnerText == "Off:")
{
string Off = htmlArray[i + 1].InnerHtml.Contains(":") ? htmlArray[i - 1].InnerHtml : htmlArray[i + 1].InnerHtml;
if (!htmlArray[i + 2].InnerHtml.Contains("skype_c2c_print_container notranslate") && !(htmlArray[i + 1].InnerHtml.Contains(":")))
Off = Off + (htmlArray[i + 2].InnerHtml.Contains(":") ? "" : htmlArray[i + 2].InnerHtml);
int value;
if (!int.TryParse(htmlArray[i + 3].InnerText, out value)&&!htmlArray[i + 3].InnerHtml.Contains("skype_c2c_print_container notranslate") && !(htmlArray[i + 2].InnerHtml.Contains(":")))
Off = Off + (htmlArray[i + 3].InnerHtml.Contains(":") ? "" : htmlArray[i + 3].InnerHtml);
model2.Off = Off.Trim();
}
if (item.InnerText.Contains("E-mail:"))
{
string Email = htmlArray[i].InnerText.Replace("E-mail:","").Trim();
model2.Email = Email;
}
if (item.InnerText.Contains("Mobile:"))
{
string Mobile = htmlArray[i].InnerHtml.Replace("Mobile:","").Trim();
model2.Mobile = Mobile.Trim();
}
if (item.InnerText.Contains("Enrolment No.of Bar Council:"))
{
string EnrolmentNoofBarCouncil = htmlArray[i].InnerText.Replace("Enrolment No.of Bar Council:","").Trim();
model2.EnrolmentNoofBarCouncil = EnrolmentNoofBarCouncil.Trim();
}
if (item.InnerText.Contains("D.H.C.B.A. Membership No.:"))
{
string DHCBAMembershipNo = htmlArray[i].InnerText.Replace("D.H.C.B.A. Membership No.:","").Trim();
model2.DHCBAMembershipNo = DHCBAMembershipNo.Trim();
if (model2.Tel!=null && model2.Tel.Length > 1)
model2.Tel = model2.Tel.Substring(0, model2.Tel.Length - 1).Trim();
if (model2.Tel!=null && model2.Tel!="" && model2.Tel.ToCharArray()[0] == ',')
{
model2.Tel = model2.Tel.Length==1?"": model2.Tel.Substring(1, model2.Tel.Length-1);
}
if (model2.Tel != null && model2.Tel != "" && model2.Tel.ToCharArray()[model2.Tel.Length-1] == ',')
{
model2.Tel = model2.Tel.Length == 1 ? "" : model2.Tel.Substring(0, model2.Tel.Length - 1);
}
ListModel.Add(model2);
model2 = ModelEmpty(model2);
}
}
}
}
}
}
return View();
}
In this is check url from xml file. Xml file is generate by userName or userName is int type.
public class LogActionFilter:ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool access= Log("OnActionExecuting", filterContext.RouteData);
if (access == true)
{
//filterContext.Result=new RedirectResult("~/User/not_assigned");
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Error" },
{ "action", "error" }
});
}
}
private bool Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
int id = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
XmlDocument doc = new XmlDocument();
string path=HttpContext.Current.Server.MapPath("~/XMLFiles/"+id+".xml");
doc.Load(path);
XmlNodeList nodes=doc.SelectNodes("/Modules/Module");
foreach (XmlNode node in nodes)
{
XmlNodeList cnodes = node.ChildNodes;
foreach (XmlNode cnode in cnodes)
{
if (cnode.HasChildNodes)
{
foreach (XmlNode chnode in cnode.ChildNodes)
{
if (chnode.Attributes["controller"].InnerText.ToString().Equals(controllerName.ToString(), StringComparison.InvariantCultureIgnoreCase) && chnode.Attributes["action"].InnerText.ToString().Equals(actionName.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
string access = chnode.Attributes["access"].InnerText;
if (access.Equals("false", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
}
}
else
{
if (cnode.Attributes["controller"].InnerText.ToString().Equals(controllerName.ToString(), StringComparison.InvariantCultureIgnoreCase) && cnode.Attributes["action"].InnerText.ToString().Equals(actionName.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
string access = cnode.Attributes["access"].InnerText;
if (access.Equals("false", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
}
}
}
return false;
}
}
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
}
I've been given working ASP code which I have to change in order to update existing data in database insted of creating new entries. I think I should swap INSERT INTO statment with UPDATE but the code is a bit too coplicated for me to figure out where and what to change.
Here it comes:
// *** Edit Operations: declare variables
// set the form action variable
var MM_editAction = Request.ServerVariables("SCRIPT_NAME");
if (Request.QueryString) {
MM_editAction += "?" + Server.HTMLEncode(Request.QueryString);
}
// boolean to abort record edit
var MM_abortEdit = false;
// query string to execute
var MM_editQuery = "";
// *** Insert Record: set variables
if (String(Request("MM_insert")) == "AddRecord") {
var MM_editConnection = MM_PhoneWeb_conn_STRING;
var MM_editTable = "Employees";
var MM_editRedirectUrl = "userRegister.asp";
var MM_fieldsStr = "textSurname|value|textFirstname|value|textUsername|value|textPass|value";
var MM_columnsStr = "Surname|',none,''|FirstName|',none,''|Username|',none,''|Password|',none,''";
// create the MM_fields and MM_columns arrays
var MM_fields = MM_fieldsStr.split("|");
var MM_columns = MM_columnsStr.split("|");
// set the form values
for (var i=0; i+1 < MM_fields.length; i+=2) {
MM_fields[i+1] = String(Request.Form(MM_fields[i]));
}
// append the query string to the redirect URL
if (MM_editRedirectUrl && Request.QueryString && Request.QueryString.Count > 0) {
MM_editRedirectUrl += ((MM_editRedirectUrl.indexOf('?') == -1)?"?":"&") + Request.QueryString;
}
}
// *** Insert Record: construct a sql insert statement and execute it
if (String(Request("MM_insert")) != "undefined") {
// create the sql insert statement
var MM_tableValues = "", MM_dbValues = "";
for (var i=0; i+1 < MM_fields.length; i+=2) {
var formVal = MM_fields[i+1];
var MM_typesArray = MM_columns[i+1].split(",");
var delim = (MM_typesArray[0] != "none") ? MM_typesArray[0] : "";
var altVal = (MM_typesArray[1] != "none") ? MM_typesArray[1] : "";
var emptyVal = (MM_typesArray[2] != "none") ? MM_typesArray[2] : "";
if (formVal == "" || formVal == "undefined") {
formVal = emptyVal;
} else {
if (altVal != "") {
formVal = altVal;
} else if (delim == "'") { // escape quotes
formVal = "'" + formVal.replace(/'/g,"''") + "'";
} else {
formVal = delim + formVal + delim;
}
}
MM_tableValues += ((i != 0) ? "," : "") + MM_columns[i];
MM_dbValues += ((i != 0) ? "," : "") + formVal;
}
MM_editQuery = "insert into " + MM_editTable + " (" + MM_tableValues + ") values (" + MM_dbValues + ")";
if (!MM_abortEdit) {
// execute the insert
var MM_editCmd = Server.CreateObject('ADODB.Command');
MM_editCmd.ActiveConnection = MM_editConnection;
MM_editCmd.CommandText = MM_editQuery;
MM_editCmd.Execute();
MM_editCmd.ActiveConnection.Close();
if (MM_editRedirectUrl) {
Response.Redirect(MM_editRedirectUrl);
I ran YSlow on my page and it's complaining I have way too many scripts on my page. On inspection with Firebug I see most of them are of Validation and ScriptManager scripts:
How do I / Can I combine all of these scripts into one? Secondly when I downloaded the contents of WebForms.js it is not minified at all. This is it's content:
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
if (typeof(Page_ClientValidate) == 'function') {
validationResult = Page_ClientValidate(options.validationGroup);
}
}
if (validationResult) {
if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
theForm.action = options.actionUrl;
}
if (options.trackFocus) {
var lastFocus = theForm.elements["__LASTFOCUS"];
if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
if (typeof(document.activeElement) == "undefined") {
lastFocus.value = options.eventTarget;
}
else {
var active = document.activeElement;
if ((typeof(active) != "undefined") && (active != null)) {
if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
lastFocus.value = active.id;
}
else if (typeof(active.name) != "undefined") {
lastFocus.value = active.name;
}
}
}
}
}
}
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
}
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}
var xmlRequest,e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
}
catch(e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// e.g. http:
var action = theForm.action || document.location.pathname, fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
action = action.substr(0, fragmentIndex);
}
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
}
else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame = document.createElement("IFRAME");
xmlRequestFrame.width = "1";
xmlRequestFrame.height = "1";
xmlRequestFrame.frameBorder = "0";
xmlRequestFrame.id = callbackFrameID;
xmlRequestFrame.name = callbackFrameID;
xmlRequestFrame.style.position = "absolute";
xmlRequestFrame.style.top = "-100px"
xmlRequestFrame.style.left = "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src = callBackFrameUrl;
}
}
catch(e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame = document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write("");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element = __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type = "hidden";
fieldElement.name = element.name;
fieldElement.value = element.value;
xmlRequestFrame.document.forms[0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type = "hidden";
callbackIdFieldElement.name = "__CALLBACKID";
callbackIdFieldElement.value = eventTarget;
xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type = "hidden";
callbackParamFieldElement.name = "__CALLBACKPARAM";
callbackParamFieldElement.value = eventArgument;
xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type = "hidden";
callbackValidationFieldElement.name = "__EVENTVALIDATION";
callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type = "hidden";
callbackIndexFieldElement.name = "__CALLBACKINDEX";
callbackIndexFieldElement.value = callbackIndex;
xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[0].submit();
}
}, 10);
}
function WebForm_CallbackComplete() {
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(1), callbackObject.context);
}
}
else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(1), callbackObject.context);
}
}
else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement = document.createElement("INPUT");
validationFieldElement.type = "hidden";
validationFieldElement.name = "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value = validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context);
}
}
}
}
}
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i] = element;
return i;
}
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
var __theFormPostData = "";
var __theFormPostCollection = new Array();
function WebForm_InitCallback() {
var count = theForm.elements.length;
var element;
for (var i = 0; i < count; i++) {
element = theForm.elements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((type == "text" || type == "hidden" || type == "password" ||
((type == "checkbox" || type == "radio") && element.checked)) &&
(element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
function WebForm_EncodeCallback(parameter) {
if (encodeURIComponent) {
return encodeURIComponent(parameter);
}
else {
return escape(parameter);
}
}
var __disabledControlArray = new Array();
function WebForm_ReEnableControls() {
if (typeof(__enabledControlArray) == 'undefined') {
return false;
}
var disabledIndex = 0;
for (var i = 0; i < __enabledControlArray.length; i++) {
var c;
if (__nonMSDOMBrowser) {
c = document.getElementById(__enabledControlArray[i]);
}
else {
c = document.all[__enabledControlArray[i]];
}
if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
c.disabled = false;
__disabledControlArray[disabledIndex++] = c;
}
}
setTimeout("WebForm_ReDisableControls()", 0);
return true;
}
function WebForm_ReDisableControls() {
for (var i = 0; i < __disabledControlArray.length; i++) {
__disabledControlArray[i].disabled = true;
}
}
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (src &&
((src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) ||
((src.tagName.toLowerCase() == "a") &&
(src.href != null) && (src.href != "")) ||
(src.tagName.toLowerCase() == "textarea")) {
return true;
}
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) != "undefined") {
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
function WebForm_GetScrollX() {
if (__nonMSDOMBrowser) {
return window.pageXOffset;
}
else {
if (document.documentElement && document.documentElement.scrollLeft) {
return document.documentElement.scrollLeft;
}
else if (document.body) {
return document.body.scrollLeft;
}
}
return 0;
}
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
}
else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
}
else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
}
else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
function WebForm_SaveScrollPositionOnSubmit() {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
return this.oldOnSubmit();
}
return true;
}
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
}
else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
function WebForm_TextBoxKeyHandler(event) {
if (event.keyCode == 13) {
var target;
if (__nonMSDOMBrowser) {
target = event.target;
}
else {
target = event.srcElement;
}
if ((typeof(target) != "undefined") && (target != null)) {
if (typeof(target.onchange) != "undefined") {
target.onchange();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
function WebForm_TrimString(value) {
return value.replace(/^\s+|\s+$/g, '')
}
function WebForm_AppendToClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index === -1) {
element.className = (element.className === '') ? className : element.className + ' ' + className;
}
}
function WebForm_RemoveClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index >= 0) {
element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
currentClassName.substring(index + className.length + 1, currentClassName.length));
}
}
function WebForm_GetElementById(elementId) {
if (document.getElementById) {
return document.getElementById(elementId);
}
else if (document.all) {
return document.all[elementId];
}
else return null;
}
function WebForm_GetElementByTagName(element, tagName) {
var elements = WebForm_GetElementsByTagName(element, tagName);
if (elements && elements.length > 0) {
return elements[0];
}
else return null;
}
function WebForm_GetElementsByTagName(element, tagName) {
if (element && tagName) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(tagName);
}
if (element.all && element.all.tags) {
return element.all.tags(tagName);
}
}
return null;
}
function WebForm_GetElementDir(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return WebForm_GetElementDir(element.parentNode);
}
return "ltr";
}
function WebForm_GetElementPosition(element) {
var result = new Object();
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
}
else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
}
else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
}
else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}
function WebForm_GetParentByTagName(element, tagName) {
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function WebForm_SetElementHeight(element, height) {
if (element && element.style) {
element.style.height = height + "px";
}
}
function WebForm_SetElementWidth(element, width) {
if (element && element.style) {
element.style.width = width + "px";
}
}
function WebForm_SetElementX(element, x) {
if (element && element.style) {
element.style.left = x + "px";
}
}
function WebForm_SetElementY(element, y) {
if (element && element.style) {
element.style.top = y + "px";
}
}
How do I do minification of this script?
Have a look at this project that uses a .NET port of YUI script and css compressor. We utilized something similar in one of the projects I worked on and it turned out great. Make sure to verify your JavaScript with JSLint or something similar before minimizing it as something very minor may screw things up (like missing a closing semicolon for example).