Simulate CryptographicException on MVC-project? - c#

I have a project (SharePoint-Addin), that throws a CryptographicException from time to time on my customers machine. This Exception happens before even entering any Controller-Action.
I want to catch that error, analyze it and react accordingly. (Currently my guess would be this is some kind of token expiration, so I want to simply show the login-page if this happens)
I got the following code:
protected void Application_Error(object sender, EventArgs e)
{
_log.Error("ExceptionError occured ");
Exception exception = Server.GetLastError();
if (exception!=null)
{
_log.Error(exception);
if (exception is CryptographicException)
{
Response.Redirect(loginPage, true);
}
}
}
This will (hopefully) work, but this question is not about the code, but about how to force a CryptographicException.
Can I add an "evil header" to a request so this will fire?

Look here at MSDN:
https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptographicexception(v=vs.110).aspx
private void StringConstructor()
{
// Construct a CryptographicException using a custom error message.
string errorMessage = ("Unexpected Operation exception.");
CryptographicException cryptographicException =
new CryptographicException(errorMessage);
Console.WriteLine("Created a CryptographicException with the " +
"following error message: " + errorMessage);
}
or just
throw new CryptographicException(errorMessage);

Related

C# try-catching and exception and throwing the exact exception back up

I'm incorporating telemetry into my product on all service requests, unfortunately that includes exceptions. A problem I'm having is I surround my requests with a try-catch and if it's successful I log the request and if there's a catch I log the exception than throw the exception so that it still gets propagated up so that it can be debugged. A problem I'm having is that with try-catch I lose all the original data from the original exception caught by my try-catch, which I think would be nice to propagate back up.
public void someFunction(object data)
{
try
{
var response = await request(data);
LogInformation(request: data, response: response);
}
catch (Exception e)
{
throw HandleAndLogException(data, e);
}
}
private HttpResponseException HandleAndLogException(object data, Exception e)
{
LogException(data: data, response: e.Message);
var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) {
Content = new StringContent(e.Message)
};
return new HttpResponseException(resp);
}
So as you can see I create a new HttpResponseException and just append the message to it, but I'd rather propagate back up the exception thrown in it's entirety.
If you want to do something clever/evil, you can use the when keyword to introduce logging without breaking the stack trace on your exception.
See when contextual keyword in the C# reference on MSDN. It's supposed to be used as a filter (the method returns true or false, indicating whether that catch block should be used) but you can do whatever you want with
I think this is what you'd want, although I haven't tested it:
public void someFunction(object data)
{
try
{
var response = await request(data);
LogInformation(request: data, response: response);
}
catch (Exception e) when (HandleAndLogException(data, e))
{
throw;
}
}
private bool HandleAndLogException(object data, Exception e)
{
LogException(data: data, response: e.Message);
return true;
}

How to read CreateErrorResponse custom message in exception

I can't see CreateErrorResponse message in exception. I am passing message "Invalid Parameters" to ThrowResponseException method but i can't read it in exception.
e.Response.RequestMessage gives default detail message but i only need to read "Invalid Parameters".
try
{
If (!ValidString)
{ ThrowResponseException(HttpStatusCode.BadRequest, "Invalid Parameters");}
}
catch (HttpResponseException e)
{
msg = " Status Code: " + e.Response.StatusCode.ToString();
}
private void ThrowResponseException(HttpStatusCode statusCode, string message)
{
var errorResponse = Request.CreateErrorResponse(statusCode,message);
throw new HttpResponseException(errorResponse);
}
I found something similar where they wrap the message in a new exception and pass that exception into the create response. Then they can pull out the text of the error message.
How can I retrieve the exception message from Request.CreateErrorResponse?
return Request.CreateResponse(statusCode, new Exception(message));

Adrotator unable to catch Ad not found exception for Pubcenter

Currently this gets caught in App.xaml.cs
Message: Error Message: System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> MicrosoftAdvertising.Shared.AdException: No ad available.
How can i catch this exception in code or should AdRotator handle it?
I can share more code if this is not a known issue.
<UI:AdControl Name="mainHeaderAd" IsAutoRefreshEnabled="True" ErrorOccurred="AdControl_ErrorOccurred" AdUnitId="xxx" ApplicationId="yyy" />
This is how I am handling AdControl exceptions:
private void AdControl_ErrorOccurred(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
try
{
var errorType = Enum.GetName(typeof(MicrosoftAdvertising.ErrorCode), e.ErrorCode);
var adControl = sender as Microsoft.Advertising.WinRT.UI.AdControl;
// Do something with the above information.
}
catch (Exception ex)
{
// Do something with the exception.
}
}

A first chance exception of type 'System.Net.WebException' occurred in System.dll

I'm using TweetSharp to find the followers for a user.
Here is the code:
public static void FindFollowersForUser(TwitterUserModel twitterUser)
{
try
{
var followers = service.ListFollowersOf(twitterUser.TwitterName, -1);
if (followers == null) return;
while (followers.NextCursor != null)
{
var foundFollowers = service.ListFollowersOf(twitterUser.TwitterName, (long)followers.NextCursor);
if (foundFollowers == null) continue;
Debug.WriteLine("Followers found for: " + twitterUser.TwitterName);
foreach (var follower in foundFollowers)
{
twitterUser.Followers.Add(follower.ScreenName);
}
}
}
catch (WebException e)
{
throw e;
}
}
I've tried wrapping the code in a try/catch, to catch the WebException error being fired and review it's InnerException, but the catch is never entered despite the error message being shown in the output window (View -> Output) in Visual Studio.
How can I see the inner exception of this breaking bug? This is the first time I've seen the debugger not firing the catch when an exception is fired.
I assume when you say "First chance exception" you mean the message that is output to the Debug console? That message is output whenever an exception is thrown. The exception may be caught by code and handled and not allowed to propagate up the stack. TweetSharp may be catching this exception within its code and handling in some way so it never reaches your catch block
This is normal and only the debugger displays this message. If this is a problem for you in some way (other than the message displaying in the Output window), please provide more detail.
I was looking something else, really, but this cought my eye. If you are planning to rethrow exception then you want to replace this
catch (WebException e) { throw e; }
with this so you won't mess up the stacktrace.
catch (WebException e) { throw; }

Problem with Exception caught without argument

Encountered a strange problem with this event, event wrapper and handler:
public delegate void StatusUpdateHandler(string message, Exception exc, SeverityLevel severity);
public event StatusUpdateHandler StatusUpdate;
private void FireStatusUpdate(string message)
{
if (this.StatusUpdate != null)
this.StatusUpdate(message, null, SeverityLevel.None);
}
void scanDocProcessor_StatusUpdate(string message, Exception exc, SeverityLevel severity)
{
try
{
if (exc != null)
{
if (severity >= setSevLevel)
this._logger.Log(message + Environment.NewLine + exc.ToString(), LogEntryType.Emergency, "OCR Submission Processor Status Update", true);
else
this._logger.Log(message + Environment.NewLine + exc.ToString(), LogEntryType.Error, "OCR Submission Processor Status Update", false);
}
else if (severity >= setSevLevel)
{
this._logger.Log(message, LogEntryType.Info, "OCR Submission Processor Status Update", true, true);
}
else
this._logger.Log(message, LogEntryType.Info, "OCR Submission Processor Status Update", false);
}
catch (Exception)
{
EventLog.WriteEntry("Russia OCR Submission Processor", "Could not log status update event: " + exc.ToString(), EventLogEntryType.Information);
}
}
For a period of a few minutes, the _logger stopped logging messages and instead I received these messages in the event log:
Could not log status update event: System.NullReferenceException: Object reference not set to an instance of an object.
at ScannedService.scanDocProcessor_StatusUpdate(String message, Exception exc, SeverityLevel severity)
at ScannedService.Processor.FireStatusUpdate(String message)
at ScannedService.Processor.ProcessQueue(Object Object)
I'm confused how the Event log could get such a stack trace when it should be writing exc.ToString(). I looked at the IL for the scanDocProcessor_StatusUpdate method is not initializing an Exception object. Beyond that I don't know how a nullreferenceexception is getting thrown. When the Log method does catch an exception it swallows it or re-throws it with "throw;". The message parameter is never null and SeverityLevel is an enumeration.
You are throwing an exception in one of the else conditions where ecx is null. In the catch block, you are assuming that ecx is not null, which generates another exception that hides your original one.
You can make your log statement null-safe with the following:
EventLog.WriteEntry("Russia OCR Submission Processor",
String.Format("Could not log status update event: {0}", exc), EventLogEntryType.Information);

Categories