Restarting a website from its own webpage - asp.net

Well, just to keep it simple: I have a webform. On it a button called "Restart". I click on this button and IIS will restart itself.
Now, what would be the C# code that I would need to write behind the OnClick event of this web button? (If it's even possible?)
Then a second button is added. It's called "Reset" and should just reset the AppDomain for the current web application. What would be the code for this?

protected void Reload_Click(object sender, EventArgs e)
{
HttpRuntime.UnloadAppDomain();
}
protected void Restart_Click(object sender, EventArgs e)
{
using (var sc = new System.ServiceProcess.ServiceController("IISAdmin"))
{
sc.Stop();
sc.Start();
}
}

Process iisreset = new Process();
iisreset.StartInfo.FileName = "iisreset.exe";
iisreset.StartInfo.Arguments = "computer name";
iisreset.Start();
//iisreset.exe is located in the windows\system32 folder.

(http://www.velocityreviews.com/forums/t300488-how-can-i-restart-iis-or-server-from-aspx-page-or-web-service.html)
string processName = "aspnet_wp";
System.OperatingSystem os = System.Environment.OSVersion;
//Longhorn and Windows Server 2003 use w3wp.exe
if((os.Version.Major == 5 && os.Version.Minor > 1) || os.Version.Major ==6)
processName = "w3wp";
foreach(Process process in Process.GetProcessesByName(processName))
{
Response.Write("Killing ASP.NET worker process (Process ID:" +
process.Id + ")");
process.Kill();
}

Is there more than one web site hosted on the server where this code will run? If so, you may want to look at the System.DirectoryServices namespace, and restart the individual web site

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.

How can I programmatically stop the current website? [duplicate]

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.

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#)

Launch WPF from ASP.NET page button click

I am trying to write an aspx page containing a button whose click event should result in opening of a WPF form for further processing. I am trying to use a new process object to launch the WPF application.
I am using the following code in the code behind:
protected void Btn_Click(object sender, EventArgs e)
{
Process WPF = new Process();
WPF.StartInfo.FileName = "WpfApplication1.exe";
WPF.Start();
}
On execution, the button click executes without any exception, but the WPF window is not opened.
Can someone please help me.
Thanks.
The code you posted starts (or attempts to start) the WPF application on the server
If you want the client to run a WPF application you could use an XBAP application or a regular WPF application that is distributed through ClickOnce deployment so you can add a link to the application on your web page.
To launch WPF form from asp.net go to the View Code of code behind and Create an object for the WPF form and in the Page_Load event paste the following code
protected void Page_Load(object sender, EventArgs e)
{
Thread t = new Thread(() =>
{
mainWindow = new MainWindow();
mainWindow.Show();
System.Windows.Threading.Dispatcher.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.IsBackground = true;
t.Start();
createDB();
}

Resources