Adrotator unable to catch Ad not found exception for Pubcenter - c#

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.
}
}

Related

Simulate CryptographicException on MVC-project?

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);

Is it possible to have one Exception handler for multiple timers in a C# class?

I have a C# program which runs a system tray application - transferring / moving / creating / editing files in the background.
There is alot of exception handling and loop handling to prevent the program from crashing / getting stuck if the user manual deletes a file the program is working with.
Unfortunately one of the computer the program is running on is having the program crash. The computer is very hard to get, and cannot have debugging software loaded on (it is an embedded PC outside with no network access).
I have tried finding the cause of the crash (such as an unhandled exeption) however have not found anything and do not have access to the PC as it is in a remote location.
I was hoping to find a way to use AppDomain / an UnhandledExceptionEventHandler to catch all unhandled exceptions and log them for diagnosis.
However the exception I have (deliberately) created in the office inside the class "DoSomething.class", are crashing the WinForm application rather than logging the exception error.
My code is:
//Current domain for the unhandled exception handling
AppDomain currentDomain;
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
public MainForm()
{
InitializeComponent();
currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
CreateTimer.Interval = Settings.Default.CreateTimer;
CreateTimer.Start();
RunCopyProtocol();
ChangeFilesTimer.Interval = 10000;
ChangeFilesTimer.Start();
RunChangeFiles();
throw new Exception("ABC");
}
public void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
try
{
Exception ex = (Exception)args.ExceptionObject;
SetLabel(ex);
}
finally { }
}
private string SetLabel(Exception ex)
{
String str;
str = ex.Message;
Label1.Text = str;
return str;
}
private void ChangeFilesTimer_Tick(object sender, EventArgs e)
{
RunChangeFiles();
throw new Exception("2");
}
Why doesn't the throw new exception call the unhandled exception error?
How would I use AppDomain to get the unhandled exception handler to handle this exception / exceptions in the RunChangeFiles?
Code on AppDomain is based of MSDN examples
If your timer is a System.Timers.Timer the reason is documented by MSDN here:
The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event.
Take a look at this similar question:
How do I get the Exception that happens in Timer Elapsed event?
You'll have to catch the exceptions that are thrown in the elapsed handler, and rethrow them on a ThreadPool thread.
Using your code above and extending the answer from the referenced question:
private void ChangeFilesTimer_Tick(object sender, EventArgs e)
{
try
{
RunChangeFiles();
}
catch (Exception ex)
{
ThreadPool.QueueUserWorkItem(
_ => { throw new Exception("Exception on timer thread.", ex); });
}
}
If your timer is a System.Windows.Forms.Timer then you will need to hook into the Application.ThreadException event to handle unhandled exceptions.
Subscribe to this event prior to calling Application.Run().
You can also handle logging of the Exception in a local exception handling block before rethrowing the exception.
try
{
/// ...
}
catch (Exception ex)
{
if (ex is ArgumentException)
{
/// handle known or specific exceptions here
}
else
{
/// log then rethrow unhandled exceptions here
logExceptions(ex);
throw;
}
}

Getting ExitCode From Exception Handler

I have following error handler in my console application
Main Procedure:
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(ErrorHandler);
Handler Procedure:
static void ErrorHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
... Loging Error ...
//Environment.Exit(?);
}
And the problem is that error is logged but after that application failed and windows popup (application is not responding) is showed.
So i want to add Environment.Exit() to prevent that behavior, but how to specify the exitCode from the exception ? I dont want to set Exit(0) (which means everything is okay) because i also want see the error (only information that some error happened, exception is already logged) in the scheduler application which trigger this script.
Thank you
Most programmers simply use Environment.Exit(1). Almost always works just fine. But that is not technically correct, if a program dies on an exception then its exit code is normally the same as the underlying exception error code. The event handler ought not change that behavior.
Doing it right is a mouthful:
Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(e));
There's a FUD factor here, you can't completely trust a library with custom exception objects that don't set an error code. Still okay, the fallback is E_FAIL.
Can you use the Exception.HResult?
Consider the following code:
class Program
{
static int Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; ;
if (args.Any() && args[0] == "/t")
{
Console.WriteLine("I am going to throw an exception");
throw new ApplicationException("This is an exception");
}
else
{
Console.WriteLine("I am going to exit");
//Environment.Exit(0);
return 0;
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("An unexpected error has occurred");
Exception ex = (Exception)e.ExceptionObject;
Environment.Exit(ex.HResult);
}
}
Then execute this from a batch file twice - once with the /t parameter and the other without:
#echo off
cls
echo Running Console Application with no error
ConsoleApplication2.exe
echo %errorlevel%
echo Running Console Application with error
ConsoleApplication2.exe /t
echo %errorlevel%
pause
In the first run you exit with 0. I've made Main return an int and just return 0 for successful execution - you can do Environment.Exit(0) here.
With the second run that throws an ApplicationException, the UnhandledException is handled, then Environment.Exit(ex.HResult) is called.
I think the HResult is tied in to specific exceptions as per MSDN. However, you may want different exit codes depending on what caused the exception. In this case you can throw custom exceptions then have some cafuffled logic in the UnhandledException handler:
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("An unexpected error has occurred");
Exception ex = (Exception)e.ExceptionObject;
if (ex is MyException)
{
Environment.Exit(10009); // my own exit codes
}
Environment.Exit(ex.HResult);
}
}
class MyException : Exception
{
}
But would you really care why it failed in the console? If you get an unhandled exception then it failed. You can have lots of possible failure points. What are you really going to do with the error code? You have logged the exception out. That provides the vital information.

WCF proxy faulted but does not throw an exception

I have a method which accesses a service to perform two calls. Here is the (simplified) client code:
try
{
using (var client = new IntegrationServiceClient())
{
int taskID = client.CreateTask(param, taskType, taskDate);
if (taskID < 0)
{
//There was some error
return -1;
}
if (!client.ExecuteTask(taskID, taskType))
{
//There was some error
}
}
}
catch (Exception ex)
{
LogManager.Log("Error while creating and executing task", ex);
}
I'm getting a CommunicationObjectFaultedException exception only on the second call. How is this possible? If there was some kind of fault, shouldn't I get a FaultException (or some other exception) after the first call? Is there something other than an exception that can cause the proxy to enter a faulted state?
It seems there was a bad web.config file. The stack trace was telling me there was an error on line with the second call because that was the last meaningful line within the using statement, after which the proxy is disposed. The CommunicationObjectFaultedException is raised only when disposing the proxy.
It was just the way that the code was written that caused the stack trace look like the exception was thrown when calling the second method.

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; }

Categories