unhandled exceptions at startup in my c# project - c#

I am getting below Unhandled exception at the startup of my chatbot application in output window.
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
Exception thrown: 'System.Globalization.CultureNotFoundException' in mscorlib.dll
Exception thrown: 'System.Security.SecurityException' in mscorlib.dll
Exception thrown: 'System.BadImageFormatException' in mscorlib.dll
Exception thrown: 'System.ArgumentNullException' in mscorlib.dll
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
I have something in my MessageController
public class MessagesController : ApiController
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private static DocumentClient client;
// Retrieve the desired database id (name) from the configuration file
private static readonly string databaseId = ConfigurationManager.AppSettings["DatabaseId"];
// Retrieve the desired collection id (name) from the configuration file
private static readonly string collectionId = ConfigurationManager.AppSettings["CollectionId"];
// Retrieve the DocumentDB URI from the configuration file
private static readonly string endpointUrl = ConfigurationManager.AppSettings["EndpointUri"];
// Retrieve the DocumentDB Authorization Key from the configuration file
private static readonly string authorizationKey = ConfigurationManager.AppSettings["PrimaryKey"];
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
Trace.TraceInformation($"Type={activity.Type} Text={activity.Text}");
//disable the Application Insights and DocumentDb logging in local enviornment
#if (LOCAL)
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.DisableTelemetry = true;
#endif
#if (!LOCAL)
if (!String.IsNullOrEmpty(endpointUrl) && !String.IsNullOrEmpty(authorizationKey))
{
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
await CaptureConversationData(activity);
}
}
#endif
if (activity.Type == ActivityTypes.Message)
{
//await Microsoft.Bot.Builder.Dialogs.Conversation.SendAsync(activity, () => new ContactOneDialog());
//Implementation of typing indication
//ConnectorClient connector = new ConnectorClient(new System.Uri(activity.ServiceUrl));
//Activity isTypingReply = activity.CreateReply("Shuttlebot is typing...");
//isTypingReply.Type = ActivityTypes.Typing;
//await connector.Conversations.ReplyToActivityAsync(isTypingReply);
logger.Debug("The User's local timeStamp is: " + activity.LocalTimestamp + "and service timeStamp is: " + activity.Timestamp);
await Conversation.SendAsync(activity, () =>
new ExceptionHandlerDialog<object>(new ShuttleBusDialog(), displayException: true));
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
return response;
}
}
It thrown at first line
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
here is the snapshot,
One weired thing is that if my project run from C:\Users\\chatbot\Mybot..
then these exception are not getting thrown even i have put the break exception setting in exception setting window.
but if I move the project to c:\Sandy\MyStuff\ChatbOt\MyBot it's started throwing all these exception since i have put the break exception setting in exception setting window.
I am seriously not able to understand what is the problem.

Try running your visual studio as administrator or running your application as administrator, and check that all the Dlls that your project depends on are there in the new path.

Related

Console application not logging error with NLOG in AppDomain.CurrentDomain.UnhandledException

The below code isn't logging to my database. Is it because the console application closes too soon and if so how can I prevent this?
private static ILogger _logger;
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
_logger.Error((Exception)e.ExceptionObject);
}
private static void Main(string[] args)
{
var container = new Container();
_logger = container.GetInstance<ILogger>();
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
throw new Exception("test");
You can call LogManager.Shutdown() before leaving your UnhandledExceptionTrapper method. This calls internally LogManager.Flush() which
Flush any pending log messages (in case of asynchronous targets) with the default timeout of 15 seconds.
see NSLog Flush documentation.
Additional Troubleshooting
In the debug console, error messages are displayed if, for example, SQL errors occur on the connection, but by default you do not see if you have an invalid configuration.
Since NLog offers extensive configuration options, it is easy to make a small configuration errors that results in no logging. A typical example would be an incorrect ConnectionString or DBProvider.
As an example, suppose you have configured an incorrect DBProvider.
You can e.g call
LogManager.GetCurrentClassLogger().Debug("test logging");
LogManager.Flush();
and it would just silently fail.
However, if you insert
LogManager.ThrowExceptions = true;
before the test log call, you will see appropriate messages in the debug console. For example, if you have an invalid DBProvider like Npgsql.NpgsqlConnection1, Npgsql (note the invalid 1 in it), you would see
Unhandled exception. NLog.NLogRuntimeException: Exception occurred in NLog
---> NLog.NLogRuntimeException: Target Database Target[nlog-db] failed to initialize.
---> System.TypeLoadException: Could not load type 'Npgsql.NpgsqlConnection1' from assembly 'Npgsql'.
which would give a clear indication of what went wrong.
More Diagnostics
To see even more diagnostics, you can add the following lines:
InternalLogger.LogToConsole = true;
InternalLogger.LogLevel = LogLevel.Trace;
Among other things, you can see when the connection is opened, what data is written and information about flushing, a small sample excerpt:
2022-03-11 08:47:56.8428 Trace DatabaseTarget(Name=nlog-db): Open connection.
2022-03-11 08:47:57.0275 Trace DatabaseTarget(Name=nlog-db): Executing Text: insert into "public"."log_table"(time_stamp,level,logger,message,stacktrace) values(CAST(#time_stamp AS timestamp),#level,#logger,#message,#stacktrace);
2022-03-11 08:47:57.0380 Trace DatabaseTarget: Parameter: '#time_stamp' = '2022-03-11T08:47:56.837' (String)
2022-03-11 08:47:57.0380 Trace DatabaseTarget: Parameter: '#level' = 'Debug' (String)
2022-03-11 08:47:57.0380 Trace DatabaseTarget: Parameter: '#logger' = 'ConsoleDBLog.Program' (String)
2022-03-11 08:47:57.0395 Trace DatabaseTarget: Parameter: '#message' = 'test logging' (String)
2022-03-11 08:47:57.0415 Trace DatabaseTarget: Parameter: '#stacktrace' = '' (String)
2022-03-11 08:47:57.1099 Trace DatabaseTarget(Name=nlog-db): Finished execution, result = 1
2022-03-11 08:47:57.1111 Trace DatabaseTarget(Name=nlog-db): Close connection (KeepConnection = false).
2022-03-11 08:47:57.1167 Debug LogFactory Flush with timeout=15 secs
Self-Contained Example
using System;
using NLog;
using NLog.Targets;
namespace ConsoleDBLog;
internal static class Program
{
private static ILogger? _logger;
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
_logger?.Error((Exception?) e.ExceptionObject, "unhandled exception");
LogManager.Shutdown();
}
private static void Main()
{
SetupDB_NLOG();
_logger = LogManager.GetCurrentClassLogger();
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
throw new Exception("test");
}
static void SetupDB_NLOG()
{
DatabaseTarget target = new DatabaseTarget();
target.Name = "nlog-db";
target.DBProvider = "Npgsql.NpgsqlConnection, Npgsql";
target.ConnectionString = "Server=127.0.0.1;Port=5432;User Id=stephan;Password=;Database=stephan;";
target.CommandText =
"insert into \"public\".\"log_table\"(time_stamp,level,logger,message,stacktrace) values(CAST(#time_stamp AS timestamp),#level,#logger,#message,#stacktrace);";
var param = new DatabaseParameterInfo
{
Name = "#time_stamp",
Layout = "${date:format=yyyy-MM-ddTHH\\:mm\\:ss.fff}"
};
target.Parameters.Add(param);
param = new DatabaseParameterInfo
{
Name = "#level",
Layout = "${level}"
};
target.Parameters.Add(param);
param = new DatabaseParameterInfo
{
Name = "#logger",
Layout = "${logger}"
};
target.Parameters.Add(param);
param = new DatabaseParameterInfo
{
Name = "#message",
Layout = "${message}"
};
target.Parameters.Add(param);
param = new DatabaseParameterInfo
{
Name = "#stacktrace",
Layout = "${exception:format=stacktrace}"
};
target.Parameters.Add(param);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
//Uncomment the following lines to see things that would silently fail and
//to get more diagnostic debug output about what is actually running.
// InternalLogger.LogToConsole = true;
// InternalLogger.LogLevel = LogLevel.Trace;
// LogManager.ThrowExceptions = true;
// LogManager.GetCurrentClassLogger().Debug("test logging");
// LogManager.Flush();
}
}
Which gives the followoing entries in the DB:

ReactiveUI's ReactiveCommand Exception handling

I'm trying to handle Exception thrown inside ReactiveUI (7.4.0.0)'s commands, but everything seems to be swllowed somehwere inside and never comes out but in Visual Studio's Output window.
My test code is this:
class Program
{
static void Main(string[] args)
{
try
{
var ata = ReactiveCommand.CreateFromTask(async () => await AsyncTaskThrowException());
ata.ThrownExceptions.Subscribe(ex => Console.WriteLine($"async with await:\t{ex.Message}"));
ata.Execute();
// Exception thrown: 'System.InvalidOperationException' in System.Reactive.Windows.Threading.dll
// Exception thrown: 'System.Exception' in Test.exe
// Exception thrown: 'System.Exception' in mscorlib.dll
var atna = ReactiveCommand.CreateFromTask(() => AsyncTaskThrowException(),null, RxApp.MainThreadScheduler);
atna.ThrownExceptions.Subscribe(ex => Console.WriteLine($"async without await:\t{ex.Message}"));
atna.Execute();
// Exception thrown: 'System.InvalidOperationException' in System.Reactive.Windows.Threading.dll
// Exception thrown: 'System.Exception' in Test.exe
var ta = ReactiveCommand.CreateFromTask(async () => await TaskThrowException());
ta.ThrownExceptions.Subscribe(ex => Console.WriteLine($"async without await:\t{ex.Message}"));
ta.Execute();
// Exception thrown: 'System.InvalidOperationException' in System.Reactive.Windows.Threading.dll
// Exception thrown: 'System.Exception' in Test.exe
var tna = ReactiveCommand.CreateFromTask(() => TaskThrowException());
tna.ThrownExceptions.Subscribe(ex => Console.WriteLine($"async without await:\t{ex.Message}"));
tna.Execute();
// Exception thrown: 'System.InvalidOperationException' in System.Reactive.Windows.Threading.dll
// Exception thrown: 'System.Exception' in Test.exe
// Exception thrown: 'System.InvalidOperationException' in System.Reactive.Windows.Threading.dll
var sf = ReactiveCommand.Create(() => ThrowException());
sf.ThrownExceptions.Subscribe(ex => Console.WriteLine($"sync:\t{ex.Message}"));
sf.Execute();
// Exception thrown: 'System.InvalidOperationException' in System.Reactive.Windows.Threading.dll
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ex.Message)}: {ex.Message}");
Debug.WriteLine($"{nameof(ex.StackTrace)}: {ex.StackTrace}");
}
Console.ReadLine();
}
static async Task<string> AsyncTaskThrowException()
{
await Task.Delay(100);
throw new Exception("Exception in async Task");
}
static Task<string> TaskThrowException()
{
throw new Exception("Exception in non-async Task");
}
static string ThrowException()
{
throw new Exception("Exception in sync func");
}
}
Under each call there are the Exception's thrown if I comment everything but that .Execute() call (intentional one included).
The only call that prints something is the third:
ReactiveCommand.CreateFromTask(() => TaskThrowException());
But still throws something.
Can you help me understand why the other Exceptions don't get piped into ThrownExceptions, and how to completely handle errors so they don't get logged in the Output window?
Thanks!

'System.NotImplementedException' occurred in mscorlib.dll

does anyone know how to fix this exception?
An unhandled exception of type 'System.NotImplementedException' occurred in mscorlib.dll
I'm using .NET microframework 4.1 and I have the "mscorlib" reference added but when I try to load a BMP image from the resources:
internal static Microsoft.SPOT.Bitmap GetBitmap(Resources.BitmapResources id)
{
return Microsoft.SPOT.Bitmap(Microsoft.SPOT.ResourceUtility.GetObject(ResourceManager, id));
}
[System.SerializableAttribute()]
internal enum BitmapResources : short
{
image = 24837,
}
I get that exception in the return sentence.
Stack trace:
System.Resources.ResourceManager::GetObjectInternal\r\nS‌​ystem.Resources.Reso‌​urceManager::GetObje‌​ctFromId\r\nMicrosof‌​t.SPOT.ResourceUtili‌​ty::GetObject\r\nFEZ‌​TouchDriver_Example.‌​Resources::GetBitmap‌​\r\nFEZTouchDriver_E‌​xample.Program::Init‌​Graphics\r\nFEZTouch‌​Driver_Example.Progr‌​am::Main\r\n" string

Dependency Resolution Exception

I am doing Unit Testing In my Project.When I try to unit test my method a browser pops up and suddenly gets stopped after that I get a long exception I pasted following.
How to fix this mess as I have no idea whats the cause?
Exception:
https://paste.ubuntu.com/24389202/
BrowseHost Class
public static class BrowserHost
{
public static readonly SelenoHost Instance = new SelenoHost();
public static readonly String RootUrl;
static BrowserHost()
{
Instance.Run("BankingSite", 1468);
RootUrl= Instance.Application.Browser.Url;
}
}
UnitTest Class
namespace BankingSite.FunctionalUITests
{
[TestFixture]
public class LoanApplicationTest
{
[Test]
public void ShouldAcceptLoanApplication()
{
BrowserHost.Instance
.Application.Browser
.Navigate()
.GoToUrl($#"{BrowserHost.RootUrl}\LoanApplication\Apply");
var firstNameBox = BrowserHost.Instance.Application
.Browser
.FindElement(By.Id("FirstName"));
firstNameBox.SendKeys("Gentry");
var lastNameBox = BrowserHost.Instance.
Application.
Browser.
FindElement(By.Id("LastName"));
lastNameBox.SendKeys("Smith");
var ageBox = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("Age"));
ageBox.SendKeys("40");
var incomeBox = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("AnnualIncome"));
incomeBox.SendKeys("9999999");
Thread.Sleep(10000);
var applyButton = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("Applt"));
applyButton.Click();
Thread.Sleep(10000);
var acceptMessageText = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("acceptMessage"));
Assert.That(acceptMessageText, Is.EqualTo("Congratulations Gentry - Your Application was accepted!"));
Thread.Sleep(10000);
}
}
Following is the Screen Shot of URL I am browsing directly.
Hard to tell from what you've provided, but there is a clue in the stack trace:
System.TypeInitializationException : The type initializer for 'BankingSite.FunctionalUITests.BrowserHost' threw an exception.
----> Autofac.Core.DependencyResolutionException : An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Not a Number (See inner exception for details.)
----> System.InvalidOperationException : Not a Number
Check the constructor for BankingSite.FunctionalUITests.BrowserHost and see if you can find the line that is causing the error. Apparently it is expecting a numeric value but received something else instead.

How to resolve a System.TimeoutException during MongoDB connection?

I've started using the MongoDB .Net driver to connect a WPF application to a MongoDB database hosted on MongoLabs.
But the following method I created to load the connection(called on the MainViewModel's constructor), threw a timeout exception on the line marked in the method below.
I tried to resolve the error further by adding an exception check of type MongoException to no avail. Also checked that the connection string is valid as per the docs and it seems so: (password starred out for security)
private const string connectionString = "mongodb://<brianVarley>:<********>#ds048878.mongolab.com:48878/orders";
The specific error thrown is as follows:
An exception of type 'System.TimeoutException' occurred in mscorlib.dll
Complete Error Link: http://hastebin.com/funanodufa.tex
Does anyone know the reason why I'm getting the timeout on my connection method?
public List<Customer> LoadCustomers()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the customers collection:
var collection = database.GetCollection<Customer>("customers");
try
{
//Timeout error thrown at this line:
customers = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
}
catch(MongoException ex)
{
//Log exception here:
MessageBox.Show("A handled exception just occurred: " + ex.Message, "Connection Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
}
return customers;
}
Solved this error by re-editing my connection string. I had left these two symbols in my connection string in error, '<' and '>' between the user name and password credentials.
Correct format:
"mongodb://brianVarley:password#ds054118.mongolab.com:54118/orders";
Incorrect format:
"mongodb://<brianVarley>:<password;>#ds054118.mongolab.com:54118/orders";

Categories

Resources