IIS Custom Duration Logging - asp.net

My ASP.NET Web Application serves on IIS 7.0 and .NET 4.0
I want to measure total duration for "any request to my web services methods (asmx)"
This log needs to include some custom data (for example ID, given by my application).
I am planning to follow these steps:
-- Run application in Integrated Pipeline mode
-- Implement custom http module and attach to BeginRequest and EndRequest events of HttpApplication.
-- In BeginRequest method, Start Stopwatch
-- In EndRequest method;
end Stopwatch; read custom ID data from context.Session;
write results to database or file log.
Do you think it is a good method?
What is the best way to achieve this, would you recommend other?

IIS will log time taken, and you can add any custom data that you wish.
You can even use ETW to read log objects instead of parsing the log files.
IIS logging:
http://msdn.microsoft.com/en-us/library/ms525410(v=vs.90).aspx
What "time taken" means:
http://support.microsoft.com/kb/944884/en-us
Writing custom data to IIS logs from your app:
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.appendtolog.aspx
Optionally interfacing through ETW instead of reading the logs from the file system:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb968803(v=vs.85).aspx
http://www.iis.net/learn/get-started/whats-new-in-iis-85/logging-to-etw-in-iis-85

Related

Akka.NET actor system in ASP.NET

I created a service with a RESTful API in ASP.NET, hosted in IIS. Inside this service, I would like to create an actor system with Akka.NET.
Upon creating the actor system:
var actorSystem = ActorSystem.Create("myActorSystem");
The following exception is thrown:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.dll
Additional information: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%# Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.
The actor system is inherently a concurrent system with asynchronous messages being exchanged between actors. As explained here, this actor system would not survive IIS taking down the AppDomain, which is probably why the aforementioned exception is thrown.
This article explains how to run background tasks in ASP.NET. However, I don't see how I could use this for my actor system, as I have no control over the lifecycle of background tasks that might be created by Akka.NET.
Is there a way to make this work, or should I abandon the idea of having an actor system in an ASP.NET application?
EDIT: I also saw a question on Stackoverflow about implementing a REST service using Akka. Any advice about a solution similar to the Spray toolkit, but working for Akka.NET would be welcome.
I've used Akka.NET and Akka.Remote inside ASP.NET MVC applications that are doing up to 1000 requests per second on EC2 - so I'll share some of the tips and tricks I used to get it up and running successfully. Had a prototype version that even used Akka.Cluster but ended up not shipping that version.
Best place to call ActorSystem.Create is inside Global.asax Application_Start().
Hang onto a static reference to the ActorSystem object inside Global.asax itself, using a static field or property. Helps ensure that the ActorSystem itself doesn't get garbage-collected in long-running applications.
Create a separate static helper class to initialize any top-level actors your applications needs - i.e. actors at the top of the /user/ hierarchy. This class should also provide actor paths that your ASP.MVC controllers and action methods can use for Tell and Ask operations.
Creating the ActorSystem is a bit of an expensive operation, because lots of system-level stuff gets fired up at once. It's definitely best to do this once at application startup and then just cache the result inside the Application class.
Creating individual actor instances is cheap - you should be able to do this no-problem inside ASP.NET MVC action methods. If you see this error come up again, please let us know what part in the request-handling process this error occurred and with which version of ASP.NET.
Edit: added some updated guidance for how to do this on ASP.NET Core
https://petabridge.com/blog/akkadotnet-aspnetcore/
Keep your ActorSystem as a shared property in some static class container - this way you may access it from the rest of your application. Actor system initialization/disposal can be done by:
Global.asax - use ActorSystem.Create(...) inside Global.asax Application_Start and dispose it with system.Shutdown() on Application_End.
OWIN - create actor system in OWIN's Startup.Configuration method and shut it down by binding to host.OnAppDisposing event (how-to link).
Remember that IIS will startup your web app only after first request and tear it down automatically after some time when it's idle. Therefore make sure, that your deployment script will ping application after publishing and set idle timeout (link) for long enough if you want your Akka actor system to run continuously.
Second option
Separate your Actor System logic and deploy it, for example, as a Windows Service (or Linux deamon). Turn on Akka.Remoting for it and create a proxy client, which will forward all application long-running sensitive tasks to external service. Similar solution is often used for things such as schedulers or event buses, when your application logic must be working continuously.

Getting the Server in Global.asax in ASP.NET MVC 4

When our ASP.NET MVC 4 app starts, we need to set a property on a Log4Net Appender which depends on what the site is.
Is there a way to get the 'http://www.site.com' part some time in the sites initial load, perhaps in Global.asax?
Overview:
If the server is www.site2.com then set the Appender.SomeValue = "555"
If the server is www.site.com then set the Appender.SomeValue = "123"
Because many sites will point to the same code base we don't know what we need to set Appender.SomeValue to until it runs.
I think methods in Global.asax would run, only in response to a request. And almost everywhere inside the ASP.NET, you have access to HttpContext.Current.Request.Url.
Also there is a method that runs way before Application_Start, and that is a method decorated with PreApplicationStartMethodAttribute attribute.
One approach is to use WMI (Windows Management Instrumentation) to get access to the current website, it's bindings and thus the site address.
Pre-application start is more limited as it is run before the application is started, more for initializing di containers. To be safe I would put the code in a new static method defined in global.asax.cs that is called by application_start method at this point access to HttpContext.Current.request.Url should be safe

Integrated app pool, modules, and HttpApplication pipeline on IIS7.5

Given an application pool that runs on integrated mode, the apppool is able to provide service to "Managed Handler Requests" (GET an aspx page) as well as "non-Managed Handler Requests" (GET a jpg file).
When processing a MHR request the app pool should consider all modules but for nonMHRs should not consider the modules marked with the Managed Handler precondition.
Has the app pool two different HttpAplication pipelines (one for MHRs and the other for nonMHRs) ?
Or he only has one pipeline and is able to decide which httpAplication event handlers are raised depending of the request?
I guess the app pool decides if the request is managed or not, before httpApplication starts the BeginRequest. At least before the AuthenticateRequest. Is that right?
Response in the link:
All resources served by IIS are mapped to a handler in configuration. If the configuration mapping does not exist, requests for the resource will receive a 404 HTTP status. In addition to the configuration mapping, which takes place before the pipeline begins, the handler mapping can be changed during request execution ...
The Init function of the modules are only executed once (maybe in the application pool startup) independently of the Managed Handler precondition?
I guess the apppool doesn't create the whole pipeline (registering httpaplication events and so) for each request.
Thanks in advance,
UPDATE1: After reading the link I still "see" two diferent pipelines given a single apppool.
By diferent pipelines I mean two diferent sets of event handlers registered in the IIS pipeline:
BEGIN_REQUEST
AUTHENTICATE_REQUEST
AUTHORIZE_REQUEST
RESOLVE_REQUEST_CACHE
MAP_REQUEST_HANDLER
ACQUIRE_REQUEST_STATE
PRE_EXECUTE_REQUEST_HANDLER
EXECUTE_REQUEST_HANDLER
RELEASE_REQUEST_STATE
UPDATE_REQUEST_CACHE
LOG_REQUEST
END_REQUEST
When an application pool in integrated mode starts, it can look up the modules section and can execute the Init function of each module (indepentdently of the precondition setting). The Init function of each module registers itself in some IIS pipeline stages. But at runtime when processing non-managed requests it should skip the event handlers of modules with precondition managed handler. How can do that?
UPDATE2:
From my understanding, an app pool (the windows process) host an ASP.Net runtime (httpRuntime in System.Web?). This runtime contains a pool of httpApplication objects. When app pool starts (or maybe until first request arrive) several httpApplications are instantiated. At this time the Init method of the httpModules (under modules in web.config) are called.
Until IIS7 integration mode appearance I thought all httpApplication objects would be clones, but because depending of the type of handler's request (managed or non managed) some httpModules should be considered or not, I deduce that the httpRutime contains two httpApplication pools or maybe a given httpApplication object is only able to process managed handler requests or non-managed hadler requests, but never the two...
I think you can read this one
http://blogs.msdn.com/b/tmarq/archive/2007/08/30/iis-7-0-asp-net-pipelines-modules-handlers-and-preconditions.aspx
In there you see that the IIS has only one pipeline. The "classic" way of serving asp.net requests begins in the IIS pipeline’s EXECUTE_REQUEST_HANDLER event. Think of ASP.NET in classic mode as a pipeline within the IIS pipeline.
With the integrated mode you can basically plug in managed code in the whole IIS pipeline series of events, like adding asp.net forms authentication to static files like .jpg

Ihttpmodule ,Ihttphandler .NET

I have some doubt over HttpModule and HttpHandler Please help me to clarify
1)In HttpModule I have noticed methods Init called only once . context_BeginRequest and context_EndRequest etc method calling for each request.
Is it guaranteed that for a module Init will call once for different users(or different request) and BeginRequest etc will call every time for different users (or different request) ?
2)Is there any possibility that Application_Start(global.asax) can run more than once because there may be more than one application object
3) Since application object can be different (from application pool) In this case how Application data is shared between different users?
4) In HttpHandler ProcessRequest method will call for each request (or for each user).
Thanks
Ritu
"Is it guaranteed that for a module Init will call once for different users(or different request) and BeginRequest etc will call every time for different users (or different request)?"
The init method will be called when the app pool starts / when the application is started for the first time. This is when the module is loaded.
The BeginRequest method is called every time the application starts handling a new HTTP request.
"2)Is there any possibility that Application_Start(global.asax) can run more than once because there may be more than one application object"
There is not more than one application in a particular folder. IIS doesn't work that way. Only one global.asax per application, and Application_Start will only be called once for each application unless the app pool is reset.
"3) Since application object can be different (from application pool) In this case how Application data is shared between different users?"
Depends where you're storing this application data and what you're using to retrieve it. I'm not sure what you mean about this. Session data should be scoped to an individual application (certainly for in-process session state server, and if properly configured also for out-of-process session state server)
"4) In HttpHandler ProcessRequest method will call for each request (or for each user)."
Yes, but only for requests which are mapped to your handler. Conversely, HttpModule can be called for ALL requests.

Calling a method in an ASP.NET application from a Windows application

Other than using a web service, is there anyway to call a method in a web app from a windows application? Both run on the same machine.
I basically want to schedule a job to run a windows app which updates some file (for a bayesian spam filter), then I want to notify the web app to reload that file.
I know this can be done in other ways but I'm curious to know whether it's possible anyway.
You can make your windows app connect to the web app and do a GET in a page that responds by reloading your file, I don't think it is strictly necessary to use a web service. This way you can also make it happen from a web browser.
A Web Service is the "right" way if you want them to communicate directly. However, I've found it easier in some situations to coordinate via database records. For example, my web app has bulk email capability. To make it work, the web app just leaves a database record behind specifying the email to be sent. The WinApp scans periodically for these records and, when it finds one with an "unprocessed" status, it takes the appropriate action. This works like a charm for me in a very high volume environment.
You cannot quite do this in the other direction only because web apps don't generally sit around in a timing loop (there are ways around this but they aren't worth the effort). Thus, you'll require some type of initiating action to let the web app know when to reload the file. To do this, you could use the following code to do a GET on a page:
WebRequest wrContent = WebRequest.Create("http://www.yourUrl.com/yourpage.aspx");
Stream objStream = wrContent.GetResponse().GetResponseStream();
// I don't think you'll need the stream Reader but I include it for completeness
StreamReader objStreamReader = new StreamReader(objStream);
You'll then reload the file in the PageLoad method whenever this page is opened.
How is the web application loading the file? If you were using a dependency on the Cache object, then simply updating the file will invalidate the Cache entry, causing your code to reload that entry when it is found to be null (or based on the "invalidated" event).
Otherwise, I don't know how you would notify the application to update the file.
An ASP.NET application only exists as an instance to serve a request. This is why web services are an easy way to handle this - the application has been instantiated to serve the service request. If you could be sure the instance existed and got a handle to it, you could use remoting. But without having a concrete handle to an instance of the application, you can't invoke the method directly.
There's plenty of other ways to communicate. You could use a database or some other kind of list which both applications poll and update periodically. There are plenty of asynchronous MQ solutions out there.
So you'll create a page in your webapp specifically for this purpose. Use a Get request and pass in a url parameter. Then in the page_load event check for this paremter. if it exists then do your processing. By passing in the parameter you'll prevent accidental page loads that will cause the file to be uploaded and processed when you don't want it to be.
From the windows app make the url Get request by using the .Net HttpWebRequest. Example here: http://www.codeproject.com/KB/webservices/HttpWebRequest_Response.aspx

Resources