Chrome/Safari Back button issue - c#

I am making an application in which we may have 5 or 6 steps.
In first step, i will select the report which i need and save&continue..it will get me to second step...like so...
my problem is according to functionality, when i hit on the browser back button i need to go to previous page.
and again when i press it second time it has to go to my home page,
but it is redirecting me to the previous page.
It is working in all browsers except in chrome and safari.
I am inserting my code for reference..please help me to solve this..
protected void Page_Load(object sender, EventArgs e)
{
DisableHistory();
lnkBackBrowse.Style["visibility"] = "hidden";
if (Session["UserId"] != null)
{
if (Convert.ToInt32(Session["UserId"].ToString()) == 0)
{
TopNavigationMenu.Style["visibility"] = "hidden";
NavigationMenu.Style["visibility"] = "hidden";
if (!Request.Url.ToString().Contains("Home") && !Request.Url.ToString().Contains("SaveandLogout"))
Response.Redirect("Home.aspx");
}
else
{
TopNavigationMenu.Items[0].Text = "Welcome :" + Session["UserName"].ToString();
TopNavigationMenu.Style["visibility"] = "visible";
NavigationMenu.Style["visibility"] = "visible";
if (Session["FirstTimeLogged"] != null && Convert.ToBoolean(Session["FirstTimeLogged"]) == true)
{
TopNavigationMenu.Enabled = false;
NavigationMenu.Enabled = false;
if (!Request.Url.ToString().Contains("MyAccount"))
Response.Redirect("Home.aspx");
}
else
{
GenerateLinks(Session["RoleId"].ToString());
TopNavigationMenu.Enabled = true;
NavigationMenu.Enabled = true;
//TopNavigationMenu.Items[1].Text = "Support <img src='Images/bullet_arrow_down.png' alt='down' title='' />";
if (Request.Url.ToString().Contains("Home"))
Response.Redirect("Default.aspx");
if (!IsPostBack)
{
string strPrevPg = "", strCurrPg = "";
if (Request.UrlReferrer != null)
{
strPrevPg = Request.UrlReferrer.AbsolutePath.ToString();
strPrevPg = strPrevPg.Substring(strPrevPg.IndexOf("/", 1) + 1, strPrevPg.Length - (strPrevPg.IndexOf("/", 1) + 1));
strPrevPg += Request.UrlReferrer.Query.ToString();
}
strCurrPg = Request.Url.AbsolutePath.ToString();
strCurrPg = strCurrPg.Substring(strCurrPg.IndexOf("/", 1) + 1, strCurrPg.Length - (strCurrPg.IndexOf("/", 1) + 1));
bool bFlag;
bFlag = Convert.ToBoolean(Session["goBackPg"]);
if (Session["PrevPg"] != null)
{
if (strCurrPg == Session["PrevPg"].ToString())
{
if (bFlag)
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = "Default.aspx";
bFlag = false;
Session["goBackPg"] = bFlag;
}
else
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = strPrevPg;
}
}
else
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = strPrevPg;
bFlag = false;
Session["goBackPg"] = bFlag;
}
}
}
}
}
}
else
{
Response.Redirect("home.aspx");
}
}

Those browsers are showing you cached content when you press the back button.
You can debug and check, your server is not being hit. This Session code will not work.
You could tell the browser not to cache the page. That way if the user wanted to go back, he would have to reload the content.

Related

My function is not called after a postback in asp.net webforms

I have a function called SetActionSection() which i placed in my pageload. I'm expecting it to be called but nothing happens. I get the result I want when I reload the page.
Here's the my pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string fullName = GetUserFullName();
string id = Request.QueryString["id"];
TextBoxProjectManager.Text = fullName;
if (id != null)
{
GetCMMDetails(TextBoxProjectManager.Text);
int valid = ValidateUserAccess(id, fullName);
if (valid > 0)
GetProjectPostEval();
else
{
Response.Write("You are not allowed to access this data.");
ActionSection.Visible = false;
}
}
else
{
TextBoxProjectManager.Text = fullName;
GetCMMDetails(fullName);
}
SetActionSection();
}
}
Here is SetActionSection() function which shows the a button based on the status in the database.
private void SetActionSection()
{
string id = Request.QueryString["id"];
if (id == null)
{
LinkButtonSaveDraft.Visible = true;
LinkButtonSubmit.Visible = true;
ActionSection.Visible = true;
return;
}
string status = GetStatus(id);
string projectManager = GetCMM(id, "ProjectManager");
string buco = GetCMM(id, "Buco");
string businessExecutiveOfficer = GetCMM(id, "BusinessExecutiveOfficer");
string i2lFunctionLead = GetCMM(id, "I2LFunctionLead");
string user = GetUserFullName();
if ((status.Equals("Draft", StringComparison.OrdinalIgnoreCase))
&& user.Equals(projectManager, StringComparison.OrdinalIgnoreCase))
{
Response.Write(status + " Draft");
LinkButtonSaveDraft.Visible = true;
LinkButtonSubmit.Visible = true;
ActionSection.Visible = true;
}
if (status.Equals("Submitted", StringComparison.OrdinalIgnoreCase) &&
user.Equals(buco))
{
Response.Write(status + " Submitted");
LinkButtonSaveDraft.Visible = false;
LinkButtonSubmit.Visible = false;
LinkButtonBUCOApprove.Visible = true;
ActionSection.Visible = true;
}
if (status.Equals("(Approved) - BUCO", StringComparison.OrdinalIgnoreCase) &&
user.Equals(businessExecutiveOfficer))
{
Response.Write(status + " (Approved) - BUCO");
LinkButtonBUCOApprove.Visible = false;
LinkButtonBEOApprove.Visible = true;
}
if (status.Equals("(Approved) - BEO", StringComparison.OrdinalIgnoreCase) &&
user.Equals(businessExecutiveOfficer))
{
Response.Write(status + " (Approved) - BEO");
LinkButtonBEOApprove.Visible = false;
LinkButtonI2LFunctionLeadApprove.Visible = true;
}
if (status.Equals("(Approved) - I2L Function Lead", StringComparison.OrdinalIgnoreCase))
{
Response.Write(status + " (Approved) - I2L Function Lead");
LinkButtonI2LFunctionLeadApprove.Visible = false;
}
}
I have tested the SetActionSection method and it works. I just want it to be called when the user clicks the submit button. By the way. I'm redirecting to the same form.
Anything inside your if(!IsPostBack) condition will only be executed on initial load and not on submit. You could put the code you want to run on submit (postback) inside an else if you want
if (!IsPostBack)
{
....
}
else
{
SetActionSection();
}
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.ispostback?view=netframework-4.8
Or put your code inside a button click event

Prepopulated Form causing issues for DbContext.SaveChanges()

After doing lots of debugging, I've narrowed down as to why my dbContext update does not work.
I have a script that runs on Page_Load that will populate a form based on the query string category_Id which is the primary key of my table.
protected void Page_Load(object sender, EventArgs e)
{
// Populate Edit Fields
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory = categoryDAL.GetCategory(categoryToGet);
tbEditCategoryName.Text = myCategory.Category_Name;
tbEditCategoryDescription.Text = myCategory.Description;
ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
ddlEditCategoryGroupList.DataBind();
}
catch(Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Could not get Category Info, please try again.";
}
}
This is my script that runs when the edit_Button is clicked, it should update the row in the database and redirect to the viewCategories page.
protected void btnEditCategory_Click(object sender, EventArgs e)
{
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
int categoryToEdit = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory.Category_Name = tbEditCategoryName.Text;
myCategory.Description = tbEditCategoryDescription.Text;
myCategory.CatGroup_Id = Convert.ToInt32(ddlEditCategoryGroupList.SelectedValue);
try
{
bool editStatus = categoryDAL.EditCategory(categoryToEdit, myCategory);
if (editStatus)
{
HttpContext.Current.Session["editStatus"] = "Successful";
Response.Redirect("~/Admin/ManageCategories.aspx");
}
else
{
lblEditStatus.Text = "Unable to update category, please try again";
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
lblEditStatus.Text = Convert.ToString(ex);
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Invalid categoryId.";
}
}
else
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Nothing to update.";
}
}
And this is in my DALayer which holds the functions that has anything to do with categories.
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo)
{
RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext();
RecipeCategory myCategory = new RecipeCategory();
bool status = false;
myCategory = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).First();
myCategory.Category_Name = newCategoryInfo.Category_Name;
myCategory.Description = newCategoryInfo.Description;
myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
try
{
if (dbContext.SaveChanges() == 1)
status = true;
else
status = false;
}
catch (InvalidOperationException ex)
{
status = false;
}
return status;
}
For some reason, whenever I try to update a row with a prepopulated form, the code will always return 0 from dbContext.SaveChanges() and does not update the row in the database.
Note: if I do not populate the form, it works perfectly as normal.
Page_Load doesn't just run the first time the page is loaded, it runs every time the page is loaded, including when the user submits the form. The result is that you're overwriting the user's input before saving it.
In this case, since you're using regular browser navigation to go to a specific category page, you can just check Page.IsPostBack in Page_Load and not set anything in that case.

c# webbrowser viewer control takes time to dispose

When closing Form containing a WebBrowser control with a Pdf document open in the webbrowser, the form takes some 10 seconds to close. I tracked the issue down to Dispose method of the webbrowser.
private void advBandedGridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (advBandedGridView1.GetFocusedDataRow() != null)
{
string wordno = advBandedGridView1.GetFocusedDataRow()["wordno"].ToString();
string itemcd = advBandedGridView1.GetFocusedDataRow()["itemcd"].ToString();
for (int i = 0; i < _caseCount; i++)
{
ButtonColoring(wordno, _seqkindCode[i]);
}
LoadPDF(itemcd);
gridControl2.DataSource = null;
gridControl2.RefreshDataSource();
}
}
Control Event
private void LoadPDF(string itemcd)
{
try
{
ReturnPacket rp;
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = 'EYE'", false);
if (rp.DataTables.Count > 0 && rp.DataTables[0].Rows.Count == 0)
{
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = '1'", false);
}
if (rp.DataTables[0].Rows.Count > 0)
{
string dockind = string.Empty;
dockind = rp.DataTables[0].Rows[0]["code"].ToString();
ParameterCollection paramCol = new ParameterCollection();
paramCol.Add("p_itemcd", itemcd);
paramCol.Add("p_dockind", dockind);
PdfFileInfo temp_fileInfo = biz.SelectInspectionStandards(paramCol);
if (temp_fileInfo != null)
{
if (_fileInfo != null && temp_fileInfo.FileNm == _fileInfo.FileNm)
{
WebBrowserPdf.Visible = true;
return;
}
_fileInfo = null;
_fileInfo = temp_fileInfo;
PDF_FILE_PATH = FilePath + _fileInfo.FileNm;
DirectoryInfo di = new DirectoryInfo(FilePath);
if (di.Exists == false)
{
di.Create();
}
if (!File.Exists(PDF_FILE_PATH))
File.WriteAllBytes(PDF_FILE_PATH, _fileInfo.FileData);
if (!PDF_FILES.Contains(PDF_FILE_PATH))
{
PDF_FILES.Add(PDF_FILE_PATH);
}
WebBrowserPdf.Navigate(PDF_FILE_PATH + "?#zoom=" + _zoomFactor + "%", false);
WebBrowserPdf.Visible = true;
simpleButtonOpenPOPUP.Enabled = true;
}
else
{
WebBrowserPdf.Visible = false;
simpleButtonOpenPOPUP.Enabled = false;
}
}
}
catch (Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Alert, true);
}
}
it is Load Method
private void w_pcmu081_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
WebBrowserPdf.Dispose();
Process[] Pro = Process.GetProcessesByName("osk");
if (Pro.GetLength(0) > 0)
Pro[0].Kill();
}
catch(Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Info, true, null, true);
}
}
Closing
The same situation happened to me.
Adobe has done something wrong in the latest version of Acrobat Reader DC (15.023.20056).
If you uncheck option Enable Protected Mode at startup in Edit -> Preferences -> Security (Enhanced), everything will be back to normal.
On my case it is not a solution.
More info here: https://forums.adobe.com/thread/2267688

aspx page used as dialog box takes time to load after closing while request was sent to server

We have aspx page that is being used as a dialog box.
Page has ascx control which has Text box to search available users from oracle DB tables.
Every search click posts back to same control and renders search results.
If I click search and before response is back from server I close the dialog aspx page, then next time I try to open same dialog box it takes forever to render.
Please suggest what could be happening, going wrong?
Any help is highly appreciated
Here is the code
protected void UserListControl_PreRender(object sender, EventArgs e)
{
//set UI text
m_objTitle.Text = TITLE_LABEL;
//Set Properties of search
m_objSearchResults.CacheResults = true;
m_objSearchResults.RefreshCache = true;
m_objSearchResults.DoSearch = true;
m_objSearchResults.Pageable = true;
m_objSearchResults.NoRecordsMessage = NO_RECORDS_MSG;
m_objSearchResults.PageSize = 25;
m_objSearchResults.SearchType = m_sSearchType;
//Add items to the dropdown
if (m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(AVAIL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT).Value = AVAIL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(ALL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT).Value = ALL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(SEARCH_USER_TEXT);
m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT).Value = SEARCH_USER_VALUE;
}
if (this.Page.IsPostBack == false)
{
m_objStatusDropDown.SelectedValue = SEARCH_USER_VALUE;
}
if (IsPostBack)
{
try
{
m_objUserInstructionText.Text = "";
//add the DAO Parameters
string assignmentTypeSelected = Request.QueryString["AssignmentType"];
m_objSearchResults.DAOParams.Add("RequestType", Request.QueryString["RequestType"]);
m_objSearchResults.DAOParams.Add("AssignmentID", Request.QueryString["AssignmentID"]);
m_objSearchResults.DAOParams.Add("AssignmentType", assignmentTypeSelected);
m_objSearchResults.DAOParams["StatusFilter"] = m_objStatusDropDown.SelectedValue.ToUpper();
m_objSearchResults.DAOParams["Name"] = m_objSearchTextBox.Value.Trim();
if (null == SetApplCode(assignmentTypeSelected))
{
throw new ApplicationException("Invalid Assignment Type.");
}
else
{
m_objSearchResults.DAOParams["ApplCode"] = SetApplCode(assignmentTypeSelected).ToUpper();
}
//add searchControl
m_objListPH.Controls.Add(m_objSearchResults);
// Get the values from the ResultsForm
string sRecordsDisplayed = m_objSearchResults.RecordsDisplayed;
string sTableWidth = m_objSearchResults.TableWidth;
bool bPageable = m_objSearchResults.Pageable;
int iCurrentPageIndex = m_objSearchResults.CurrentPageIndex;
int iPageSize = m_objSearchResults.PageSize;
int iRecordCount = m_objSearchResults.RecordCount;
int iEndRecord = m_objSearchResults.EndRecord;
// Create the html if we are paging data
m_objNavigation.Visible = bPageable;
m_objNavigation.DisplayViewAllButton = false;
m_objNavigation.PageSize = iPageSize;
m_objNavigation.Count = iRecordCount;
m_objNavigation.ItemsDisplayText = "Users";
m_objNavigation.CurrentPage = iCurrentPageIndex + 1;
}
catch (ApplicationException ex)
{
m_objInvalidAssignTypeErr.Text = ex.Message;
m_objUserInstructionText.Text = "";
}
}
}

Session variable at master page is null in ASP.NET

In my login page code behind:
After success of DB
protected void btnLogin_Click(object sender, EventArgs e)
{
int intErr = 0;
LoginDetails objLogDetails = new LoginDetails();
objLogDetails.UserName = txtUsername.Value.ToString();
objLogDetails.UserPassword = txtUserpassword.Value.ToString();
if (Request.Form["rdoLogType"] != null)
sType = Request.Form["rdoLogType"].ToString();
else if (Request.Form["rdoLogType"] == null && txtUsername.Value.ToString().ToLower() == "admin")
sType = "3";
else
sType = "0";
try
{
if (Request.Form["rdoLogType"] == null)
{
intErr = 1;
divErrMsg.InnerText = "Please Select Login type.";
divErrMsg.Visible = true;
}
else
{
int intLogId = 0;
ServeAtDoorstepService objService = new ServeAtDoorstepService();
if (sType == "1")
intLogId = objService.LoginCustomer(objLogDetails);
if (sType == "2")
intLogId = objService.LoginVendor(objLogDetails);
if (sType == "3")
intLogId = objService.LoginCustomer(objLogDetails);
if (string.IsNullOrEmpty(intLogId.ToString().Trim()))
{
intErr = 1;
divErrMsg.InnerText = "Invalid Loginname and Password! Please try again.";
divErrMsg.Visible = true;
}
else
{
Session.Abandon();
Session.RemoveAll();
Session.Add("LoginId", intLogId.ToString());
Session.Add("LoginType", sType);
if (chkAgree.Checked == true)
{
HttpCookie cLoginId = new HttpCookie("LoginId", intLogId.ToString().Trim());
HttpCookie cLoginType = new HttpCookie("LoginType", sType);
cLoginId.Expires = DateTime.Now.AddDays(5);
cLoginType.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cLoginId);
Response.Cookies.Add(cLoginType);
HttpCookie cLoginName = new HttpCookie("LoginName", txtUsername.Value.ToString().Trim());
HttpCookie cPassword = new HttpCookie("Password", txtUserpassword.Value.ToString().Trim());
cLoginName.Expires = DateTime.Now.AddDays(5);
cPassword.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cLoginName);
Response.Cookies.Add(cPassword);
}
}
}
}
catch (System.Threading.ThreadAbortException)
{
}
catch (Exception ex)
{
divErrMsg.InnerText = ex.Message.ToString();
intErr = 1;
}
if (intErr == 0 && Session["LoginType"].ToString() == "1")
Response.Redirect("MyCustomerDash.aspx");
else if (intErr == 0 && Session["LoginType"].ToString() == "2")
Response.Redirect("MyVendorDash.aspx");
else if (intErr == 0 && Session["LoginType"].ToString() == "3")
Response.Redirect("MyAdminDash.aspx");
}
At my master page
this master page is common to all page
protected void Page_Load(object sender, EventArgs e)
{
isShowHideControl = "0";
lblWelcomeMsg.Visible = false;
lblDashboard.Visible = false;
if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "3"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "3"; // Admin
}
else if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "2"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "2"; // Vendor
}
else if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "1"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "1"; // Customer
}
}
But LoginId AND LoginType are always null.
Please help me to get the session value.
This is most likely due to the event life cycle of master pages/web forms. I'm not entirely certain, but the mast page Load event may be firing after your Click event. See this page for details: http://msdn.microsoft.com/en-us/library/dct97kc3.ASPX
See msdn Session.Abandon
When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
so in your sample you abandon session before redirect and on other pages it becomes unavailable. So for resolve try delete this line from your code in login page
Session.Abandon();

Categories