Configure Azure web role to start app domain on launch - asp.net

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();
}
}

Related

Start/Stop Continuous Azure WebJobs from Website or on call of WebAPI

I have a Continuous WebJob published on my Azure Portal which performs some tasks.
I want to run this WebJob on call of WebAPI & WebAPI should not wait for the response, it should run WebJob in the background.
I have created one WebAPI & tried to call my WebJob but it is showing nothing.
WebAPI WebJobController.cs code:
public class WebJobController : ApiController
{
public void CallWebJob()
{
try
{
//App Service Publish Profile Credentials
string username = "userName"; //userName
string password = "userPWD"; //userPWD
string URL = "https://"+username+":"+password+"#reportjobprocess.scm.azurewebsites.net/api/continuouswebjobs/ContinuousReportServiceWebJob/run";
System.Net.WebRequest request = System.Net.WebRequest.Create(URL);
request.Method = "GET";
request.ContentLength = 0;
request.GetResponseAsync();
Console.WriteLine("OK"); //no response
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong: " + ex.Message.ToString());
}
}
}
I'm totally new to WebJob & WebAPI. Please help.
You could use WebJobs API to start/stop WebJob.
Start:wiki
POST /api/continuouswebjobs/{job name}/start
Stop:wiki
POST /api/continuouswebjobs/{job name}/stop
If you want to invoke triggered webjob you could use this. It doesn't support stop triggered job.
If you still have other questions, please let me know.
Update : about credentials you could refer to this.

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

BeginGetRequestStream takes a long time for callback in WPF

I have an application that is a load tester, and uses async web api to send lots of traffic to a test server. The application has 2 GUI incarnations: one is a web app which is controlled via standard .aspx forms. Another is a WPF forms application. The http code however is the same in both cases so I'm confused as to why the performance difference.
In the WPF application there is about 30 seconds before GetRequestStreamCallback is called by the CLR. In the web application it is more like 40ms. I suspect this has something to do with the threading model in the 2 applications (there are lots of threads not shown here). Since the GetRequestStreamCallback is a callback I have no influence over the priority it is called.
Any insight is appreciated,
Aaron
public class PendingRequestWrapper
{
public HttpWebRequest request;
PendingRequestWraqpper(HttpWebRequest req) {request = req;}
}
public class Poster
{
public static void SendPost(string url) {
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url);
request.Method = "POST";
// more header setup ...
PendingRequestWrapper = new PendingRequestWrapper(request);
wrap.request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), wrap);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
PendingRequestWrapper wrap = asynchronousResult.AsyncState as PendingRequestWrapper;
try {
// End the operation
System.Diagnostics.Debug.Writeln("Received req stream for " + wrap.request.RequestUri.ToString());
Stream postStream = wrap.request.EndGetRequestStream(asynchronousResult);
} catch(Exception e)
{
// ...
}
// Use the stream
}
}
The reason WPF has slower asp.net web performance than an IIS web application by default is that the default connection limit per host is 2. Whereas in IIS application it defaults to 32k. The fix is to go:
ServicePoint myPoint = ServicePointManager.FindServicePoint(new Uri("http://example.com"));
// WPF application needs this!
myPoint.ConnectionLimit = 10000;
This is probably irrelevant to all applications except for load-testing-types that open many connections to the same host.

Clearing temp ASP.NET files on application restart

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);
}
}

.Net 2.0 ServiceController.GetServices()

I've got a website that has windows authentication enable on it. From a page in the website, the users have the ability to start a service that does some stuff with the database.
It works fine for me to start the service because I'm a local admin on the server. But I just had a user test it and they can't get the service started.
My question is:
Does anyone know of a way to get a list of services on a specified computer by name using a different windows account than the one they are currently logged in with?
I really don't want to add all the users that need to start the service into a windows group and set them all to a local admin on my IIS server.....
Here's some of the code I've got:
public static ServiceControllerStatus FindService()
{
ServiceControllerStatus status = ServiceControllerStatus.Stopped;
try
{
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
ServiceController[] services = ServiceController.GetServices(machineName);
string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();
foreach (ServiceController service in services)
{
if (service.ServiceName.ToLower() == serviceName)
{
status = service.Status;
break;
}
}
}
catch(Exception ex)
{
status = ServiceControllerStatus.Stopped;
SaveError(ex, "Utilities - FindService()");
}
return status;
}
My exception comes from the second line in the try block. Here's the error:
System.InvalidOperationException:
Cannot open Service Control Manager on
computer 'server.domain.com'. This
operation might require other
privileges. --->
System.ComponentModel.Win32Exception:
Access is denied --- End of inner
exception stack trace --- at
System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String
machineName, Int32
serviceControlManaqerAccess) at
System.ServiceProcess.ServiceController.GetServicesOfType(String
machineName, Int32 serviceType) at
TelemarketingWebSite.Utilities.StartService()
Thanks for the help/info
Note: This doesn't address enumerating services as a different user, but given the broader description of what you're doing, I think it's a good answer.
I think you can simplify this a lot, and possibly avoid part of the security problem, if you go directly to the service of interest. Instead of calling GetServices, try this:
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
string serviceName = ConfigurationManager.AppSettings["ServiceName"];
ServiceController service = new ServiceController( serviceName, machineName );
return service.Status;
This connects directly to the service of interest and bypasses the enumeration/search step. Therefore, it doesn't require the caller to have the SC_MANAGER_ENUMERATE_SERVICE right on the Service Control Manager (SCM), which remote users do not have by default. It does still require SC_MANAGER_CONNECT, but according to MSDN that should be granted to remote authenticated users.
Once you have found the service of interest, you'll still need to be able to stop and start it, which your remote users probably don't have rights to do. However, it's possible to modify the security descriptor (DACL) on individual services, which would let you grant your remote users access to stop and start the service without requiring them to be local admins. This is done via the SetNamedSecurityInfo API function. The access rights you need to grant are SERVICE_START and SERVICE_STOP. Depending on exactly which groups these users belong to, you might also need to grant them GENERIC_READ. All of these rights are described in MSDN.
Here is some C++ code that would perform this setup, assuming the users of interest are in the "Remote Service Controllers" group (which you would create) and the service name is "my-service-name". Note that if you wanted to grant access to a well-known group such as Users (not necessarily a good idea) rather than a group you created, you need to change TRUSTEE_IS_GROUP to TRUSTEE_IS_WELL_KNOWN_GROUP.
The code has no error checking, which you would want to add. All three functions that can fail (Get/SetNamedSecurityInfo and SetEntriesInAcl) return 0 to indicate success.
Another Note: You can also set a service's security descriptor using the SC tool, which can be found under %WINDIR%\System32, but that doesn't involve any programming.
#include "windows.h"
#include "accctrl.h"
#include "aclapi.h"
int main()
{
char serviceName[] = "my-service-name";
char userGroup[] = "Remote Service Controllers";
// retrieve the security info
PACL pDacl = NULL;
PSECURITY_DESCRIPTOR pDescriptor = NULL;
GetNamedSecurityInfo( serviceName, SE_SERVICE,
DACL_SECURITY_INFORMATION, NULL, NULL,
&pDacl, NULL, &pDescriptor );
// add an entry to allow the users to start and stop the service
EXPLICIT_ACCESS access;
ZeroMemory( &access, sizeof(access) );
access.grfAccessMode = GRANT_ACCESS;
access.grfAccessPermissions = SERVICE_START | SERVICE_STOP;
access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
access.Trustee.ptstrName = userGroup;
PACL pNewDacl;
SetEntriesInAcl( 1, &access, pDacl, &pNewDacl );
// write the changes back to the service
SetNamedSecurityInfo( serviceName, SE_SERVICE,
DACL_SECURITY_INFORMATION, NULL, NULL,
pNewDacl, NULL );
LocalFree( pNewDacl );
LocalFree( pDescriptor );
}
This could also be done from C# using P/Invoke, but that's a bit more work.
If you still specifically want to be able to enumerate services as these users, you need to grant them the SC_MANAGER_ENUMERATE_SERVICE right on the SCM. Unfortunately, according to MSDN, the SCM's security can only be modified on Windows Server 2003 sp1 or later.
Thanks for that line of code Charlie. Here's what I ended up doing. I got the idea from this website: http://www.codeproject.com/KB/cs/svcmgr.aspx?display=Print
I also had to add the account I'm accessing this as to the Power Users group on the server.
public static ServiceControllerStatus FindService()
{
ServiceControllerStatus status = ServiceControllerStatus.Stopped;
try
{
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();
ImpersonationUtil.Impersonate();
ServiceController service = new ServiceController(serviceName, machineName);
status = service.Status;
}
catch(Exception ex)
{
status = ServiceControllerStatus.Stopped;
SaveError(ex, "Utilities - FindService()");
}
return status;
}
And here's my other class with the ImpersonationUtil.Impersonate():
public static class ImpersonationUtil
{
public static bool Impersonate()
{
string logon = ConfigurationManager.AppSettings["ImpersonationUserName"];
string password = ConfigurationManager.AppSettings["ImpersonationPassword"];
string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
WindowsImpersonationContext impersonationContext = null;
if (LogonUser(logon, domain, password, 2, 0, ref token) != 0)
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
impersonationContext = new WindowsIdentity(tokenDuplicate).Impersonate();
//
return (impersonationContext != null);
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
}
You can try using ASP.NET impersonation in your web.config file and specify a user account that has the appropriate permissions:
<system.web>
<identity impersonate="true" userName="Username" password="Password" />
</system.web
Take a look at this article on MSDN. I believe there are other options that do not require storing the password in the web.config file such as placing it in a registry key instead.
This will cause the ASP.NET worker process to run under the context of the specified user instead of the user logged into the web application. However, this poses a security issue and I would strongly rethink your design. You may want to consider having the ASP.NET web page in turn fire off a request to some other process that actually controls the services, even another windows service or write the request to a database table that the windows service polls periodically.

Resources