Correct way of using variables from global.asax - c#

I have a simple global.asax file that runs some code at startup and stores a handle in a variable. I want to access that variable from my other files in the project. Here is my global.asax:
<%# Application Language="C#" %>
<script runat="server">
static JustTesting justTesting;
static public JustTesting JustTesting { get { return justTesting ; } }
void Application_Start(object sender, EventArgs e)
{
//my code here
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
</script>
And when I want to use that variable...
ASP.global_asax.JustTesting
...which works, but I'm sure there must be a more elegant way of calling it instead of having to add ASP.global_asax. all the time.

You can use Application object.
Reading:
var x = Application["x"];
Writing:
Application.Lock();
Application["x"] = "value";
Application.UnLock();
Reference: http://msdn.microsoft.com/en-us/library/94xkskdf(v=vs.90).aspx
You can also create your own class, which should be thread safe.

Related

C# how to stop a control's event

I have an .aspx page that has a page_load as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.Name != "")
{
....
}
else
{
FormsAuthentication.RedirectToLoginPage();
return;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
....
}
The issue I am noticing is that when the user clicks the submit button it goes though the Page_Load (goes though the else) and then tries to run though the protected void btnSubmit_Click(object sender, EventArgs e).
Is there a way to make it redirect to the login page and not continue to the next void?
This is NOT an issue. This is the normal ASP.NET Page Life Cycle.
Controls events fire right after the Page_Load event.
Note that the FormsAuthentication.RedirectToLoginPage method does not end the request by calling HttpResponse.End. This means that code that follows the RedirectToLoginPage method call will run.
Assuming you want to stop further processing from within the Page_Load (which I believe is your intention with return):
protected void Page_Load(Object sender, EventArgs e)
{
if (/*I want to kill processing*/)
{
// Method one:
Response.End(); // Though admittedly ugly
// Method two:
this.Context.ApplicationInstance.CompleteRequest();
return; // return as normal (short-circuit)
}
}

Calling pageload after some operation

I have an aspx.cs file with the following code
protected void Page_Load(object sender, EventArgs e)
{
//Some code
}
protected void Removeabc(object sender, EventArgs e)
{
//Some code
}
In the last line of Removeabc i want to reload the page and call Page_Load again. Please help me on how to do the same.
To reload the page, use
Response.Redirect(Request.Url.ToString())
It will call the Page_Load on that reload.
You can use
Response.Redirect(Request.RawUrl);
It will redirect you to the same page and call Page_Load().
You should wrap that logic into a third method which can be called from both handlers:
protected void Page_Load(object sender, EventArgs e)
{
//Some code
DoSomeCleverStuff();
}
protected void Removeabc(object sender, EventArgs e)
{
//Some code
DoSomeCleverStuff();
}
private void DoSomeCleverStuff() {
// Clever stuff
}
It is good practice not to put heavy logic/code into event handlers in C#. Extract the core logic out into either another method or class so that the code can be re-used elsewhere throughout the class/application.
You can redirect to this page using Response.Redirect(Request.Url.ToString()) or if you only want the code in Page_Load to execute you can call Page_Load(null,null)

urlrewriting in asp.net button click

Hi all I have seen many articles on url rewriting but I didn't find any as per my requirement. Assume I have two pages Default.aspx and Default1.aspx.. On initial load I would like to re write my Default.aspx to some thing like urlrewrite\dummy.aspx and on my Default.aspx I will have a button when I click on this I am going to redirect to Default1.aspx I would like to rewrite this to urlrewrite\dummy1.aspx
I just post the sample rewrites but if there is any better way of redirecting can you please help me..
Also what is the best way to rewrite all pages if I have some 20-50 pages
my global.asax file
<%# Application Language="C#" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.Routing" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routeCollection)
{
string root = Server.MapPath("~");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(root);
System.IO.FileInfo[] files = info.GetFiles("*.aspx", System.IO.SearchOption.AllDirectories);
foreach (System.IO.FileInfo fi in files)
{
string pageName = fi.FullName.Replace(root, "~/").Replace("\\", "/");
routeCollection.MapPageRoute(fi.Name + "Route", fi.Name, pageName);
}
routeCollection.MapPageRoute("DummyRouteName1", "Dummy", "~/Default2.aspx");
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
You can add routes in your Global.asax file on application start:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
private void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("DummyRouteName", "Dummy", "~/Default.aspx");
....
}
Usage:
Response.Redirect("~/Dummy");
In url you will see: (server)/Dummy
Edit:
here is how to automatically add routes:
// Get root directory
string root = Server.MapPath("~");
DirectoryInfo info = new DirectoryInfo(root);
// Get all aspx files
FileInfo[] files = info.GetFiles("*.aspx", SearchOption.AllDirectories);
foreach (FileInfo fi in files)
{
// Get relative path
string pageName = fi.FullName.Replace(root, "~/").Replace("\\", "/");
// Add route
routes.MapPageRoute(fi.Name + "Route", fi.Name.Replace(".aspx", ""), pageName);
}
I assume that you got that rewriting part covered and only problem is postback, you can set postback to "friendly" URL by seting form action, like this :
Page.Form.Action = Page.Request.RawUrl;

Redirects with Global.asax file in C#

I have added the following code to my Global.asax file:
<%# Application Language="C#" %>
<script runat="server">
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (ConfigurationManager.AppSettings["IsReviewServer"] == "Yes")
{
if (!Request.IsSecureConnection)
{
string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));
Response.Redirect(path);
}
}
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
etc.....
But my BeginRequest function just gets ignored. How do I redirect my entire application from http: to https:?
If you're using a master page or a base class, I would put your logic there. Global events shouldn't be relied upon for logic like this.
Put the logic in Page_Load (or earlier in the lifecycle) of the master page or base class like this:
protected void Page_Load(object sender, EventArgs e)
{
if (ConfigurationManager.AppSettings["IsReviewServer"] == "Yes")
{
if (!Request.IsSecureConnection)
{
string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));
Response.Redirect(path);
}
}
}
You could do the above at another point in the lifecycle if you wanted too, like PreLoad or PreRender.
Using global events
If you're going to use a global event, I would actually use Application_EndRequest, because it gets called on every request so the application can clean up resources.

Null Reference exception when accessing property in OnClick

Please help me to figure out what is wrong with this code:
I have ASP.NET page with one button visible.
When user clicks it - it instances MyClass (its implementation is in AppCode directory) and turns invisible (button2 becomes visible).
When I click button2 it raises "Object reference not set to an instance of an object" Exception.
What seems to be the problem?
{
public MyClass noviTest;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
noviTest = new MyClass(TextBox1.Text);
Button1.Visible = false;
Button2.Visible = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text=noviTest.getID; //this is the critical line
}
}
Since on postback the noviTest reference to MyClass is not recreated.
You can add it to the viewstate to keep a reference to it. (Assuming MyClass is serializable).
In Button1_Click:
ViewState("noviTest") = noviTest;
Then in Button2_Click:
var noviTest = ViewState("noviTest");
noviTest is null inside Button2_Click.
Try something like this:
protected void Page_Load(object sender, EventArgs e)
{
noviTest = new MyClass(TextBox1.Text);
}
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Visible = false;
Button2.Visible = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = noviTest.getID;
}
This will cause noviTest to be instantiated on each page request, regardless of which button was clicked. This may not be the best solution for your particular application (I am unfamiliar with the rest of the logic in this class) but you get the idea.
Each visit to the code-behind is kind of like running the code from scratch, nothing is set up or preserved for you between visits to page.
So when you hit the second button noviTest is not initialised and therefore when you attempt to call .getID to you get a null reference exception.
To deal with this you need to ensure that noviTest is initialised. If you want to have it persisted between visits to the page you need to use some mechanism to either store or recreate the instance. To store it you would (probably) use session. To recreate you would use either session or viewdata to persist a key value that would then allow you to retrieve the object state from storage of some kind.

Categories