So if a a Singelton calls a method that throws an exception - c#

So this is a follow-up to a previous question that I asked: Trying to figure out if this code creates any benefit by using a Singleton
In a nutshell, I have inherited a poorly architected program that uses a pseudo-facade class and places it into a Singelton. Every method call goes through the Singleton which then calls different methods.
The Singelton looks like this:
public class FooFacade
{
private static FooFacade m_facade = null;
private static DataAccessManager m_dataAccessMgr = null;
public StringBuilder Status {get; set; }
private FooFacade()
{
this.Status = new StringBuilder();
}
public static FooFacade getInstance()
{
if (m_facade == null)
{
m_dataAccessMgr = DataAccessManager.getInstance();
m_facade = new FooFacade();
}
return m_facade;
}
public void clearStatus()
{
this.Status.Remove(0, Status.Length);
}
public void Method1(string value1, int value2)
{
// do something
}
public int Method2(int value1, int value2)
{
return externalMethod(value1, value2)
}
}
So in this example above, would there be a security concern if the externalMethod that is being called in Method2 threw an error?
For example:
public int externalMethod(value1, value2)
{
try
{
return value1/value2;
}
catch
{
throw;
}
}
In this method, should I be concerned that a Singleton could display a thrown error to the wrong user?
When I have the chance to refactor, I'm getting rid of the Singleton, but in the meantime, I just don't want to accidentally add a huge security hole by adding better exception handling.
-Chad

There is no way that the exception thrown is displayed to another "user". The exception is thrown in the call stack of the current call, so if two different threads were to call Method2 and in thread A the external method throws an exception and in thread B it doesn't, than only thread A would receive the exception.

Related

How can I create a set-once app-level action that isn't enforced via runtime exceptions or swallowing second-sets?

I'd like to be able to specify an Action<string> at the app level that my library could then use for progress reporting. ConfigurationManager.AppSettings only allows XmlSerializeables, and Actions are not that.
The motivation is that console apps might just write to the console, webapps perhaps to a trace, and forms perhaps to files or a particular field, the point is the app should be able to configure it imo.
My approach currently is to have in the library a LibSettings class that has a static settable Action<string>. That means anyone can set it elsewhere too, which poses potential for bugs.
At first I thought maybe a static constructor (with parameters) would do but it turns out you can't call static constructors explicitly and you certainly can't give them parameters.
Is there any way to achieve my goal of being able to specify the Feedback action once and only onc in some sort of custom app settings, and not throw a runtime exception on second setting, or swallow the second setting? That is essentially like a singleton property of my design when I design it. Thanks in advance.
Serializing and deserializing a delegate usually isn't a good idea, as it easily leads to pretty serious security concerns (see arbitrary code execution).
Instead I would recommend having a enum or similar serializable type that identifies a number of statically defined functions and convert between them. Something like this:
public enum FeedbackAction
{
Console,
Trace,
...
}
public static class FeedbackActions
{
public static void Console(string text) { ... }
public static void Trace(string text) { ... }
public static Action<string> GetAction(FeedbackAction action)
{
switch (action)
{
case FeedbackAction.Console:
return Console;
case FeedbackAction.Trace:
return Trace;
default:
throw new ArgumentException("Invalid feedback action.", nameof(action));
}
}
}
Now whenever you're trying to use the app setting, just call FeedbackActions.GetAction to convert between your enum values and the appropriate Action<string>.
For example:
public static class Feedback
{
public static Action<string> feedbackAction;
public static object syncLock = new object();
public static void ProvideFeedback(string text)
{
if (feedbackAction == null)
{
// synchronize to avoid duplicate calls
lock (syncLock)
{
if (feedbackAction == null)
{
var value = ConfigurationManager.AppSettings["FeedbackAction"];
feedbackAction = FeedbackActions.GetAction(value);
}
}
}
feedbackAction(text);
}
}
This way you can safely call Feedback.ProvideFeedback, and its behavior will be driven by the app/web.config file.
If you need to make a solution that's flexible enough to handle almost any feedback action, I'd strongly recommend reading up on inversion of control in general and the Managed Extensibility Framework (MEF) in particular. A full implementation would be a bit too complex to provide here, but in general it would look a bit like this:
public interface IFeedbackAction
{
void ProvideFeedback(string text);
}
public interface IFeedbackMetadata
{
string Name { get; }
}
[Export(typeof(IFeedbackAction)), ExportMetadata("Name", "Console")]
public interface ConsoleFeedbackAction : IFeedbackAction { ... }
[Export(typeof(IFeedbackAction)), ExportMetadata("Name", "Trace")]
public interface TraceFeedbackAction : IFeedbackAction { ... }
public static class Feedback
{
[ImportMany]
public IEnumerable<Lazy<IFeedbackAction, IFeedbackMetadata>> FeedbackActions { get; set; }
private IFeedbackAction feedbackAction;
public static void ProvideFeedback(string text)
{
if (feedbackAction == null)
{
// synchronize to avoid duplicate calls
lock (syncLock)
{
if (feedbackAction == null)
{
var value = ConfigurationManager.AppSettings["FeedbackAction"];
feedbackAction = GetFeedbackAction(value);
}
}
}
feedbackAction.ProvideFeedback(text);
}
private static IFeedbackAction GetFeedbackAction(string name)
{
return FeedbackActions
.First(l => l.Metadata.Name.Equals(name)).Value;
}
}
With this method, consumers would be able to provide their own implementation of IFeedbackAction, decorated with the appropriate [Export] and [ExportMetadata] attributes, and simply specify use of their custom actions in the app/web.config file.
Ok, let's see if I inderstood all right.
Let's suppose this is your config class:
public static class LibSettings
{
public static readonly Action<string> TheAction{ get; private set; }
static LibSettings()
{
var action = ConfigurationManager.AppSettings["libAction"];
switch(action)
{
case "console":
TheAction = ConsoleAction;
break;
case "web":
TheAction = WebAction;
break;
//And as many as you need...
}
}
private static void ConsoleAction(string Parameter)
{
//Whatever it does...
}
private static void WebAction(string Parameter)
{
//Whatever it does...
}
}
Is this what you meant? it will be only set once whenever you access any property of the class, it cannot be modified externally and will change the Action upon an AppSeting record.
Ok, let's go with another approach. Now we will have two classes a temporal holder where you will set the action you want and the current settings class.
public static class TemporalHolder
{
public static Action<string> HeldAction{ get; set; }
}
public static class LibSettings
{
public static readonly Action<string> TheAction;
static LibSettings()
{
TheAction = TemporalHolder.HeldAction;
}
public static void Init()
{
/*Just do nothing as we will use it to fire the constructor*/
}
}
And now, to use it, just seth the action to the temporal holder and call anithing static on LibSettings:
TemporalHolder.Action = (your function);
LibSettings.Init();
And voila! no errors on second settings, it cannot be changed on runtime and cannot be reasigned. are all the conditions met?

Is there a short and simple way for checking variable/property values?

I wonder whether there is a short and simple way for checking whether variable/property values match some condition?
Currently one of the most popular line in my code is similar to this one:
if (string.IsNullOrWhiteSpace(someFileName))
{
throw new NullReferenceException("'someFileName' must not be null.");
}
then the exception gets logged in the catch part and the execution continues and so on.
I don't like writing this line all over the place and just changing the variable name. It would be great if one could write something like this:
Assert.IsNotNullOrWhiteSpace(someFileName);
and it threw an exception saying that "{my variable} must not be null" with maybe some additional information like the parent class etc. that would help you to debug the code if you only have the logs available.
The problem with writing such a utility class that I encountered was that the thrown exception had of course the wrong stack trace like it happened in the utility method and not inside the method that called the assertion function.
This kind of value checking is required to especially work at runtime because I most of the time check user input like settings, paths, inputs etc.
EDIT:
I think I should have given an example of what I try to achieve:
public class FileExtractor {
public Form MainForm { get; set; }
public void ExtractFile(string fileName) {
Assert.IsNotNullOrWhiteSpace(fileName);
Assert.IsNotNull(MainForm);
// ...
}
}
and the let's call it Assert library should do this:
public static Assert {
public static void IsNotNullOrWhiteSpace(this string value) {
if (string.IsNullOrWhiteSpace(value)) {
// throw an exception like it occured in the ExtractFile
// the message should contain a hint like: "fileName must not be null"
}
}
public static void IsNotNull(this object value) {
if (value == null) {
// throw an excaption like it occured in the ExtractFile,
// the messagge should contain a hint like: "FileExtractor.MainForm must not be null."
}
}
EDIT-2
#CodeCaster - unfortunately I cannot not use C# 6 yet.
After some research and inspirated by two other questions here on stackoverflow
How to get Property Value from MemberExpression without .Compile()?
and
get name of a variable or parameter
I came up with this so far:
namespace ExceptionTest
{
class Program
{
static void Main(string[] args)
{
object test = null;
Assert.IsNotNull(() => test);
}
}
static class Assert
{
public static void IsNotNull<T>(Expression<Func<T>> expression)
{
MemberExpression memberExpr = expression.Body as MemberExpression;
var constExpr = memberExpr.Expression as ConstantExpression;
var value = (memberExpr.Member as FieldInfo).GetValue(constExpr.Value);
if (value == null)
{
throw new ArgumentNullException(memberExpr.Member.Name);
}
}
}
}
It almost does what I need. The last thing is to modify the stack trace so that it points to the Main method and not to the IsNotNull
You could use Debug Methods (http://msdn.microsoft.com/en-us/library/System.Diagnostics.Debug_methods%28v=vs.110%29.aspx), which however only work when compiling in debug mode.
Maybe Debug.WriteLineIf(Boolean, String) does what you need?
http://msdn.microsoft.com/en-us/library/y94y4370%28v=vs.110%29.aspx
How about applying attributes to the properties
http://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx
I think that you should try with Fody library library. For null-guards there is a package that you can find here. All libs are available via Nuget.
Fody is some kind AOP library that uses "weaving" technique to manipulate IL of an assembly and inject additional code.
So NullReferenceExcpetion (or maybe NullArgumentException) will be thrown exactly from your method.
Example from GitHub:
Your code
public void SomeMethod(string arg)
{
// throws ArgumentNullException if arg is null.
}
public void AnotherMethod([AllowNull] string arg)
{
// arg may be null here
}
What gets complied
public void SomeMethod(string arg)
{
if (arg == null)
{
throw new ArgumentNullException("arg");
}
}
public void AnotherMethod(string arg)
{
}

Guard object in C#

In C++, it's fairly easy to write a Guard class which takes a reference to a variable (usually a bool) and when the instance object exits scope and gets destructed, the destructor resets the variable to the original value.
void someFunction() {
if(!reentryGuard) {
BoolGuard(&reentryGuardA, true);
// do some stuff that might cause reentry of this function
// this section is both early-exit and exception proof, with regards to restoring
// the guard variable to its original state
}
}
I'm looking for a graceful way to do this in C# using the disposal pattern (or maybe some other mechanism?) I'm thinking that passing a delegate to call might work, but seems a bit more error-prone than the guard above. Suggestions welcome!
Something like:
void someFunction() {
if(!reentryGuard) {
using(var guard = new BoolGuard(ref reentryGuard, true)) {
// do some stuff that might cause reentry of this function
// this section is both early-exit and exception proof, with regards to restoring
// the guard variable to its original state
}
}
}
With the understanding that the above code won't work.
You are correct…without unsafe code, you can't save the address of a by-ref parameter. But, depending on how much you can change the overall design, you can create a "guardable" type, such that it's a reference type containing the value to actually guard.
For example:
class Program
{
class Guardable<T>
{
public T Value { get; private set; }
private sealed class GuardHolder<TGuardable> : IDisposable where TGuardable : Guardable<T>
{
private readonly TGuardable _guardable;
private readonly T _originalValue;
public GuardHolder(TGuardable guardable)
{
_guardable = guardable;
_originalValue = guardable.Value;
}
public void Dispose()
{
_guardable.Value = _originalValue;
}
}
public Guardable(T value)
{
Value = value;
}
public IDisposable Guard(T newValue)
{
GuardHolder<Guardable<T>> guard = new GuardHolder<Guardable<T>>(this);
Value = newValue;
return guard;
}
}
static void Main(string[] args)
{
Guardable<int> guardable = new Guardable<int>(5);
using (var guard = guardable.Guard(10))
{
Console.WriteLine(guardable.Value);
}
Console.WriteLine(guardable.Value);
}
}
Here's a functional (as in lambda-based) way to do it. Pluses are, no need to use a using:
(note: This is not thread-safe. If you are looking to keep different threads from running the same code simultaneously, look at the lock statement, the monitor, and the mutex)
// usage
GuardedOperation TheGuard = new GuardedOperation() // instance variable
public void SomeOperationToGuard()
{
this.TheGuard.Execute(() => TheCodeToExecuteGuarded);
}
// implementation
public class GuardedOperation
{
public bool Signalled { get; private set; }
public bool Execute(Action guardedAction)
{
if (this.Signalled)
return false;
this.Signalled = true;
try
{
guardedAction();
}
finally
{
this.Signalled = false;
}
return true;
}
}
EDIT
Here is how you could use the guarded with parameters:
public void SomeOperationToGuard(int aParam, SomeType anotherParam)
{
// you can pass the params to the work method using closure
this.TheGuard.Execute(() => TheMethodThatDoesTheWork(aParam, anotherParam);
}
private void TheMethodThatDoesTheWork(int aParam, SomeType anotherParam) {}
You could also introduce overloads of the Execute method that accept a few different variants of the Action delegate, like Action<T> and Action<T1, T2>
If you need return values, you could introduce overloads of Execute that accept Func<T>
Sounds like the sort of thing you'd have to implement yourself - there are no such mechanisms built into C# or the .NET framework, though I did locate a deprecated class Guard on MSDN.
This sort of functionality would likely need to use a Using statement to operate without passing around an Action block, which as you said could get messy. Note that you can only call using against and IDisposable object, which will then be disposed - the perfect trigger for resetting the value of the object in question.
You can derive your object from IDisposable interface and implement it.
In specific case you are presenting here Dispose will be called as soon as you leave using scope.
Example:
public class BoolGuard : IDisposable
{
....
...
public void Dispose()
{
//DISPOSE IMPLEMANTATION
}
}

Checking constraints using IDisposable -- madness or genius?

I ran across a pattern in a codebase I'm working on today that initially seemed extremely clever, then later drove me insane, and now I'm wondering if there's a way to rescue the clever part while minimizing the insanity.
We have a bunch of objects that implement IContractObject, and a class InvariantChecker that looks like this:
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public void Dispose()
{
if (!obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
internal class Foo : IContractObject
{
private int DoWork()
{
using (new InvariantChecker(this))
{
// do some stuff
}
// when the Dispose() method is called here, we'll throw if the work we
// did invalidated our state somehow
}
}
This is used to provide a relatively painless runtime validation of state consistency. I didn't write this, but it initially seemed like a pretty cool idea.
However, the problem arises if Foo.DoWork throws an exception. When the exception is thrown, it's likely that we're in an inconsistent state, which means that the InvariantChecker also throws, hiding the original exception. This may happen several times as the exception propagates up the call stack, with an InvariantChecker at each frame hiding the exception from the frame below. In order to diagnose the problem, I had to disable the throw in the InvariantChecker, and only then could I see the original exception.
This is obviously terrible. However, is there any way to rescue the cleverness of the original idea without getting the awful exception-hiding behavior?
I don't like the idea of overloading the meaning of using in this way. Why not have a static method which takes a delegate type instead? So you'd write:
InvariantChecker.Check(this, () =>
{
// do some stuff
});
Or even better, just make it an extension method:
this.CheckInvariantActions(() =>
{
// do some stuff
});
(Note that the "this" part is needed in order to get the C# compiler to look for extension methods that are applicable to this.) This also allows you to use a "normal" method to implement the action, if you want, and use a method group conversion to create a delegate for it. You might also want to allow it to return a value if you would sometimes want to return from the body.
Now CheckInvariantActions can use something like:
action();
if (!target.CheckInvariants())
{
throw new ContractViolatedException();
}
I would also suggest that CheckInvariants should probably throw the exception directly, rather than just returning bool - that way the exception can give information about which invariant was violated.
This is a horrid abuse of the using pattern. The using pattern is for disposing of unmanaged resources, not for "clever" tricks like this. I suggest just writing straight forward code.
If you really want to do this:
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public void Dispose()
{
if (Marshal.GetExceptionCode() != 0xCCCCCCCC && obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
Instead of this:
using (new InvariantChecker(this)) {
// do some stuff
}
Just do this (assuming you don't return from do some stuff):
// do some stuff
this.EnforceInvariants();
If you need to return from do some stuff, I believe some refactoring is in order:
DoSomeStuff(); // returns void
this.EnforceInvariants();
...
var result = DoSomeStuff(); // returns non-void
this.EnforceInvariants();
return result;
It's simpler and you won't have the problems you were having before.
You just need a simple extension method:
public static class InvariantEnforcer {
public static void EnforceInvariants(this IContractObject obj) {
if (!obj.CheckInvariants()) {
throw new ContractViolatedException();
}
}
}
Add a property to the InvariantChecker class that allows you to suppress the check/throw.
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public bool Suppress { get; set; }
public void Dispose()
{
if (!this.Suppress)
{
if (!obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
}
internal class Foo : IContractObject
{
private int DoWork()
{
using (var checker = new InvariantChecker(this))
{
try
{
// do some stuff
}
catch
{
checker.Suppress = true;
throw;
}
}
}
}
If you current problem is to get original exception - go to Debug -> Exceptions and check "thrown" for all CLR exceptions. It will break when exception is thrown and as result you'll see it first. You may need to also turn off tools->options->debug->"my code only" option if exceptions are throw from "not your code" from VS point of view.
What is needed to make this nice is a clean means of finding out whether an exception is pending when Dispose is called. Either Microsoft should provide a standardized means of finding out at any time what exception (if any) will be pending when the current try-finally block exits, or Microsoft should support an extended Dispose interface (perhaps DisposeEx, which would inherit Dispose) which would accept a pending-exception parameter.

What is the best way to re-use exception handling logic in C#?

I have two functions that have different enough logic but pretty much the same exception handling:
public void DoIt1 // DoIt2 has different logic but same exception handling
{
try
... DoIt1 logic
catch (MySpecialException myEx)
{
Debug.WriteLine(myEx.MyErrorString);
throw;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
throw;
}
}
It is not possible to use a single entry point for DoIt1 and DoIt2, because they are called in from outside.
Is Copy/Pase (for the exception block) the best approach?
It depends... if there is that much commonality, you could pass in the thing to do as a parameter - either as an interface or a delegate:
void Foo(Action thingToDo) {
if(thingToDo == null) throw new ArgumentNullException("thingToDo");
try {
thingToDo();
} catch {...} // lots of
}
And call as:
Foo(delegate { /* logic A */ });
Foo(delegate { /* logic B */ });
Try:
public static class Catching<TException> where TException : Exception
{
public static bool Try<T>(Func<T> func, out T result)
{
try
{
result = func();
return true;
}
catch (TException x)
{
// log exception message (with call stacks
// and all InnerExceptions)
}
result = default(T);
return false;
}
public static T Try<T>(Func<T> func, T defaultValue)
{
T result;
if (Try(func, out result))
return result;
return defaultValue;
}
}
Example:
int queueSize = Catching<MyParsingException>
.Try(() => Parse(optionStr, "QueueSize"), 5);
If Parse throws a MyParsingException, queueSize will default to 5, otherwise the returned value from Parse is used (or any other exception will propagate normally, which is usually what you want with an unexpected exception).
This helps to avoid breaking up the flow of the code, and also centralises your logging policy.
You can write specialised versions of this kind of exception wrapping for special cases, e.g. catching a particular set of three exceptions, or whatever.
For the extreme end of the spectrum of possible solutions, check out Aspect-Oriented-Programming techniques, and tools such as PostSharp or Microsoft Policy Injection Block. This way you can define an aspect that does something on exception and weave it into all places in your code that need it.
If you just want to log the exceptions' messages and items, without doing special processing in the catch block, you could create a Reflection-based Object logger, passing the Exception as an argument. Doing so, you don't have a lot of catch blocks.
And if you are the code's owner, you can put the logging procedure inside the MySpecialException's constructor, removing the catch's block and making the code cleaner.
You could have something like:
public static class ErrorHandler
{
public static void HandleMyException(MyException myEx)
{
Debug.WriteLine(myEx.MyErrorString);
throw;
}
public static void HandleException(Exception myEx)
{
Debug.WriteLine(e.ToString());
throw;
}
}
or, in this specific case, have a more generic function like:
public static class ErrorHandler
{
public static void WriteAndThrow(string msg)
{
Debug.WriteLine(msg);
throw;
}
}

Categories

Resources