How to resolve a System.TimeoutException during MongoDB connection? - c#

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

Related

C# Retry Policy: How to check what exception you receive as a variable?

I have a retry policy created for SQL Exceptions but it seems to not be retrying properly.
I am currently trying to debug and I want to create a temporary code line to test if the exception is a SQL Exception:
if (exception == SQLException) then bool correct = true;
But how would I create an exception variable?
I am currently causing the exception by using RAISERROR('test', 16, 1); in the stored procedures in the database and also creating a SQL timeout.
Just want to check if the exception I'm receiving is a SQL Exception or if it's not even registering.
Thank you
Not sure enough about the context, but if you have the exception object, then try the is operator
if (ExceptionObject is SqlException )
{
//run the retry logic for SqlException
}
The details are here:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast
Just catch the SqlException and check for the Class and State properties:
if (exception is SqlException sqlException)
{
if(sqlException.Class == 16 && sqlException.State == 1)
{
}
}

MySQL 6.9.8 - System.String.Substring exception when opening new connection

Every now and then, when I'm making a database query I run into a problem with ExecuteNonQuery in the MySQL.Data library.
The exception which gets raised is this:
Exception thrown: 'System.ArgumentOutOfRangeException' in CommonLanguageRuntimeLibrary ("Length cannot be less than zero.")
There are my logs from IntelliTrace from an Azure Worker Role.
It works most of the time but when this happens it stops the normal processing of the worker.
I'm loading the connection string from app.config, this is what it looks like:
<add key="DatabaseConnectionString" value="Server=localhost; Port=3306; Uid=user; Pwd=mypassword; Pooling=false;" />
I select the database at runtime with every request because it keeps changing which database it's connecting to.
Is there anything I can do to stop this from occurring and allow the new connection to open correctly?
Edit
Upon further investigation and crawling through the MySQL.Data Source code I've drilled down into this getter.
[DisplayName("program_name")]
public string ProgramName
{
get
{
string name = Environment.CommandLine;
try
{
string path = Environment.CommandLine.Substring(0, Environment.CommandLine.IndexOf("\" ")).Trim('"');
name = System.IO.Path.GetFileName(path);
if (Assembly.GetEntryAssembly() != null)
name = Assembly.GetEntryAssembly().ManifestModule.Name;
}
catch (Exception ex)
{
name = string.Empty;
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
return name;
}
}
Now is it possible that the WorkerRole will start returning a different value for the Environment.CommandLine property sometime during the execution? That's what seems to be happening because it works at the beginning and then fails after a while (2-3 days.)

CRM 2013 Exception Handling due to Security Roles

I have a plugin which fires on Update of the Incident entity. It creates a new record in another table (new_documentaccess). This new_documentaccess record needs to have the same Owner as that of the Incident entity.
Now, I understand that I cannot set the Owner field like any other field on the entity by doing a simple assignment.
So, I wrote in the following.
public void CreateDocumentAccess(Incident incident)
{
new_documentsaccess documentAccess = new new_documentsaccess();
documentAccess.new_CaseId = incident.ToEntityReference();
documentAccess.new_name = incident.OwnerId.Name;
Guid recordId = crmService.Create(documentAccess);
var request = new AssignRequest{
Assignee = new EntityReference(SystemUser.EntityLogicalName, incident.OwnerId.Id),
Target = new EntityReference(new_documentsaccess.EntityLogicalName, recordId)};
crmService.Execute(request);
}
However, I got the following error during execution when I was debugging with
Break when an exception is Thrown: enabled for Common Language Runtime Exceptions.
thrown at the line
var request = new AssignRequest{
Assignee = new EntityReference(SystemUser.EntityLogicalName, incident.OwnerId.Id),
Target = new EntityReference(new_documentsaccess.EntityLogicalName, recordId)};
Principal user (Id=e9e3a98d-a93e-e411-80bc-000c2908bc67, type=8) is
missing prvAssignnew_documentsaccess privilege
(Id=7ecaf3da-77c8-4ee3-9b29-e5a4455cd952)"}
My Plugin code is as follows
try
{
CreateDocumentAccess(Incident incident);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred while creating the document access.", ex);
}
catch (Exception ex)
{
TracingService.Trace("ExecutePreIncidentUpdate: {0}", ex.ToString());
throw;
}
If I just run it as User using the front end, I get the following error.
Exiting PluginPreIncidentUpdate.Execute(), Correlation Id: 4e7e4c3c-3cef-46ab-8d08-a6d0dbca34c7, Initiating User: be179876-9b39-e411-80bb-000c2908bc67
Questions
What code changes should I be making so that even if it errors out
on the above mentioned error, the ErrorDetails.txt captures the
error Principal user (Id=e9e3a98d-a93e-e411-80bc-000c2908bc67, type=8) is missing prvAssignnew_documentsaccess privilege
(Id=7ecaf3da-77c8-4ee3-9b29-e5a4455cd952)?
Why is it not happening already?
Firstly: To answer your questions:
Trace logs are only included with InvalidPluginExecutionException. Your second catch is being used and is throwing the caught exception not an "InvalidPluginExecutionException"
Changing this:
catch (Exception ex)
{
TracingService.Trace("ExecutePreIncidentUpdate: {0}", ex.ToString());
throw;
}
To something like this should pull your trace logs through into the ErrorDetails attachment.
catch (Exception ex)
{
TracingService.Trace("ExecutePreIncidentUpdate: {0}", ex.ToString());
throw new InvalidPluginExecutionException("An error has occurred");
}
Secondly: The cause
The error you are getting is indicating that the user does not have privileges to assign a new_documentaccess record.
When you register a plugin and add a new step; you can choose which user's context to run it in.
By default this is set to "Calling User".
Can you confirm that the calling user is in a security role that has the assign privilege for new_documentaccess records?

Converting string into exception

I want to convert a string into exception but not able to find any thing on google.
I am using C# .Net 2.0.
Reason is because third party client has a method that is logging method and only takes exception and i have a scenario where i must need to log something but using that method. so must need to convert string into exception.
Exceptions are created as any other object, using the new keyword. You can provide it a message argument that you can store your string in:
Exception e = new Exception("Your string goes here");
If you are using Try...Catch() then you can do following to add your customize message and original exception together
try{
//your code block
}
catch(Exception e)
{
var exception = new Exception("Your message: ");
//Display "exception" to users
//Log "e" for further investigation
}

Elmah add message to error logged through call to Raise(e)

I'm a bit confused at how to add a message to an error logged programatically with ELMAH.
eg:
public ActionResult DoSomething(int id)
{
try { ... }
catch (Exception e)
{
// I want to include the 'id' param value here, and maybe some
// other stuff, but how?
ErrorSignal.FromCurrentContext().Raise(e);
}
}
It seems all Elmah can do is log the raw exception, how can I also log my own debug info?
You can throw a new Exception setting the original as the inner exception and ELMAH will log the messages for both:
catch(Exception e)
{
Exception ex = new Exception("ID = 1", e);
ErrorSignal.FromCurrentContext().Raise(ex);
}
will show
System.Exception: ID = 1 ---> System.NullReferenceException: Object reference not set to an instance of an object.
I found that I can also do something like:
Elmah.ErrorSignal.FromCurrentContext().Raise(new NotImplementedException("class FbCallback.Page_Load() Request.Url= " + Request.Url));
To log my own messages. Then in when I browse to
http://localhost:5050/elmah.axd
I see my messages as type NotImplementedException.
Not very pretty but works.

Categories

Resources