I've seen way too many times in my event logs this "ContextId" for a given ASP.NET request. I've recently started looking into ETW events that are pushed out by ASP.NET, and want to re-use this ContextID in my own events that I fire.
How can I do this?
System.Threading.Thread.CurrentContext doesn't seem to have it. It's always 0.
This is a poorly documented feature, but yes you can get it.
It sits on the HttpWorkerRequest RequestTraceIdentifier property.
http://msdn.microsoft.com/en-us/library/system.web.httpworkerrequest.requesttraceidentifier.aspx
You can get it from the HttpWorkerRequest.RequestTraceIdentifier property. Note that obviously you need to have the IIS ETW (Event Tracing for Windows) feature enabled or this property will be Guid.Empty. The following is how to get it from HttpContext:
var serviceProvider = (IServiceProvider)HttpContext.Current;
var workerReqest = (HttpWorkerRequest)serviceProvider.GetService(typeof(HttpWorkerRequest));
var requestId = workerReqest.RequestTraceIdentifier;
Reference: https://github.com/serilog/serilog/commit/b289dbcde3e0f7366d90daf66e00c94f4cc58de3#diff-4934d624fc1d467b08411d520972e840R48
Related
I would like to add a tag to the System.Diagnostics.Activity object for each incoming ASP.NET Request, as soon as the request-handling starts. Is there a way I can access the ActivitySource for the Request Pipeline, and add a listener to it?
Currently I'm thinking of using a Pipeline middleware, but there has to be a more lightweight way. Especially one where other developers can't add any other middleware handlers before this one. Any ideas?
Looks like you can add it via DI at startup. The Key thing is the name of the ActivitySource. I couldn't find it in any documentation. I had to trawl through the aspnetcore code, and it looks like registers an empty name ActivitySource for the DiagnosticListener.
In any case ...
Add the following to Configure(...):
var requestActivityListener= new ActivityListener();
requestActivityListener.ShouldListenTo = activitySource => activitySource.Name == "";
requestActivityListener.ActivityStarted = activity => LetsShapeThisActivityToOurLiking(activity);
ActivitySource.AddActivityListener(requestActivityListener);
That should be it.
I am trying to add PerformanceCounter logging as part of our WebForms application. I am attempting to port an MVC implementation that uses ActionFilters to write request durations per controller action to custom performance counter instances here.
My implementation is to write an HttpModule that logs the OnBeginRequest and OnEndRequest to write to these custom performance counters. However, when I view in PerfMon, I can see the instances of my counters show up in PerfMon, but the values are all empty ("------").
I am initializing the performance counter using the following code:
var counter = new PerformanceCounter {
CategoryName = categoryName,
CounterName = counterName,
InstanceName = instanceName,
ReadOnly = false,
InstanceLifetime = PerformanceCounterInstanceLifetime.Process,
RawValue = 0,
};
Even if I didn't update the value, I would assume that the Last value would be 0, but instead it is '-------'.
The code in the sample associated with the article does work and uses the same syntax. I did notice that the counters written by the MVC attribute have no 'Parent' but the ones created by the WebForms module have a parent specified. I don't know if this has anything to do with it.
I have checked to ensure that no errors are being recorded in the Event log. I would appreciate guidance on why my performance counters are not updating.
Thanks
UPDATE 6/5/2014
I discovered that the issue was a '/' in the instance name, which gets turned into parent/instance which cannot be found once created. Make sure that you clean up your instance name to ensure that no forward slashes exist, or you won't be able to update the values.
I discovered that the issue was a forward slash ('/') in the instance name I was assigning, which gets split into parent/instance which cannot be found once created. Make sure that you clean up your instance name to ensure that no forward slashes exist, or you won't be able to update the performance counter's values.
I'm trying to figure out a way to start the MVC Mini Profiler depending on whether one of our developers is logged into our Production website. We have rolled our own authentication and authorization mechanisms, so I need to be able to inspect the current session to get the ID of the logged in user, and I cannot seem to ascertain where to best do this inspection to know when to call MiniProfiler.Start();.
Much of the time, foo winds up being null in this code sample, though according to the MSDN documentation for this event it doesn't seem like this should ever be possible:
protected void Application_PostAcquireRequestState()
{
var foo = HttpContext.Current.Session;
}
This application is using the MVC2 framework.
How can this ever be null? Also, does anyone have any good recommendations where I should start the profiler? My next guess is going to be whatever "begin request" events are available in our controller base class.
I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.
So I am working on a project which uses ASP.NET. I am trying to call Cache["key"] but the compiler complains about how System.Web.Caching.Cache is "nat valid at this point".
If I call Cache obj = new Cache(); the obj is always null.
I can access HttpContext.Current.Cache - but this doesnt let me specify an absolute expiration and sliding expiration in the Insert() method.
Can someone help me?
You should be able to absolute or sliding expiration calling the insert on HttpRuntime.Cache. It has several overloads. Ex:
HttpRuntime.Cache.Insert("EXAMPLE_KEY",
exampleItem,
Nothing,
DateTime.Now.AddHours(1),
System.Web.Caching.Cache.NoSlidingExpiration);
The exact same code should also work with HttpContext.Current.Cache.
I suggest you to try PCache class under PokeIn library. Even if you use FREE edition of that library, there is no limitation with this class. It has many more functionalities in comparison to ASP.NET Cache class and you dont have to deal with these problems. there is a simple sample project available on the web site.