Clearing temp ASP.NET files on application restart - asp.net

We're dynamically loading assemblies at startup and adding them as a reference:
BuildManager.AddReferencedAssembly(assembly);
The application supports installing new plugins at runtime. Following an install/uninstall action we are restarting the web application. I've tried:
HostingEnvironment.InitiateShutdown();
and
System.Web.HttpRuntime.UnloadAppDomain();
However, the new version of a plugin is not loaded - I believe this is due to how ASP.NET is aggressively caching referenced assemblies - especially ASP.NET MVC controllers.
In production this shouldn't be a problem since the plugin assembly version would be incremented each time. However, in development this is more of an issue since we don't wish to change the version number every time we make a slight change to a plugin.
How can we force the clearing of temp asp.net files, either programatically or using a post build event?
One solution is to "touch" global.asax but this seems a bit hacky to me.

I've used following piece of code to reset the application pool on demand. (Just connect this to a Controller Action).
Note : Since it's the application pool, you might want to check the impact to any other apps running on the same app pool.
public class IisManager
{
public static string GetCurrentApplicationPoolId()
{
// Application is not hosted on IIS
if (!AppDomain.CurrentDomain.FriendlyName.StartsWith("/LM/"))
return string.Empty;
// Application hosted on IIS that doesn't support App Pools, like 5.1
else if (!DirectoryEntry.Exists("IIS://Localhost/W3SVC/AppPools"))
return string.Empty;
string virtualDirPath = AppDomain.CurrentDomain.FriendlyName;
virtualDirPath = virtualDirPath.Substring(4);
int index = virtualDirPath.Length + 1;
index = virtualDirPath.LastIndexOf("-", index - 1, index - 1);
index = virtualDirPath.LastIndexOf("-", index - 1, index - 1);
virtualDirPath = "IIS://localhost/" + virtualDirPath.Remove(index);
var virtualDirEntry = new DirectoryEntry(virtualDirPath);
return virtualDirEntry.Properties["AppPoolId"].Value.ToString();
}
public static void RecycleApplicationPool(string appPoolId)
{
string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPoolId;
var appPoolEntry = new DirectoryEntry(appPoolPath);
appPoolEntry.Invoke("Recycle");
}
public static void RecycleApplicationPool(string appPoolId, string username, string password)
{
string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPoolId;
var appPoolEntry = new DirectoryEntry(appPoolPath, username, password);
appPoolEntry.Invoke("Recycle");
}
}
The overridden method is to cater for instances where you want to explicitly pass a user with Admin rights on the machine/server which hosts IIS instance.
And the controller action could be something like;
public string ResetAppPool()
{
var appPoolId = IisManager.GetCurrentApplicationPoolId();
if (appPoolId.Equals(string.Empty))
return "Application is not running inside an App Pool"; //May be not IIS 6 onwards
try
{
IisManager.RecycleApplicationPool(appPoolId); //Can only be used by Admin users
return string.Format("App pool {0} recycled successfully", appPoolId);
}
catch (Exception ex)
{
Logger.Error("Failed to recycle app pool : " + ex.StackTrace);
return string.Format("App pool {0} recycle failed", appPoolId);
}
}

Related

How do you correctly and programmatically recycle an app pool on an IIS server

This is what I am currently doing
public static string RecycleSite(string siteName)
{
try
{
using (ServerManager iisManager = new ServerManager())
{
SiteCollection sites = iisManager.Sites;
foreach (Site site in sites)
{
if (site.Name == siteName)
{
ObjectState os = iisManager.ApplicationPools[site.Applications["/"].ApplicationPoolName].Recycle();
return "Recycle Successful";
}
}
}
return "Recycle Unsuccessful";
}
catch(Exception ex)
{
return "Recycle Unsuccessful: " + ex;
}
I have viewed multiple other threads, but none seem to have the answer I am look for. I want to use the Server Manager class to recycle a specific IIS site. This current solution does a "recycle" but it also kills any active connections that are still present. The IIS manager is set up so I can begin a new instance while there are persisting connections on the current instance until those connections have closed on their own.
Is my solution correct or do I need to go about recycling in a more direct way? This is part of a console application that is set to run as an admin so that my other service that is calling is can sit under a user account (security reasons). Using IIS 8.5 on Server 2012 R2.

Windows User getting "access denied" from exchange server

I have a MVC Web Application makes use of Windows Authentication and Exchange Web Services. While in development, this worked great, since the application pool in IIS on my development machine is set to run under my windows user and the Exchange Server is on the same domain.
On the web server, though, all our applications are set to run under a system user that has access to all the database servers etc. The database connection uses Integrated Security, so I cannot impersonate a user over an application level.
I've been trying to impersonate the current windows user through the code as follows:
public abstract class ExchangeServiceImpersonator
{
private static WindowsImpersonationContext _ctx;
public Task<string> CreateMeetingAsync(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
var tcs = new TaskCompletionSource<string>();
EnableImpersonation();
try
{
tcs.TrySetResult(CreateMeetingImpersonated(from, to, subject, body, location, begin, end));
}
catch(Exception e)
{
tcs.TrySetException(e);
}
finally
{
DisableImpersonation();
}
return tcs.Task;
}
public abstract string CreateMeetingImpersonated(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end);
private static void EnableImpersonation()
{
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
_ctx = winId.Impersonate();
}
private static void DisableImpersonation()
{
if (_ctx != null)
_ctx.Undo();
}
}
Then, the class that implements the abstract methods:
public class ExchangeServiceExtensionsBase : ExchangeServiceImpersonator
{
private ExchangeService _service;
public ExchangeService Service
{
get
{
if (this._service == null)
{
this._service = new ExchangeService(ExchangeVersion.Exchange2013);
this._service.Url = new Uri(WebConfigurationManager.AppSettings["ExchangeServer"]);
this._service.UseDefaultCredentials = true;
}
return this._service;
}
set { return; }
}
public override string CreateMeetingImpersonated(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
//this.Service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, from);
Appointment meeting = new Appointment(Service);
string meetingID = Guid.NewGuid().ToString();
meeting.Subject = subject;
meeting.Body = "<span style=\"font-family:'Century Gothic'\" >" + body.Replace(Environment.NewLine, "<br/>") + "<br/><br/>" +
"<span style=\"color: white;\">Meeting Identifier: " + meetingID + "</span></span><br/><br/>";
meeting.Body.BodyType = BodyType.HTML;
meeting.Start = begin;
meeting.End = end;
meeting.Location = location;
meeting.ReminderMinutesBeforeStart = 60;
foreach (string attendee in to)
{
meeting.RequiredAttendees.Add(attendee);
}
meeting.Save(SendInvitationsMode.SendToAllAndSaveCopy);
return meetingID;
}
}
Then, the methods are accessed as follows:
public static class ExchangeServiceExtensions
{
public static async Task<string> CreateMeetingAsync(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
ExchangeServiceImpersonator serviceImpersonator = new ExchangeServiceExtensionsBase();
return await serviceImpersonator.CreateMeetingAsync(from, to, subject, body, location, begin, end);
}
}
This still works on my local dev machine, but no matter what I do, the user accessing from the server keeps getting an access denied from the exchange server:
The request failed. The remote server returned an error: (401) Unauthorized.
I've tried leaving it on default credentials:
this._service.UseDefaultCredentials = true;
And attempting to manually set the credentials to the current (supposedly impersonated) user:
this._service.Credentials = new WebCredentials(CredentialCache.DefaultNetworkCredentials);
Also, I've tried using the Exchange ImpersonatedUserId object using the email address:
this._service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, from);
which returns the following exception:
The account does not have permission to impersonate the requested user.
By default and as a security measure, Windows will prevent you from delegating your credentials from the web server to Exchange. This means you cannot impersonate the user accessing your web site.
This is known as the "server double hop" scenario. The first "hop" is from the user's machine to the web server, and the second "hop" is from the web server to the Exchange server (Google will give you lots of hits on server double hop).
This is a good thing because it will prevent any hackers from moving around your servers.
The reason it is working on your development machine is that there is only one "hop" from your local web server to the Exchange server.
To solve it you need to allow the web server to delegate the credentials to the Exchange server. This is called Kerberos delegation and must be set up by your system administrator somehow in the Active Directory (which is beyond my knowledge).
I tried to change the AD object setting to Trust this computer for delegation.. (you need AD admin rights) but that didn't solve the problem.
My breakthrough was to set the Identity of the Application Pool (Advanced Settings...) to NetworkService. It worked also with LocalService and LocalSystem, but be careful because they have elevated rights.
What surprised me, that it didn't work with Custom account, when I entered the AD admin account that in reality got all the rights for the exchange system.
general infos about my application:
ASP.CORE 2.1 webservice
Windows Server 2016
IIS 10.0.x
internal corporate network

Configure Azure web role to start app domain on launch

Azure has a fantastic ability to roll updates so that the entire system is not offline all at once. However, when Azure updates my web roles, the AppDomains are understandably recycled. Sometimes the ASP.NET startup code can take over a minute to finish initializing, and that's only once a user hits the new server.
Can I get Azure to start the AppDomain for the site and wait for it to come up before moving on to the next server? Perhaps using some magic in the OnStart method of WebRole?
See Azure Autoscale Restarts Running Instances which includes the following code:
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
string ip = null;
foreach (IPAddress ipaddress in ipEntry.AddressList)
{
if (ipaddress.AddressFamily.ToString() == "InterNetwork")
{
ip = ipaddress.ToString();
}
}
string urlToPing = "http://" + ip;
HttpWebRequest req = HttpWebRequest.Create(urlToPing) as HttpWebRequest;
WebResponse resp = req.GetResponse();
return base.OnStart();
}
}

AppHarbor NopCommerce running issue

I uploaded nopcommerce solution to appharbor (using this method Can't build notcommerce project under appharbor) and solution succesfully builded, but I receiving 403 error - Forbidden: Access is denied when trying to open page(Allow write-access to file system is set to true).
Thanks and hope for your help
The problem is that the standard NopCommerce solution contains two Web Projects. AppHarbor only deploys one web project per application, and in this case, we happen to deploy Nop.Admin which is not what you want.
To resolve this, you should take advantage of the AppHarbor solution file convention and create an AppHarbor.sln solution file that only references the Nop.Web project.
We use a wrapper in our base controller to ensure that all of our code is oblivious to appharbor port changing.
First, fix in Webhelper.cs:75
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null)
return url;
if (includeQueryString)
{
string storeHost = GetStoreHost(useSsl);
if (storeHost.EndsWith("/"))
storeHost = storeHost.Substring(0, storeHost.Length - 1);
url = storeHost + _httpContext.Request.RawUrl;
}
else
{
#if DEBUG
var uri = _httpContext.Request.Url;
#else
//Since appharbor changes port number due to multiple servers, we need to ensure port = 80 as in AppHarborRequesWrapper.cs
var uri = new UriBuilder
{
Scheme = _httpContext.Request.Url.Scheme,
Host = _httpContext.Request.Url.Host,
Port = 80,
Path = _httpContext.Request.Url.AbsolutePath,
Fragment = _httpContext.Request.Url.Fragment,
Query = _httpContext.Request.Url.Query.Replace("?", "")
}.Uri;
#endif
url = uri.GetLeftPart(UriPartial.Path);
}
url = url.ToLowerInvariant();
return url;
}
So what we did is simply add files from https://gist.github.com/1158264 into Nop.Core\AppHarbor
and modified base controllers:
nopcommerce\Presentation\Nop.Web\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(RequestContext requestContext)
{
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current),
requestContext.RouteData));
}
//Same file from here downwards...
}
nopcommerce\Presentation\Nop.Web.Admin\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//set work context to admin mode
EngineContext.Current.Resolve<IWorkContext>().IsAdmin = true;
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current), requestContext.RouteData));
//base.Initialize(requestContext);
}
//Same file from here downwards...
}
Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
To do this, follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true
refrence :https://support.microsoft.com/en-us/kb/942062

How to Start/Stop a Windows Service from an ASP.NET app - Security issues

Here's my Windows/.NET security stack:
A Windows Service running as LocalSystem on a Windows Server 2003 box.
A .NET 3.5 Website running on the same box, under "default" production server IIS settings (so probably as NETWORKSERVICE user?)
On my default VS2008 DEV environment I have this one method, which gets called from the ASP.NET app, which works fine:
private static void StopStartReminderService() {
ServiceController svcController = new ServiceController("eTimeSheetReminderService");
if (svcController != null) {
try {
svcController.Stop();
svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
svcController.Start();
} catch (Exception ex) {
General.ErrorHandling.LogError(ex);
}
}
}
When I run this on the production server, I get the following error from the ServiceController:
Source: System.ServiceProcess ->
System.ServiceProcess.ServiceController -> IntPtr
GetServiceHandle(Int32) -> System.InvalidOperationException Message:
Cannot open eTimeSheetReminderService service on computer '.'.
Why is this happening, and how do I fix it?
EDIT:
The answer is below, mostly in comments, but to clarify:
The issue was Security related, and occurred because the NETWORKSERVICE account did not have sufficient rights to Start/Stop a service
I created a Local User Account, and added it to the PowerUsers Group (this group has almost admin rights)
I don't want my whole Web App to impersonate that user all the time, so I impersonate only in the method where I manipulate the service. I do this by using the following resources to help me do it in code:
MS KB article and this, just to get a better understanding
NOTE: I don't impersonate via the web.config, I do it in code. See the MS KB Article above.
To give IIS permission to start/stop a particular service:
Download and install Subinacl.exe. (Be sure to get the latest version! Earlier versions distributed in some resource kits don't work!)
Issue a command similar to: subinacl /service {yourServiceName} /grant=IIS_WPG=F
This grants full service control rights for that particular service to the built-in IIS_WPG group. (This works for IIS6 / Win2k3.) YMMV for newer versions of IIS.)
Try adding this to your Web.Config.
<identity impersonate="true"/>
This was a good question that intrigued me as well...
So here is what I did to solve this problem:
Step 1: Create a Windows user account on the local machine with minimal rights.
Step 2: Give this user rights to start and stop the service via subinacl.exe
i.e. subinacl.exe /service WindowsServiceName /GRANT=PCNAME\TestUser=STOE
Dowload from : http://www.microsoft.com/en-za/download/details.aspx?id=23510
Step 3: Use Impersonation to impersonate the use created in Step 1 to start and stop the Service
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext _impersonationContext;
[DllImport("advapi32.dll")]
// ReSharper disable once MemberCanBePrivate.Global
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
// ReSharper disable once MemberCanBePrivate.Global
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
// ReSharper disable once MemberCanBePrivate.Global
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
// ReSharper disable once MemberCanBePrivate.Global
public static extern bool CloseHandle(IntPtr handle);
private bool _impersonate;
public bool ImpersonateValidUser(String userName, String domain, String password)
{
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
if (_impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
_impersonate = true;
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
_impersonate = false;
return false;
}
#region Implementation of IDisposable
#endregion
#region Implementation of IDisposable
private void Dispose(bool dispose)
{
if (dispose)
{
if (_impersonate)
_impersonationContext.Undo();
_impersonationContext.Dispose();
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
public static void StartStopService(bool startService, string serviceName)
{
using (var impersonateClass = new Impersonation())
{
impersonateClass.ImpersonateValidUser(Settings.Default.LocalUsername, Settings.Default.Domain, Settings.Default.Password);
using (var sc = new ServiceController(serviceName))
{
if (startService)
sc.Start();
else if (sc.CanStop)
sc.Stop();
}
}
}
Update for IIS 8 (and maybe some slightly earlier versions)
The usergroup IIS_WPG does not exist anymore. It has changed to IIS_IUSRS.
Also, to start stop a service it is not neccesary to give full permissions (F). Permissions to start, stop and pause a service (TOP) should be enough. As such the command should be:
subinacl /service {yourServiceName} /grant=IIS_IUSRS=TOP
Note that you need to point the command prompt (preferably elevated to run as administrator) to C:\Windows\System32 Folder before running this command.
Also make sure that you have copied the subinacl.exe file to C:\Windows\System32 from the installation directory if there is an error.
Just a hunch, but it does not appear to me the error is necessarily related to security. Did you give the service the same name on the production server?
If your web application has the database and windows service can access it, you can just use the flag in the DB to restart the service. In the service, you can read this flag and restart if not busy etc. Only in case if you can modify the code of the service.
If it's third party service you can create your own windows service and use database config to control (restart) services. It's the safe way and gives you much more flexibility and security.

Resources