How can I programmatically stop the current website? [duplicate] - asp.net

This question already has answers here:
How can I programmatically stop or start a website in IIS (6.0 and 7.0) using MsBuild?
(3 answers)
Closed 7 years ago.
I am using the MVC5 for an web application. The web app runs in IIS7 or greater.
In the Global.asax on application_start, the number of licenses will be set:
protected void Application_Start()
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch(Exception e)
{
// log exception
// stop web site.
}
}
If any expection will be thrown in this context, the web site should shut down as you can do that in the IIS-Manager:
How can I stop the current web site in my Application_Start ?

You can do it with the help of "Microsoft.Web.Administration.dll"
using Microsoft.Web.Administration;
After adding the reference of "Microsoft.Web.Administration.dll" write below code in Global.asax
protected void Application_Start(object sender, EventArgs e)
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch (Exception e)
{
// get the web site name
var lWebSiteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
// log exception
// stop web site.
using (ServerManager smg = new ServerManager())
{
var site = smg.Sites.FirstOrDefault(s => s.Name == lWebSiteName);
if (site != null)
{
//stop the site...
site.Stop();
}
}
}
}

I will go not with stop it, but to show some message if you do not have license.
This is an example, and an idea.
You can use this code on global.asax where if you do not have licenses the moment you start, you open a flag, and after that you do not allow any page to show, and you send a page that you can keep on an html file.
private static bool fGotLicense = true;
protected void Application_Start()
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch(Exception e)
{
// log exception
// stop web site.
fGotLicense = false;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
// if not have license - let show some infos
if (!fGotLicens)
{
// the file we look now is the app_offline_alt.htm
string cOffLineFile = HttpRuntime.AppDomainAppPath + "app_offline_alt.htm";
// if exist on root
if (System.IO.File.Exists(cOffLineFile))
{
using (var fp = System.IO.File.OpenText(cOffLineFile))
{
// read it and send it to the browser
app.Response.Write(fp.ReadToEnd());
fp.Close();
}
}
// and stop the rest of processing
app.Response.End();
return;
}
}

You can have a file named app_offline.htm with content say This website is offline now in web server and copy that to root directoy of website you want for any event.
It will directly show that message, but yes, App pool will be still ON, when you need to start , you just need to rename that to something else.

Related

How to disable a single aspx page in ASP.NET webapplication?

Would like to disable a single aspx page in an ASP.NET web application and show the message 'This page is under maintenance' while the application is still up. Is this possible?
One way to do that on Application_BeginRequest on global.asax. Check the if the specific file is called and show some other static page and End the process there. Here is how:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
string cTheFileName = System.IO.Path.GetFileName(HttpContext.Current.Request.Path);
// if its the file you want to be offline
if (cTheFileName == 'filename.aspx')
{
// the file we look now is the app_offline_alt.htm
string cOffLineFile = HttpRuntime.AppDomainAppPath + "app_offline_alt.htm";
// if exist on root - if not we skip the offline mode.
// this way you can put it offline with just the existing of this file.
if (System.IO.File.Exists(cOffLineFile))
{
using (var fp = System.IO.File.OpenText(cOffLineFile))
{
// read it and send it to the browser
app.Response.Write(fp.ReadToEnd());
fp.Close();
}
// and stop the rest of processing
app.Response.End();
return;
}
}
}
the app_offline_alt.htm contains a simple under maintenance message or what ever you like.

IIS turned off my application automatically?

I just noticed that IIS turned off my ASP.NET web application automatically after it idled 20 minutes. The website is hosted on Godaddy.com.
Below is the Global class which logs the Application_Start and Application_End methods. And the image I uploaded is the result that I saw.
It turned off at 2013-05-24 06:42:40 after the last call I did at 06:22:01. (20 minutes, hua...)
After one day, I did another call at 2013-05-25 03:05:27, the website was awakened.
Strange? I didn't want my website to sleep. Is there any way to keep it sane all the time?
public class Global : HttpApplication
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
log.Debug("Application_AuthenticateRequest -> " + base.Context.Request.Url);
}
protected void Application_End(object sender, EventArgs e)
{
log.Info("Application_End");
}
protected void Application_Start(object sender, EventArgs e)
{
log.Info("Application_Start");
}
}
The IIS/asp.net is turn off the application if you do not have any request for some time to save resource.
Now this usually handle on server side if you wish to avoid it, but in your case you can't interfere with the IIS setup, so one trick is to create a timer that reads every 10 minutes or so one page.
You start it when application starts, and do not forget to stop it when application is go off.
// use this timer (no other)
using System.Timers;
// declare it somewhere static
private static Timer oTimer = null;
protected void Application_Start(object sender, EventArgs e)
{
log.Info("Application_Start");
// start it when application start (only one time)
if (oTimer == null)
{
oTimer = new Timer();
oTimer.Interval = 14 * 60 * 1000; // 14 minutes
oTimer.Elapsed += new ElapsedEventHandler(MyThreadFun);
oTimer.Start();
}
}
protected void Application_End(object sender, EventArgs e)
{
log.Info("Application_End");
// stop it when application go off
if (oTimer != null)
{
oTimer.Stop();
oTimer.Dispose();
oTimer = null;
}
}
private static void MyThreadFun(object sender, ElapsedEventArgs e)
{
// just read one page
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadData(new Uri("http://www.yoururl.com/default.aspx"));
}
}
One note, do not use this trick unless you needed because you create one more thread living for ever. Usually google reads the web pages and keep it "warm", the auto turn off usually occurs if you have a very new site that google and other search engines did not start to index, or if you have one two page only that never change.
So I do not recomended to do it - and is not bad to close your site and save resource, and your site is clear from any forgotten open memory and start fresh...
Similar Articles.
Keep your ASP.Net websites warm and fast 24/7
Application Initialization Module for IIS 7.5
Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)

ASPX page loading data from last session

I'm creating a C# application with a ASP.net frontend, however I'm having a problem at the moment. I want to the user to enter some information, which once submitted, will be displayed within a listbox on the page which works fine. However, once I close the page, stop debugging the program and run it again - the information is still displayed but I want it to start off blank. Here if the ASPX page that I think if causing the issue, it's driving me mad.
public partial class CarBootSaleForm : System.Web.UI.Page, ISaleManagerUI
{
private SaleList saleList;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && Application["SaleList"] != null)
{
LoadData();
}
else
{
saleList = (SaleList)Application["SaleList"];
}
if (saleList != null)
{
UpdateListbox();
}
}
private void UpdateListbox()
{
lstSales.Items.Clear();
if (saleList != null)
{
for (int i = 0; i < saleList.Count(); i++)
{
lstSales.Items.Add(new ListItem(saleList.getSale(i).ToString()));
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Application.Lock();
Application["SaleList"] = saleList;
Application.UnLock();
Response.Redirect("AddSaleForm.aspx");
}
}
Forget the LoadData() within the page load as it's not actually loading anything at the moment :)
Any help is really appreciated!
The variables stored in Application state are not flushed unless you restart the web server, so you will need to use the iisreset commmand (on command-line) if you are using IIS, or you will need to stop the ASP.NET web server (use the tray icons) after each debugging session.
if it is not postback you can add
Session.Abandon(); in the else block in Page_load.
Kill Session:
How to Kill A Session or Session ID (ASP.NET/C#)

Custom HTTP handler for URL rewriting + session and application variable

Currently my product page URL is like
http://www.localhost:80/products/default.aspx?code=productCode
I want to access product page with
http://www.localhost:80/productCode
I have used HTTP module for this.
public class UrlRewritingModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (some condition)
{
context.RewritePath(url);
}
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
//We set back the original url on browser
HttpContext context = ((HttpApplication)sender).Context;
if (context.Items["originalUrl"] != null)
{
context.RewritePath((string)context.Items["originalUrl"]);
}
}
}
I have register it in web.config and it is working fine. But when I deploy it in IIS that session and application variables are not throwing null referent Exceptions.
Can anyone help me?
Edit: Do it require extra code to access session/ Application variable for rewritten URLs
?
Have you tried using HTTPContext.Current?
I was able to solve issue (accessing session and application variables in subsequent pages rewritten by custom handler) by adding runAllManagedModulesForAllRequests="true" attribute in modules in web.config.

Asp.net global output cache

Last few days I thinkin about output cache in asp.net. In my task I need to implement output cache for the very big project. After hours of searching I did not find any examples.
Most popular way to use output cache is declarative, in this case you need to write something like this on the page which you want to cache.
But if you need to cache whole site you must write this on all pages or master pages on project. It is madness. In this case you cant store all configuration in one place. All page have his own configurations..
Global.asax could help me, but my site contains about 20 web progects and ~20 global.asax files. And i don't want copy same code to each project.
For these reasons, i made decision to create HTTPModule.
In Init method i subscribe to two events :
public void Init(HttpApplication app)
{
app.PreRequestHandlerExecute += new EventHandler(OnApplicationPreRequestHandlerExecute);
app.PostRequestHandlerExecute += new EventHandler(OnPostRequestHandlerExecute);
}
In method "OnPostRequestHandlerExecute" I set up output caching parameters for each new request :
public void OnPostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpCachePolicy policy = app.Response.Cache;
policy.SetCacheability(HttpCacheability.Server);
policy.SetExpires(app.Context.Timestamp.AddSeconds((double)600));
policy.SetMaxAge(new TimeSpan(0, 0, 600));
policy.SetValidUntilExpires(true);
policy.SetLastModified(app.Context.Timestamp);
policy.VaryByParams.IgnoreParams = true;
}
In "OnApplicationPreRequestHandlerExecute" method I set calback method to cache validation:
public void OnApplicationPreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Context.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), app);
}
And last part - callback validation method :
public void Validate(HttpContext context, Object data, ref HttpValidationStatus status)
{
if (context.Request.QueryString["id"] == "5")
{
status = HttpValidationStatus.IgnoreThisRequest;
context.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), "somecustomdata");
}
else
{
status = HttpValidationStatus.Valid;
}
}
To attach my HttpModule I use programmatically attach method :
[assembly: PreApplicationStartMethod(typeof(OutputCacheModule), "RegisterModule")]
This method works perfectly, but I want to know is there other ways to do this.
Thanks.
Try seeing if IIS caching provides what you need.
http://www.iis.net/configreference/system.webserver/caching

Resources