Unique value in StackTrace? - c#

Background:
I have written a generic logging library in .NET 3.5. Basically the developer needs to call the Begin() method at the beginning of their method and the End() method at the end of it. These methods do not take a parameter - the library uses the stacktrace to figure out where it came from. The library has a collection that keeps track of the call stack and writes out the elapsed time of each method.
This works really well and I'm happy with it.
But now we want to add it to the server. When multiple users are on the system, there is only one log file and the stack traces are lumped together. It's impossible to tell which thread is doing what.
My question is this:
Is there a way to retrieve a unique value from the StackTrace class or an indivdual StackFrame? What about using reflection? I would like to be able to create a seperate file for each user. At the very least, I'd like to be able to tag each line with the unique value so we can filter the file by this value when reviewing traces.
We are using WCF TcpBinding as our server side communication protocol, if that helps. I am looking for a thread id, hashcode, address, something to distinguish where the call stack came from.
Any ideas?
Thanks.

You could use something associated with the current thread - perhaps the thread id?.
Threads from the thread pool get reused, so you would see the id's repeated throughout the log file, but for the lifetime of a Begin/End pair it would uniquely tag a single user.

If you used some form of Aspect Oriented Programming (like Postsharp) you might find a better, declarative way to get the information you need. Thread.CurrentThread.ManagedThreadId would give you a reference for the thread running the code at the time, but all your developers would have to do do is apply an attribute to a method, rather than calling Begin() and End() for every method.

To get the user account under which the current thread is running, you can use WindowsIdentity.GetCurrent().

Related

ASP.NET: How to make data visible for AOP/Cross-cutting concerns?

I would be interested in seeing a relevant pattern for this, but here is my immediate specific problem.
I have a requirement to modify logging in a web application such that every entry in the log is annotated with the entity (user name or process name) responsible for executing the code that resulted in the log entry. For example, rather than:
timestamp level loggerName A sensitive object was deleted from the database
you would get
timestamp level loggerName [ELLIOT.ALDERSON] A sensitive object was deleted from the database
or
timestamp level loggerName [DAILY CRON JOB] A sensitive object was deleted from the database
In addition to identifying the "user" (or process) that took an action, if it is a user, there is also a requirement to log information about the request itself (e.g. ip address, user agent, headers, etc.), although that data can be written to an adjunct log so the main log itself stays readable.
In Java, this was relatively trivial to do without modifying the interface to our logger because the HTTP server we use (Tomcat) 'guarantees' one request/one thread, resulting in my being able to put both user information and request information in thread-local variables. Any of my code, anywhere, could figure out "who" called it and access request properties by asking for the current user and request associated with that thread, with no need to pass user and request variables in every method down through the entire application. Which meant that when any of my code wrote to the log, my minimally-modified logger code could produce the desired output without changing any single call to the logger in my application.
In C#.NET, I don't know how to do this. IIS pretty much guarantees thread reuse from a pool, so there goes thread-local variables to identify what user and which request is associated to any particular method call (and therefore the the user/request to tie to logger calls made by that method). All of the AOP articles I've ever read deal with applying behavior, not so much data. Inside the controller method itself, of course, I can see session and request information. But the controllers call methods that call methods that call methods, etc. ad nauseum, those methods don't have visibility unless the session and request are passed as additional parameters to every method, which is a non-starter (I also thought of and dismissed walking the stack up to the controller or until I'm convinced there is no controller; however, the stack trace just essentially identifies the source code associated with a particular frame, it doesn't give you access to the actual objects on the stack. Plus, as expensive as formatting and writing log data is, the additional expense of walking the stack seems a bit excessive).
Is there a technique that would allow me the same kind of visibility to arbitrary context-specific data (in this case session and request objects) to my cross-cutting concern code?
If you need a static access to current request data you can use HttpContext.Current.Items . It Is a dictionary of string, object and differs for every request. If you change thread (i.e. you are using async await) the context will be preserved and you will find the correct data.

Call method inside Workflow's IF ChartFlow

I am using Windows Workflow Foundation 4and as part of more complicated scenario I have those two states:
The idea is that the users are allowed to upload files which is part of the whole workflow. There may be several reason which my lead to the fact that an uploaded file can not be processed immediately. One of the reasons may be that currently there is a file uploaded from a certain user which is being processed so every other file uploaded during the processing should be in state WaitingProcessing. However when I enter the WaitingProcessing state I need to check this. In order to do that I have to implement something like this:
where generally the HasFileToProcess is a function which will call a stored procedure from the database to check if currently there is a file for this user which is in state Processing.
Almost all parts of the tasks are clear, one thing that I don't know how to do is how to call e function inside the condition field. In fact I have almost zero experience with Windows Workflow at all so I'm not even sure that this is the way to go so as a sub-question I would appreciate if someone knows and show me if there is better way to implement this kind of logic.

How to make a process fire an event in another process in c#/.net?

How to make process-1 able to fire an event in process-2, and send along few argument, to signal the 2nd process to do a specific action, and optionally receive a reply?
It is possible to do this using the filesystem, there could be a file, where process-1 dumps some commands/querys, and process-2 would be constantly reading from that file, but, this solution is not nice.
Any other way to do it?
(I know that its easy in VB.net to fire an event in a running process whenever a new process is started, IF the "single instance" is enabled in the project properties)
You can use named EventWaitHandle to achieve cross-process synchronization.
This article seems to do what you are used to with vb.net single instance (and it seems still a viable option).
In short it seems that there are three approaches to accomplishing single instance like solutions:
Use a Mutex
Cycle through the process list to see if a process with the same name is already running
Use the Visual Basic system for single instance apps (which you can access from C#)
If by "process" you mean "app-domain", it's fairly easy to set up eventing between the two. In fact if you have two classes in two separate app-domains (where each class has MarshalByRefObject as a base class), then .net will automatically set up a remoting structure that will make events appear to behave as they would in a single app-domain. (Example here: http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject.aspx)
The key here though is 'appear'. 'App-domain' and 'process' separation are intended to keep resources isolated on purpose. To access anything outside of your process you really need help from the operating system, like a shared file or internet connection or named pipes - something to that effect. But .net concepts like events don't exist outside of your space in the runtime.
In other words, you'd have to use something like Named-Pipes (http://msdn.microsoft.com/en-us/library/system.io.pipes.namedpipeserverstream.aspx) if both processes are on the same machine, TCPClient/TCPListener (http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) if communicating across multiple systems, or WCF if you need something more heavy duty.
If you'd like to see a specific example of one of these technologies in practice, I can write one up for you, btw.

Windows Phone 8 Web Post return boolean AFTER call back completed?

I'm trying to make an application in windows phone 8 and make it easy to extend or change by coding it in to simple classes. I would like to do a simple web call with a webclient that does a HTTP POST to log a user in to a service. Here is the flow I have so far:
User enters username and api details or they are called from previously saved details.
WebClient does a POST to web service and receives XML response with user information etc.
Call back executes after having set WebClient.UploadStringCompleted += new UploadStringCompletedEventHandler(name)
User information is processed and stuff done with it.
For various reasons and mainly for wanting to code in to classes and ultimately release the code as a free SDK for other developers, I wish the flow to look like this:
User enters details or called from saved details.
Function within class called something similar to if(class.Authenticate(user,apikey)){logged in stuff}; which returns a boolean value or even better an integer value so I can easily process errors from the web service.
Nothing i have tried will make this work and I can't get my head around how to make it work with async and await as webclients just seem to execute on their own thread and wouldn't hold one up for me until the call back was completed.
I've found a custom webclient class somewhere but it only did GET requests which isn't good enough for my needs.
You don't want to do this.
To do this you would need to block the executing thread until the server responds:
- This could be a very long time.
- If on the UI thread this would stop the user interacting with the UI.
- What if there's no, or a very slow, connection
This is the reason that WebClient doesn't have a synchronous way of making calls.
There are ways to make the execution appear synchronous but you'll get a lot more from learning to work with the framework and understanding why it wants you to work a specific way and why that's appropriate on an occasionally connected device.
You could also make this code look synchronous by making an Awaitable request. See more at http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

C# / ASP.NET - Web Application locking

I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering [MethodImpl(MethodImplOptions.Synchronized)] and a few ways of using lock(), but I have a few questions/concerns.
It seems like MethodImplOptions.Synchronizedwill essentially dolock(this)`. If that's the case, it seems like a thread entering any synchronized method would block all other threads from entering any synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.)
Concerning lock(), I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way?
Thanks in advance!
My preference is to create an object specifically for the lock.
private object lockForSomeResource = new object();
in the class that is managing the contentious resource.
Jeff Richter posted an article I read some time ago that recommended this.
You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.
I have posted a similar question on this forum, that may help you. Following is the link
Issue writing to single file in Web service in .NET
You can expose some static reference or a singleton, and lock() that.
Maybe you can care to explain why you need such locking and what you will use it for?
Creating discrete object instances at static/application level is the best way for plain exclusive locking.
Should also consider if reader/writer lock instances at application level could also help improve your application concurrency e.g. for reading and updating lists, hashes etc.

Categories