How to get a dump of all local variables? - c#

How can I get a dump of all local & session variables when an exception occurs? I was thinking of writing some sort of reflection based function that would interrogate the calling function & create a dump of variables & values.
Is there an existing library that I can use?
UPDATE
After speaking to a colleague, I was pointed to AOP or Aspect Oriented Programming. Here is what I understand ... Using AOP, one would simple decorate the methods & classes with certain attributes. AOP framework then injects code in or around these classes & methods. There are two separate kinds of framework, one that injects code & then compiles the assembly & the second simply uses reflection & traps the call which you have decorated and wraps whatever code around the method at runtime.
I hope all that makes sense. I will be doing more research on this & post my approach.
Thanks guys ...

I'm not sure if this is what you're looking for. But if you're in a catch-block you can get all fields and properties of this class in the following way:
try
{
double d = 1 / 0;
}
catch (Exception ex)
{
var trace = new System.Diagnostics.StackTrace();
var frame = trace.GetFrame(1);
var methodName = frame.GetMethod().Name;
var properties = this.GetType().GetProperties();
var fields = this.GetType().GetFields(); // public fields
// for example:
foreach (var prop in properties)
{
var value = prop.GetValue(this, null);
}
foreach (var field in fields)
{
var value = field.GetValue(this);
}
foreach (string key in Session)
{
var value = Session[key];
}
}
I've showed how to get the method name where the exception occured only for the sake of completeness.
Type.GetProperties Method
Type.GetFields Method
PropertyInfo.GetValue Method
FieldInfo.GetValue Method
StackTrace Class
With BindingFlags you can specify constraints, for example that you only want properties of this class and not from inherited:
Using GetProperties() with BindingFlags.DeclaredOnly in .NET Reflection
Of course the above should give you only a starting-point how to do it manually and you should encapsulate all into classes. I've never used it myself so it's untested.

You should not use Exception handling in Try Catch form. Rather, it should be
Page Level Error
Application Level error
Suppose You have a Presentation Layer and a Business Logic Layer/DataAccess Layer.
Upon facing the error in say Business Logic, it will move directly to Glogal.asax.cs file under Application_Error Event without going back to the calling function. Here you can log the error message like below....
HttpContext.Current.Server.GetLastError().InnerException.StackTrace
HttpContext.Current.Server.GetLastError().InnerException.Message
HttpContext.Current.Server.GetLastError().InnerException.Source
HttpContext.Current.Server.GetLastError().InnerException.TargetSite.DeclaringType.FullName
HttpContext.Current.Server.GetLastError().InnerException.TargetSite.DeclaringType.Name
HttpContext.Current.Server.GetLastError().InnerException.TargetSite.DeclaringType.Namespace
In case of page level error, Priority is the Page OnError Override and finally the Application Level error event. here also you can log errors.
I will prefer Application_error handler because If you have 20 modules and a situation come when you need to create baseclass for each module. It is not good to make code redundancy.
Now in the Web Config you can write code to redirect the user on some default page like below.
<customErrors defaultRedirect="ErrorPage.htm" mode="On">
<error statusCode="404" redirect="ErrorPageNotFound.htm"/>
</customErrors>

This is a question asked ad nauseum on Stack Overflow, although phrased differently. In one thread, the answer was to use PostSharp. As others have suggested dumping the stack trace, you can do that. The easiest would be to manually dump the local variables. This can either be to Trace or you can create your own custom exception handler.

Related

Exception Handling in ASP.NET Web Api 2

Problem:
I need to handle web api 2 exceptions and return a rich object with the correct status code (401 for Unauthorized, 404 for ContentNotFound, etc) and some extra information as the content. Moreover, I need the content to look like a serialized Exception object (have the message, exceptionMessage, stackTrace, ... properties).
Suggested Solutions:
Create custom exception classes and writing a custom exception filter to apply to any controller's action. this custom exception filters handles the exception thrown according to it's type (one of the custom exceptions that I've already defined) and responds accordingly via something like this (filter's code):
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized,
new Exception("my exception")));
wrapping the already written web api 2 *ActionResult classes ( System.Web.Http.Results.UnauthorizedResult Unauthorized(), System.Web.Http.Results.OkResult Ok(), etc ) and adding some custom data to them and use them so that their result get passed to client every time they're called (the problem is in this case my controller's action's return type should be IHttpActionResult which is not as easily testable and readable as a strongly typed action).
What solution should I choose? Or is there any other way to do what I'm trying to achieve here?
Or you could use the built-in, out-of-the-box solution: exception filters.
Furthermore, you may be interested on exception handling starting from Web API 2.x.
From what I understand you don't want to handle exceptions thrown by the code, rather create them in your action methods. For the case where exceptions are thrown by other areas in the code (other things you call inside your actions or by other filters, you can either use exception filters or global error handling).
Hence I would go with your second approach (though you don't need to customize the action results much). Your code is actually a lot more easy to unit test with IHttpActionResult, because you can inspect the result type directly. In fact one of the reasons IHttpActionResults where added is to simplify unit testing.
The flow of your code is simpler as you don't need to throw to generate errors, and you can always inspect the content of an ok(returnValue) as you can see below.
[TestMethod]
public void GetProduct_ShouldReturnCorrectProduct()
{
var testProducts = GetTestProducts();
var controller = new SimpleProductController(testProducts);
var result = controller.GetProduct(4) as OkNegotiatedContentResult<Product>;
Assert.IsNotNull(result);
Assert.AreEqual(testProducts[3].Name, result.Content.Name);
}
http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api

Can I write tests for custom attributes without defining x^n classes?

I'm building a class library that includes several custom attributes that apply to properties. Then I have methods that do certain things based on the placement of the attributes.
Now I want to build some unit tests, but how to I make the tests without creating something on the order of x^(number of attributes) classes just for testing purposes? Can I leverage metadata classes or something?
Basically I'd love for there to be a way for me to apply attributes to properties at runtime (i.e. inside the "Arrange" part of my test method), but I'm pretty sure that's impossible.
Edit
This is the reflection code I'm using to test attributes, since apparently how I'm reading them may make a difference:
bool skip = false, iip = false;
string lt = null;
SerializeAsOptions sa = SerializeAsOptions.Ids;
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
Type attrType = attr.GetType();
if (typeof(JsonIgnoreAttribute).IsAssignableFrom(attrType))
{
skip = true;
continue;
}
if (typeof(IncludeInPayload).IsAssignableFrom(attrType))
iip = ((IncludeInPayload)attr).Include;
if (typeof(SerializeAs).IsAssignableFrom(attrType))
sa = ((SerializeAs)attr).How;
if (typeof(LinkTemplate).IsAssignableFrom(attrType))
lt = ((LinkTemplate)attr).LinkTemplate;
}
if (skip) continue;
I'm adding another answer, because since you now provided some code, the old one is too broad. It's now (mostly) obvious that:
you control the attribute-reading code
you are reading the code via reflection (PropertyInfo.GetCustomAttributes)
So. Since you are using Reflection, TypeDescriptors will not help. You'd need to:
either read the attrs differently so TypeDescr can be used
dynamically generate assemblies at runtime to generate classes with properties on the fly during tests
It can be very interesting/entertaining, but it can also turn into nice amount of work. But, since you control both sides of the code, none of these two is actually needed.
First, let's trim the code to significant parts:
somemethod(PropertyInfo prop)
{
// ...
object[] attrs = prop.GetCustomAttributes(true); // read ATTRs from PROP
foreach (object attr in attrs) // scan the PROP's ATTRs
{
// check attr type, do something
}
// ...
}
The core of your problem is not:
adding/removing attributes during Arrange/Teardown part
but
forcing the loop over PROP's ATTRs to see attributes that your test specifies
Looking at the problem like this, the answer is almost obvious: your loop has to abstract from the "Read attributes" part.
object[] attributeReader(PropertyInfo prop)
{
return prop.GetCustomAttributes(true);
}
somemethod(PropertyInfo prop)
{
// ...
object[] attrs = attributeReader(prop); // read ATTRs from PROP
foreach (object attr in attrs) // scan the PROP's ATTRs
{
// check attr type, do something
}
// ...
}
Now, your processing code is independent of the way the attributes are read. Sure, in the example above that way is hardcoded. But it does not have to be. Depending on how you want/like to organize your tests, you can use many ways to replace the attributeReader method with other mechanisms.
For example, just add 'virtual' to the attributeReader and use inheritance to create a class that will enable AttributeFaking:
// original class:
virtual object[] attributeReader(PropertyInfo prop)
{
return prop.GetCustomAttributes(true);
}
// derived class:
object[] AttributesOverrides {get;set;}
override object[] attributeReader(PropertyInfo prop)
{
if(prop.Name = "ShoeSize") return AttributesOverrides; // return what I say!
return base.attributeReader(prop);
}
// your test setup
var t = ... // that DERIVED object
t.AttributesOverrides = new [] { ... } ; // attributes to use
For example, use delegates/lambdas, no inheritace
// note the attributeReader is now a field, not function
Func<PropertyInfo, object[]> attributeReader = defaultAttributeReader;
static object[] defaultAttributeReader(PropertyInfo prop)
{
return prop.GetCustomAttributes(true);
}
// and your test setup
var t = ... // that ORIGNAL object
t.attributeReader = customReaderForTheTest; // change the reader on the fly
// that's the reader-function to use in THIS TEST setup
static object[] customReaderForTheTest(PropertyInfo prop)
{
if(prop.Name = "ShoeSize") return null; // crash when I say so! muhaHAHAhaa!
return prop.GetCustomAttributes(true);
}
Both of those two examples end up with one class that is enables faking the attributes in some way, but that's not the only ways to do that. You can use IoC to inject the correct attributeReader. You can do that in any way you like - you just need to abstract from reading part and leave it 'open'.
It is not possible to really apply the attribute at runtime to an existing class, but there are at least two ways you could do something similar to it - it depends on how exactly are you reading those attributes later.
The options focus on the 'really' and 'existing class' part:
1) don't do that, just fake adding them
2) apply them on a class that does not exist yet! ;)
First option is a CustomTypeDescriptor. In its implementations, you will be able to dynamically answer to any queries about Attributes for some class that uses it (-> see virtual GetAttributes method).
This leads to first way:
Create AttributableTestObject that i.e. inherits from your ClassCompatibleWithThatAttribute etc
Create something like DynamicallyAttributedClass : CustomTypeProvider that exposes a static property similar to IEnumerable<Attribute>
override the GetAttributes and return whatever was provided by that static property
on your AttributableTestObject class set a TypeDecriptorProvider attribute pointing to provider (you've got to implement it, again) that returns DynamicallyAttributedClass
Now, using that static property you can change what the GetAttributes returns, and therefore you can dynamically change the setof attributes that are visible through typedescriptor.
And here's the catch: Not all engines/observers/readers/(..) actually care about TypeDescriptors. Some simply read the metadata right away from the Reflection. Reflection will not check the typedescriptors. It will simply return an information that the AttributableTestObject class has a TypeDecriptorProvider property. But whe nusing used the ComponentModel mechanisms, the custom list of attribues will be visible.
That reminds me that the reading mechanisms simply sit at TypeDescriptor class, see its methods. There's also AddAttribute, so maybe you can even get what you want without actually implementing the stuff I said above - Try using AddAttribute and then GetAttribute on your target Type and check the results. It may "just work". But again, it will not fool the reflection.
So, there's a second, "more hardcore" approach - dynamic classes. With System.Reflection.Emit you can dynamically generate an assembly that will contain whatever IL code you wish, and then load the assembly to the current runtime.
This gives you a unique option to simply generate a new fresh class(es) at runtime, with any contents and any attributes you like. You can use inheritance, so you can inherit from any ClassCompatibleWithThatAttributes. It's not that easy to do manually, but there are some libraries that make using the IL emitter easier.
Note that the generated types will be generated at runtime. This means that at compile-time you will not have them checked, you must generate them perfectly or face some really rarely seen Exceptions. Also, note that as the types are not known at compile-time, you cannot simply new the objects. You will have to create the objects basing on their freshly-generated Type through i.e. Activator.CreateInstance(Type).
Also, even though you can generate as much new classes as you want - if you overdo it, you probably will eventually hit some CLR limit, or at leat OutOfMemory, since the generated and loaded assemblies actually occupy space. You can overcome it with AppDomains - you can create some extra AppDomains and generate and load the assemblies inside them, and then, finally, you can unload that extra domain to release all memory and also unload any assemblies that were loaded there. But, I suppose you will not generate that much types to really need that. I'm writing about it just-in-case. Dont worry until you hit the OutOfMemory or similar.

Attribute Useage For Checking Method Permissions

I'm trying to implement a security mechanism to automatically test a particular plugins permissions and method security privileges and I've gotten a bit stuck on how to get this working.
I've writing a custom MEF Metadata attribute that takes a constructor property like:
params PluginPermission[] permission
This contains an array of all the permissions that the plugin is granted.
The PluginPermission class looks like:
PluginPermission.cs
public enum PluginPermission
{
CreateUsers,
DeleteUsers,
ReadPassword,
WritePassword,
AddUsersToGroups,
AddGroups,
DeleteGroups
}
I've also written a RequiredPermissionAttribute that targets individual methods and takes one or more PluginPermission objects to tell the system what permissions are required for an individual method to be execute. These are applied to the interface for the plugins like:
ILicensingManagement.cs
[RequiredPermission(PluginPermission.CreateUsers)]
bool AddUser(string userName);
Obviously if the plugin doesn't have the required permissions for a particular method the method is not executed.
What I'm stuck on is how to actually get the test method in the RequiredPermissionAttribute class to run before the method is executed and how to gracefully exit the execution if the permissions requirements for the method are not met by the plugin.
I looked at the xUnit BeforeAfterTestAttribute but the implementation seemed so specific I stuggled to pull the source code apart to arrive at the solution.
I can't comment on MEF specific things but one thing to keep in mind that custom attributes are nothing more than "tags", they do not do anything unless your code specifically checks for them, for example using reflection.
The BeforeAfterTestAttribute of xUnit probably works, because xUnit uses reflection to execute the methods. When it encounters this attribute it changes its behavious accordingly.
Attributes in the .NET framework namespace work because either the CLR checks for them or the compiler does.
I know this doesn't really answer your question completely but it was a bit too long to put into a comment.
Update: you can access the attributes using the Type if it's a class or the MethodInfo if it's a method, e.g.
MethodInfo mi = /* method info */;
Attribute[] attrs = mi.GetCustomAttributes(typeof(RequiredPermissionAttribute), false);
RequiredPermissionAttribute req = attrs.Cast<RequiredPermissionAttribute>().FirstOrDefault();
if ((req != null) && (/* current user does not have the required permission */)) throw new Exception();
But this is not a real security solution, a developer can easily avoid these checks. I've only briefly glanced at it but PostSharp could maybe help you.

Code Contracts and failure on private static readonly fields

I have a private static readonly field in my class:
public class MyClass
{
// ISSUE #1 -- requires unproven: path != null
private static readonly DirectoryInfo MyDirectory =
new DirectoryInfo(Settings.Default.MyDirectoryPath);
protected virtual void SomeMethod()
{
if (MyDirectory.Exists)
{
// ISSUE #2 -- requires unproven: !string.IsNullOrEmpty(path)
var catalog = new DirectoryCatalog(MyDirectory.FullName);
}
}
}
For issue #1 I used a null coalescing operator to default to some magic string and that fixed it, but I don't really like that solution. I was hoping there was a better solution.
For issue #2 the only thing I can think of is using a Contract.Assumes because if I attempt to use Contract.Requires(MyDirectory.Exists || !String.IsNullOrEmpty(MyDirectory.FullName)); it complains about visibility (private field used in a requires on a protected method).
Issue #1 is a result of Settings.Default.MyDirectoryPath being code generated by Visual Studio without any contracts on the property. This issue is not limited to null strings. Many API's now have contracts that require say a TimeSpan to be non-negative but using a setting directly in the API will generate a Code Contracts warning.
A way to solve this issue is to wrap the setting in a method that has a contract. E.g.:
String GetMyDirectoryPath() {
Contract.Ensures(Contract.Result<String>() != null);
var myDirectoryPath = Settings.Default.MyDirectoryPath;
Contract.Assume(myDirectoryPath != null);
return myDirectoryPath;
}
Notice how the Contract.Assume really performs validation of your setting (which can't be verified by Code Contracts because it is controlled by an external configuration file). Had it been a TimeSpan that is expected to be non-negative you can either use Contract.Assume to do the validation resulting in a ContractException or some other method using your own exception instead.
Adding this extra layer is somewhat tedious but because the setting is defined outside the application it needs to be run-time validated at some point just as you have to validate interactive user input.
Issue #2 is probably because DirectoryInfo doesn't have any contracts defined. The easist way is to use Contract.Assume. This will make a statement about what you believe is the expected behavior of DirectoryInfo but a run-time check will still be in place to ensure that your belief is correct (provided that you keep the checks in your code).
var path = MyDirectory.FullName;
Contract.Assume(!string.IsNullOrEmpty(path));
var catalog = new DirectoryCatalog(path);
After having used Code Contracts in a current project for a while now I have found that it does force you to rewrite your code at times to correct for issues. You really have two options here.
You can add the setting to your project settings to output what the correct attributes to apply are to ignore certain warnings. This is done by adding the "-outputwarnmasks" flag to the "Extra Static Checker Options" under the Advanced section in the Code Contracts tab of the Project file settings. This will add information to the Build Output window giving you the correct attributes to add to ignore the individual cases. (very useful when dealing with Entity Framework).
You can rewrite your code to add the proper Requires and Ensures to your code so that the warnings don't appear.
If you want to rewrite the code:
To solve Issue #1 you would have to wrap the Settings class and expose a new MyDirectoryPath as a property that isn't code generated so that you can add a check in it and return an empty string and add the Contract.Ensures(Contract.Result<string>() != null) at the top of the Getter for the property.
To solve Issue #2 you would have to wrap you access to the class field inside a private static property that adds the proper Ensures and Requires.
I have usually gone with rewriting the code wherever possible except with Entity Framework/LINQ where you need to add the attributes, especially with complex queries.
** Disclaimer ** These are just the ways I have found to solve the issues as there isn't a great deal of information on other ways of working around these types of items.
Well, for Issue#2, I think you might want to use && not ||. But beyond that, perhaps for Issue#1 you can put those checks in the static constructor? Another option for Issue#2 is to have the method to take the directory as a parameter:
private static readonly DirectoryInfo MyDirectory;
static MyClass()
{
Contract.Requires(Settings.Default.MyDirectoryPath != null);
MyDirectory = new DirectoryInfo(Settings.Default.MyDirectoryPath);
}
protected void SomeMethod()
{
SomeOtherMethod(MyDirectory);
}
protected virtual void SomeOtherMethod(DirectoryInfo directory)
{
Contract.Requires(directory.Exists && !String.IsNullOrEmpty(directory.FullName));
var catalog = new DirectoryCatalog(directory.FullName);
}
I don't have much experience working with the Contract API, so I might be off my rocker with all this. :)
Contract.Requires(MyDirectory.Exists || !String.IsNullOrEmpty(MyDirectory.FullName));
Don't do this! MyDirectory.Exists can change at any time and the caller cannot guarantee it. Just throw an exception if the directory doesn't exist - this is what exceptions are for.

Allow or disallow method run in .NET

I need to organize some simple security in a class depends on value of the enum.
All that I can figure out is using attribute on a method and then run check then if it fails throw an exception.
Sample:
[ModulePermission(PermissonFlags.Create)]
public void CreateNew()
{
CheckPermission();
System.Windows.Forms.MessageBox.Show("Created!");
}
protected void CheckPermission()
{
var method = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod();
if (!flags.HasFlag(method.GetCustomAttributes(true).Cast<ModulePermissionAttribute>().First().Flags))
{
throw new ApplicationException("Access denied");
}
}
is there more elegant or simple way to do this, like just to trigger an event when method run?
Why not just use standard Code Access Security instead of reimplementing the attribute handling and stack walking?
I think that if you read through the linked documentation, you'll see that what you have is nowhere close to what is needed to achieve actual security. Thankfully, this hard problem has already been solved...
Not with an enum, but with strings - voila (enforced by the runtime, even in full-trust):
public static class PermissionFlags {
public const string Create = "Create";
}
[PrincipalPermission(SecurityAction.Demand, Role = PermissionFlags.Create)]
public void CreateNew() {
System.Windows.Forms.MessageBox.Show("Created!");
}
All you need to do now is to represent the user as a principal. This is done for you in ASP.NET, and there is a winform plugin (in VS2008 etc) to use ASP.NET for membership. It can be configured for vanilla winforms and WCF, too; at the most basic level, GenericPrincipal / GenericIdentity:
// during login...
string[] roles = { PermissionFlags.Create /* etc */ };
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("Fred"), // user
roles);
But you can write your own principal / identity models easily enough (deferred / cached access checks, for example).
You might want to look at doing this with something like PostSharp, which will give you a framework for applying the attributes so that you don't have to run the check in your method. This may, however, increase the complexity depending on how the currently active flags are accessed. You'd probably need some class to cache the current permissions for the current user.
You could take a look at Aspect Oriented Programming.
Check out Postsharp for instance, which will enable you to 'weave' some additional logic at compile time in the methods that you've decorated with your ModulePermission attribute.
By doing so, you will not have to call the 'CheckPermission' method anymore inside that 'secured' method, since that logic can be weaved by Postsharp.
(A while ago, I've been playing around with Postsharp: http://fgheysels.blogspot.com/2008/08/locking-system-with-aspect-oriented.html )

Categories