asp.net - global.asax in asp.net 2.0 app - asp.net

I created a global.asax file for an asp.net application. I run some code in the session_start method. The code does not get executed. Is there some type of procedure for using a global.asax file in asp.net 2.0?
I have the asax file itself and also a codebehind file.
Thank you!
Edit:
asax file:
<%# Application Codebehind="Global.asax.cs" Inherits="GrowUp.Global" %>
The code behind file:
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
namespace Ligdol
{
/// <summary>
/// Summary description for Global.
/// </summary>
public class Global : System.Web.HttpApplication
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
Application["HostName"] = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
Application["counter"] = 1;
}
protected void Session_Start(Object sender, EventArgs e)
{
// Get the count from the application variable
int counter = int.Parse(Application["counter"].ToString());
//Check if a cookie exists.
if(HttpContext.Current.Request.Cookies["ligdolVersion"] != null)
{
//If a cookie exists, we need to redirect the user to the respective site.
if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "new")
{
Response.StatusCode = 302;
Response.Status = "Moved temporarily";
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "old")
{
return;
}
}
else if (counter == 40)
{
// If a cookie does not already exist,
//we need to check if the user is to be allowed to continue to the old site
//or be redirected to the new site.
//Note in a file that a user was redirected, so we can get an estimate of how many are being redirected.
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to new site.");
tw.Close();
// Reset counter.
Application["counter"] = 1;
//write cookie made to expire in 30 days, by then the experiment will be over (we hope!).
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "new";
Response.Cookies.Add(cookie);
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else
{
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to old site.");
tw.Close();
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "old";
Response.Cookies.Add(cookie);
return;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
}
protected void Application_Error(Object sender, EventArgs e)
{
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
}
#endregion
}
}

The issue was the codebehind file. Once I put the code inline inside the asax file, it worked. This might be the only solution for old website projects.

Related

web service is unable to return back to default page

I have asmx web service hosted on IIS and its purpose is to authenticate logined user.
when I run my code using visual studio and debug service is successfully called and authenticate user from DB but it is unable to transfer control back to my code that has default page.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
Response.Redirect("Default.aspx");
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
Session["Uri"] = Request.UrlReferrer;
}
this.hdnLoginStatus.InnerHtml = "";
if (!Page.IsPostBack)
{
new DAS().AuthenticateRequest();
if (HttpContext.Current.Items["LoginStatus"] == null)
return;
var key = (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"];
string msg = (string)GetGlobalResourceObject("Message", key.ToString()) ?? "";
this.ShowMessage(msg, MessageType.Warning);
this.hdnLoginStatus.InnerHtml = "SignedOutForcefully";
}
}
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?key=" + (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"]);
}

HTTP module re-writing the URL with some encryption

I am writing one class with the help of HTTPModule to check userIdentity in session before he access any page.If the variable in the session is null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx", false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of encryption in URL for which my Breadcrumbs are not working in the page. The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu

Update controls field when page load

I fill some controls with data from data base, by calling a select method
and I change the values to update it, but when I press update button, it takes the values that called at the page load, and ignore all changes.
how can I avoid this ?
thanks in advance : )
here is a simple code to present my problem
SelectBLL _selectbll;
string _title = string.Empty;
string _details = string.Empty;
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
GetUMedicineDetails();
}
#endregion
#region Get UMedicine Details
private void GetUMedicineDetails()
{
_selectbll = new SelectBLL();
_selectbll._GetUMedicineDetails(Request.QueryString[0].ToString(), ref _title, ref _details);
#region Bind Controls
txtdetails.Text = _details;
txttitle.Text = _title;
#endregion
}
#endregion
#region Update Button
protected void btnupdate_Click(object sender, EventArgs e)
{
_UpdateUMedicine();
}
#endregion
#region UpdateU Medicine
public void _UpdateUMedicine()
{
_updatebll = new UpdateBLL();
_updatebll._UpdateUMedicine(
Convert.ToInt32(Request.QueryString[0]), txtdetails.Text, txttitle.Text);
}
#endregion
Page.IsPostBack Property: Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetUMedicineDetails();
}
}
Also, Refer:
How to: Determine How ASP.NET Web Pages Were Invoked
DataBind only if !Page.IsPostaBack:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostaBack)
GetUMedicineDetails();
}

Passing the value of a XML tag to another page

Here is the page where I am retrieving from a XML page and by storing it in cookie, I want to retrieve it in another page.
public partial class shopping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie userCookie = new HttpCookie("user");
userCookie["quantity"] = TextBox1.Text;
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("shopping_cart.xml"));
XmlNode root = doc.DocumentElement;
if (RadioButton1.Checked)
{
string str1 = doc.GetElementsByTagName("cost").Item(0).InnerText;
userCookie["cost"] = str1;
//Label3.Text = str1;
Response.Redirect("total.aspx");
}
}
}
and here is other page where I am trying to retrieve it (total.aspx.cs):
public partial class total : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
**Label2.Text = Request.Cookies["user"]["quantity"];**
}
}
I am getting a Null Reference on the line which is in bold. Any suggestions on how can I do it?
You created the cookie in the first section, but forgot to append it to the Response.
Response.Cookies.Add(userCookie); // place before your Response.Redirect
Also, be aware that cookies have a useful maximum size of 4000 bytes, and otherwise a probably not the best choice for what you are doing. You may wish to store temporary session info in the Session for access between pages, rather than use a cookie.
Session["quantity"] = TextBox1.Text
// ...
Session["cost"] = str1;
and in the second page
Label2.Text = Session["quantity"] as string;

webpart control in master page

I have a webpart in a control that I am using on a webpage. The webpage uses a master page and there is a content holder in the MP that can hold controls for alignment/design issues. Everything works well with this but the webpart control. When i put the webpart in the container i lose the ability to move the webparts around but as soon as i move it out of the container it works fine.
default.aspx
/// <summary>
/// Set the selected item equal to the current display mode.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Page_PreRender(object sender, EventArgs e)
{
MyWebPartManager wpm = (MyWebPartManager)WebPartManager.GetCurrentWebPartManager(Page);
Control control = (Control)Master.FindControl("divReturnBack");
if (control != null)
{
control.Visible = true;
control.Controls.Add(DisplayModeMenul1);
}
}
displaymode.ascx
MyWebPartManager webPartManager;
public void Page_Init(object sender, EventArgs e)
{
Page.InitComplete += new EventHandler(InitComplete);
}
public void InitComplete(object sender, System.EventArgs e)
{
webPartManager = (MyWebPartManager)WebPartManager.GetCurrentWebPartManager(Page);
String browseModeName = WebPartManager.BrowseDisplayMode.Name;
foreach (WebPartDisplayMode mode in
webPartManager.SupportedDisplayModes)
{
String modeName = mode.Name;
if (mode.IsEnabled(webPartManager))
{
ListItem listItem = new ListItem(modeName, modeName);
ddlDisplayMode.Items.Add(listItem);
}
}
}
public void ddlDisplayMode_SelectedIndexChanged(object sender, EventArgs e)
{
String selectedMode = ddlDisplayMode.SelectedValue;
WebPartDisplayMode mode = webPartManager.SupportedDisplayModes[selectedMode];
if (mode != null)
{
webPartManager.DisplayMode = mode;
}
}
public void Page_PreRender(object sender, EventArgs e)
{
ListItemCollection items = ddlDisplayMode.Items;
int selectedIndex = items.IndexOf(items.FindByText(webPartManager.DisplayMode.Name));
ddlDisplayMode.SelectedIndex = selectedIndex;
}
I moved this code outside the postback section and it works fine now.
// move to container in masterpage
Control control = (Control)Master.FindControl("divReturnBack");
if (control != null)
{
control.Visible = true;
control.Controls.Add(DisplayModeMenul1);
}

Resources