I have written some code in the application_start() method in my global.asax file. It does not get called when I deploy my application on IIS server. The code is accessible when I run it in the .NET framework.
I've tried to restart the application many times, but it's still not working.
I've also tried the suggestion from the following link.
Application_Start not firing?
There are few things you need to know before you are trying to debug Appplication_Start. There are -
One : When the code executes and why it is almost impossible to debug by attaching to it.
The application start method is executed when the application pool starts and your website is being started up for the first time. If you deploy new deliverables to IIS, then IIS might restart it itself, but there is no guarantee that it will. So, deploying new codes does not guarantee that it will restart the pool and he execution of application start. You should restart your application pool to guarantee execution of application start.
While debugging IIS applications, Visual Studio attaches itself to a process something named w3wp.exe or similart (I forgot the actual executable name), which is the worker process and only available after, remember after, your application pool is up and your site is up. So, in other words, if you are seeing this in service list, then the application start has already been executed and attaching to it will not give you a chance to debug it. It is kind of a tug of war with time.
So, in other words, it is kind of impossible to debug application start unless you are very very quick.
Two, the solution 1 - With Dev Server
Launch your application in visual studio with Asp.net development server or IIS express, then you will be able to debug. But if you really want to debug on IIS, then check the next section
Two, the solution 2 - With IIS
There is a library in the name System.Diagnostics, Debuggerand it has a nice way to call debugger in code. You can read it here - http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx
Modify you application start with this -
public void Application_Start(){
....... //other codes
Debugger.Break() or Debugger.Launch()
}
When this line executes, IIS will halt execution, and will show you a debugger selector window (similar to the one attached), keep your solution open in vs and select that vs from the list, will be able to debug as usual... :)
In case you are using windows 8 and the debugger does not launch, read this article to enable it -
http://blogs.msdn.com/b/mapo/archive/2013/11/07/debugger-launch-not-displaying-jit-debugger-selection-popup-on-windows-8-8-1.aspx
Three: A very important thing
I noticed that you said, you are adding db entries in Application_Start. You should keep in mind that, Application_Start does not have a HttpContext, ViewContext, So your db access code may fail for so many others reasons.
Make sure that the Global.asax file is actually deployed to the destination folder in the root. If the file is not present then the code behind you have written for Application_Start will never be called.
Also make sure the signature is correct
public class Global : System.Web.HttpApplication {
protected void Application_Start(object sender, EventArgs e) {/*do something here like logging so you know it was called*/}
}
If you are running Server 2008R2 (or earlier) and/or IIS 7.5, you might want to look into the Application Initialization module. This can be downloaded here:
www.iis.net/downloads/microsoft/application-initialization
With IIS versions prior to 8.0, the application start is not called until the first web request arrives. I'm reading your question as you want your application start to be fired before the first web request, yes?
Here is a fantastic guide to configuring this module (if it applies to you):
https://blogs.msdn.microsoft.com/benjaminperkins/2014/01/07/configure-the-iis-application-initialization-module/
The key takeaways is that you need to set your app pool to 'AlwaysRunning' instead of 'OnDemand'. You also need to set a preloadEnabled flag for your website. Once both of these are done, fire off an iisreset and you should see the results of your application start (look in the database since it's writing there).
Other answers are relevant as well, in that this is tough to debug and you're missing all the niceties you're used to such as a httpcontext in app start.
If you are running IIS 8.0 - you should still read the above link to configure preloading.
This did work for me:
Menu -> Build -> Clean Solution
Menu -> Build -> Rebuild Solution
Then, Application_Start() was fired only for the first time.
In my case in production environment App_global.asax.compiled was missing and all content of global.asax not fired.
Related
I made a Window service and let it work automatically and under localsystem account, when the service starts it fires this message for me and then stops
The [service name] service on local computer started and then stopped. Some Services stop automatically if they are not in use by another services or programs.
What's the problem and what's the solution?
Either you are not starting any threads on the OnStart method to do work, or there is an exception raised within your OnStart method.
If an exception is thrown, it will appear in the Windows Event log. The Windows Event log is a good place to start in any case.
Generally an OnStart method looks like this:
Thread _thread;
protected override void OnStart(string[] args)
{
// Comment in to debug
// Debugger.Break()
// Do initial setup and initialization
Setup();
// Kick off a thread to do work
_thread = new Thread(new MyClass().MyMethod)
_thread.Start();
// Exit this method to indicate the service has started
}
This particular error message means what it says - that your service has started but then quite soon it exited for some reason. The good news is that your service is actually doing something, so you have the executable configured and running as a service properly.
Once started, for some reason it is quitting. You need to find out why this is. Add some debugging to tell you its up and running and known exit cases. If that doesn't reveal the problem then add some debugging to let you know it's still running and work backwards from when that stops.
Are you tracing out any debug information? Most likely an exception is being thrown during your initialization. I would trace out all your exceptions and use Debugview to view them.
I had a similar problem that occurred because my Event Logs were full and the service was unable to write to them. As such, it was impossible to debug by looking for messages in the Event Viewer. I put a try/catch and dumped the exception out to a file. I had to change the settings on my logs to fill as needed instead of every 7 days and this allowed the services to start.
Of course, the root of the problem for me is that I have a nVidia driver issue that is flooding my event logs and now I'm probably beating on the disk, but that's another issue.
Maybe you need to run the service as Local System Account. See this post by Srinivas Ganaparthi.
I had the same issue starting JBoss, then I changed the JAVA_HOME variable, it worked for me. It was the JBoss version that doesn't support the 1.6, it supports 1.5.
I had similar problem and it turned out in my case that the program simply crashed in OnStart method. It tried to read some file that it couldn't find but I suppose that any other program crash would give the same result. In case of Windows forms application you would get some error message but here it was just "your service started and stopped"
If you ever need, like me to read some files from the directory where Windows Service .exe is located, check this topic:
Getting full path for Windows Service
In my case, a method in my service, was being called recursively (as no terminate condition being true) and after specific time my service was being stopped.
I've created the WCF service and some simple WPF application consuming it. When I'm running the project from within Visual Studio, the WCF Test Client opens and the application works just fine, method defined in service work.
But I need to host this WCF service in a Windows Service. I've followed this, installed the services using Installutil.exe and the ran the service. Everything went fine, it's working.
Yet, when I'm trying to open the executable file with WPF application directly from the debug folder of the app, I'm getting this error:
zad8. has stopped working
After choosing the option to debug it with new instance of VS I get
XamlParseException occured in PresentationFramework.dll
The stack trace shows something like:
connection can't be started, because the target computer is actively refusing it
Do you have any idea what could go wrong?
Fortunately, I've managed to come up with solution. I think I should post it, maybe one day it will help somebody:)
I actually did two mistakes, but one of them was unfortunately caused by the mentioned tutorial (here) in connection with my temporary blackout.
In step 5, point 8 of this tutorial, there's an example of overriding OnStart() method:
protected override void OnStart(string[] args)
{
if (myServiceHost != null)
{
myServiceHost.Close();
}
myServiceHost = new ServiceHost(typeof(Service1));
myServiceHost.Open();
}
Beware, that Service1 is ambiguous in this context, because it's name of the Windows Service project class as well as the name of WCF Service class. It should be written with fully qualified name (here it is WcfServiceLibrary1.Service1). In my case, the service name was different, and I just put the Service1 in there in a hurry. Anyway..
In case, someone has it all behind and still encounters the same problem (with app stopped working), I think that you should try open the project in Visual Studio and try to debug the client consuming application as a new instance (right click on the project-> Debug -> Start as new instance...).
It might seem trivial, but when u hit F5 or Ctrl+F5 then even if u have only those project set as startup project, VS will host it's client anyway. In my case it did matter, because I needed to use isolation storage file. And as it was kept on the service side, then I had this file created in IIS server created by VS. Somehow, my method of creating such file had set FileMode.Open() and it was causing the crush, because in Windows Service it didn't exist and the new one couldn't be created and that was neccessary to run it correctly.
What's more it just showed me that this question couldn't be answered properly, cause the data I've provided was not enough and it was delicate.
Cheers:)
I am using VS2013 Premium to publish a site to Windows Server 2012.
All files publish ok except these:
SqlServerTypes\x64\msvcr100.dll
SqlServerTypes\x64\SqlServerSpatial110.dll
SqlServerTypes\x86\msvcr100.dll
SqlServerTypes\x86\SqlServerSpatial110.dll
I get this kind of errors for each of the above files I tried to publish:
Web deployment task failed. (The file 'msvcr100.dll' is in use. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_FILE_IN_USE.)
Interrestingly, these files were published the first time (when they were not on the server), then they are no longer overwritten. Tried with 2 different web servers.
I have followed the guide here:
http://blogs.msdn.com/b/webdev/archive/2013/10/30/web-publishing-updates-for-app-offline-and-usechecksum.aspx
...But it only managed to put the site offline (VS is placing the app_offline.htm) but publish still fails with the same error.
All other files publish perfectly.
Any ideas?
You can take you app offline during publishing which hopefully should free up the lock on the file and allow you to update it.
I blogged about this a while back. The support outlined was shipped inside of the Azure SDK and Visual Studio Update. I don't remember the exact releases but I can find out if needed. Any update dating around/after that blog post should be fine.
Prerequisites:
VS 2012 + VS update / VS 2013 + VS Update / VS2015
MSDeploy v3
Note: if you are publishing from a CI server the CI server will need the updates above as well
Edit the publish profile
In VS when create a Web Publish profile the settings from the dialog are stored in Properties\PublishProfiles\ as files that end with .pubxml. Note: there is also a .pubxml.user file, that file should not be modified
To take your app offline in the .pubxml file add the following property.
<EnableMSDeployAppOffline>true</EnableMSDeployAppOffline>
Notes
ASP.NET Required
The way that this has been implemented on the MSDeploy side is that an app_offline.htm file is dropped in the root of the website/app. From there the asp.net runtime will detect that and take your app offline. Because of this if your website/app doesn't have asp.net enabled this function will not work.
Cases where it may not work
The implementation of this makes it such that the app may not strictly be offline before publish starts. First the app_offline.htm file is dropped, then MSDeploy will start publishing the files. It doesn't wait for ASP.NET to detect the file and actually take it offline. Because of this you may run into cases where you still run into the file lock. By default VS enables retrys so usually the app will go offline during one of the retrys and all is good. In some cases it may take longer for ASP.NET to respond. That is a bit more tricky.
In the case that you add <EnableMSDeployAppOffline>true</EnableMSDeployAppOffline> and your app is not getting taken offline soon enough then I suggest that you take the app offline before the publish begins. There are several ways to do this remotely, but that depends on your setup. If you only have MSDeploy access you can try the following sequence:
Use msdeploy.exe to take your site offline by dropping app_offline.htm
Use msdeploy.exe to publish your app (_make sure the sync doesn't delete the app_offline.htm file_)
Wait some amount of time
Publish the site
Use msdeploy.exe to bring the app online by deleting app_offline.htm
I have blogged how you can do this at http://sedodream.com/2012/01/08/howtotakeyourwebappofflineduringpublishing.aspx. The only thing that is missing from that blog post is the delay to wait for the site to actually be taken offline. You can also create a script that just calls msdeploy.exe directly instead of integrating it into the project build/publish process.
I have found the reason why the solution at
http://blogs.msdn.com/b/webdev/archive/2013/10/30/web-publishing-updates-for-app-offline-and-usechecksum.aspx
did not work for the original poster, and I have a workaround.
The issue with the EnableMSDeployAppOffline approach is that it only recycles the app domain hosting the application. It does not recycle the app pool worker process (w3wp.exe) which the app domain lives in.
Tearing down and recreating the app domain will not affect the Sql Server Spatial dlls in question. Those dlls are unmanaged code which are manually loaded via interop LoadLibray calls. Therefore the dlls live outside the purview of the app domain.
In order to release the files locks, which the app pool process puts on them, you need to either recycle the app pool, or unload the dlls from memory manually.
The Microsoft.SqlServer.Types nuget package ships a class which is used to load the Spatial dlls called SqlServerTypes.Utilities. You can modify the LoadNativeAssemblies method to unload the unmanaged dlls when the app domain is unloaded. With this modification when msdeploy copys the app_offline.htm the app domain will unload and then unload the managed dlls as well.
[DllImport("kernel32.dll", SetLastError = true)]
internal extern static bool FreeLibrary(IntPtr hModule);
private static IntPtr _msvcrPtr = IntPtr.Zero;
private static IntPtr _spatialPtr = IntPtr.Zero;
public static void LoadNativeAssemblies(string rootApplicationPath)
{
if (_msvcrPtr != IntPtr.Zero || _spatialPtr != IntPtr.Zero)
throw new Exception("LoadNativeAssemblies already called.");
var nativeBinaryPath = IntPtr.Size > 4
? Path.Combine(rootApplicationPath, #"SqlServerTypes\x64\")
: Path.Combine(rootApplicationPath, #"SqlServerTypes\x86\");
_msvcrPtr = LoadNativeAssembly(nativeBinaryPath, "msvcr100.dll");
_spatialPtr = LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial110.dll");
AppDomain.CurrentDomain.DomainUnload += (sender, e) =>
{
if (_msvcrPtr != IntPtr.Zero)
{
FreeLibrary(_msvcrPtr);
_msvcrPtr = IntPtr.Zero;
}
if (_spatialPtr != IntPtr.Zero)
{
FreeLibrary(_spatialPtr);
_spatialPtr = IntPtr.Zero;
}
};
}
There is one caveat with this approach. It assumes your application is the only one running in the worker process that is using the Spatial dlls. Since app pools can host multiple applications the file locks will not be released if another application has also loaded them. This will prevent your deploy from working with the same file locked error.
There are known issues with IIS and file-locks (why they aren't solved yet i dont know).
The question i want to ask however is if you even need to re-deploy these files?
I recognize the file-names and recall them to be system-files which should either already be present on the server or simply not need to be re-deployed.
I am not very experienced when it comes to IIS but i have ran into this problem before and several of my more experienced co-workers have told me that this is as i said a known IIS-issue and i believe the answer to your question is:
Avoid deploying unnecessary files.
try again
Reset website
try again
iisreset
I think what would be the easiest thing to do is to make these dll's as CopyLocal as true. I am assuming these dll's are pulled out from program files folder. Try marking them as copylocal true and do a deployment.Try to stop any IIS local process running in your local machine.
Watch out you don't have one of those new-fangled cloud backup services running that is taking file locks - and also you don't have things open in explorer or a DLL inspection tool.
I think it's kind of ridiculous that MS doesn't make better provisions for this problem. I find that 9 times out of 10 my deployment works just fine, but then as our traffic increases that can become 1 in 10 times.
I am going to solve the problem with :
two applications MySite.A and MySite.B, where only one is running at a time.
I always then deploy to the dormant site.
If there's a problem during the deployment it will never cause the whole site to go down.
If there's a major problem after deployment you can revert back very easily.
Not quite sure how I'm implementing it, but I think this is what I need to do.
I researched a lot but got nothing...
Application_Start event is not firing when published the site. However it works fine in localhost. After publishing i got the App_global.asax.dll and App_GlobalResources.compiled in Bin folder and also have PrecompiledApp.config at root.
Application_Start event is fired when the Application is ran for the first time. It has nothing to do with restarting machine or restarting IIS. Did you tried in making a new sample app and test that Application_Start event of that application ran well or not. If yes then you application configuration is corrupted someway.
maybe restarting your application pool can help you.
Possibly it's this event is fired as expected, but since you're executing a precompiled web, and in release mode, there're no debugging symbols - in the case of trying to remotely debug your application -.
Another possible reason is it's firing, but some exception is thrown within Application_Start handler, and since this is called once per application life-cycle, you'll need to recycle application's pool or restart the entire IIS.
Your code, told in other comments:
protected void Application_Start(Object sender, EventArgs e) {
logfile.ErrorLog("UserErrorLog\\UserErrorLog.txt", "Application_Start method executed at " + System.DateTime.Now);
DoSomeWork();
logfile.ErrorLog("UserErrorLog\\UserErrorLog.txt", "Application_Start method execution ends at " + System.DateTime.Now);
}
Writing to UserErrorLog\\UserErrorLog.txt will be problematic in a normal IIS setup, it will attempt to write somewhere within %SYSTEMROOT%\System32\Inetsrv which is the executing directory of IIS. You need to either specify an absolute path (C:\Logs\...) or using HostingEnvironment.MapPath to resolve an application based path (HostingEnvironment.MapPath("~/App_Data/Logs/..."))
Ok, I got an asp.net web service using WSE2. It runs on a xp machine.
And I got the front end asp.net application in my win7 machine.
both in Framework 3.5.
In production environnement everthing is fine.
The problem is, when I run the "developpement" version of the front end, web services calls takes forever. And by forever, I mean eternity. Here we count eternity in minutes.
By "developpement" version, I mean that I run the instance that is bound to the visual studion (2008) solution. I use the local IIS web server.
My first thought was for a network/firewall problem between my two machines. But if, form visual studio, I "publish" the site to another virtual folder, then everithing works fine.
So I have http://localhost/MyDevApp and http://localhost/MyPublishedApp.
Both uses default app pool. Both have identical web.config. As far as I know, both virtual directories have exact same parameters.
But http://localhost/MyDevApp is terribly when calling web services, and http://localhost/MyPublishedApp runs at light's speed.
It is like this since 3 days now.
Doing some debuggin I can say that :
MyWebServiceRequest request = new MyWebServiceRequest ();
request.Url = "http://mywebserviceurl";
request.RequestSoapContext.Tokes.Add (MyUsernameToken);
//All these previous lines executes correctly, rapidly.
//THIS is the slow one.
request.CallWebServiceMethod ();
Does anyone have the slightest idea what the problem can be?
Edit
I also tried changing the virtual directory from my web site's property to something different (say http://localhost/MydDevApp2), with the same result.
Edit 2
Maybe it can be in cause, the site binded to the solution reside in c:\Projets\MySolution\MyDevApp while the "published" one is under c:\inetpub\wwwroot\MyPublishedApp. The c:\Projets folder is excluded from the antivirus scans, so normally it should be faster rather than slower.
Edit 3
I created another workspace (the solution is under team server source control) in c:\inetpub\wwwroot\Other, changed the url of the web project, compiled and run : no problem. So it really seems that the physical path where the files resides is causing this, while the fact of beeing bound to the solution is not.
Edit 4 (August 19)
Well, it seems that there not much to do. It's been about 10 days since my last update, and now the site under the new workspace is beginning to slow down too. So I moved the workspace on disk, now in c:\inetpub\wwwroot\Other2, and you know what? That's running fine again. Perhaps I will have to move it again in about 10 days.
Edit 5
I flagged my question to move to serverfault, finally it does not have nothing to do with programmation, as I first thought.
Hard to say without seeing your machine in config, but often times it means you have some kind of a problem with your dns server or hosts file that is causing the process to be slow to resolve the service.
Also, if you are using a proxy server, make sure you are bypassing it for any urls that call the service.
Finally, it appears that wse2 traces where on :
<microsoft.web.services2>
<diagnostics>
<trace enabled="true" input="InputTrace.log" output="OutputTrace.log" />
</diagnostics>
<policy>
<cache name="policyCache.config" />
</policy>
</microsoft.web.services2>
While the log file was growing more and more, it slow down and down... just disabling the trace solves the problem.