How to check if ObjectResult<> contains a value - c#

How do I check to see if the ObjectResult<> has a value or not? Right now it's returning values but will it throw an exception is there is nothing to return?
This is the section of code that I need to check so I do not have to depend on a try catch block
iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
public static Task<IProjectInfo> GetProjectInfo(int projectID)
{
return Task.Run(() =>
{
using (var db = new StorefrontSystemEntities())
{
IProjectInfo iProjInfo = db.proc_GetProject_ForDrawings(projectID).Single<IProjectInfo>();
try
{
iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
}
catch (Exception ex)
{
}
return iProjInfo;
};
});
}

As long as the stored procedure is getting executed and returning a result set; even if it is empty (no records returned by the stored procedure), you can be sure of an empty list being returned.

Related

where the error coming from inside Try Catch

I am doing 5 things inside a try/catch. If there is a error, how can i tell which function the error is coming from. so on line Console.WriteLine("Invalid operation"); I want it to display which function the error is so that its easy to debug.
I am trying to avoid using 5 different try/catch in Main OnGet() method. I was thinking to put try/catch inside each sub-method but I am return IQueryable so I wont be able to return error as type string. even so I will end up have 5 different if statement to check for error in OnGet()
How do you guys handle something like this?
public async Task<IActionResult> OnGetAsync(int p = 1, int s = 20)
{
try
{
// get all Data
IQueryable<MY_Model> Query = await _services.Get_All_CoursesTaken();
// Add Filters
Query = AddFilters(Query );
// Add Sorting
Query = AddSorting(Query );
// Add Paging
Query = AddPaging(p, s, Query );
//Display Data
My_List= await Query.AsNoTracking().ToListAsync();
}
catch (InvalidOperationException)
{
Console.WriteLine("Invalid operation");
}
return Page();
}
private IQueryable<MY_Model> AddFilters(IQueryable<MY_Model> Query)
{
//some code
}
private IQueryable<MY_Model> AddSorting(IQueryable<MY_Model> Query)
{
//some code
}
private IQueryable<MY_Model> AddPaging(int p, int s, IQueryable<MY_Model> Query)
{
//some code
}
Maybe your solution is:
Tuple
You can return IQueryable and String as return type in methods.
private Tuple<IQueryable<MY_Model>,string> AddFilters(IQueryable<MY_Model> Query)

My method is executing the IF 'Return' and the Catch 'Return'

I feel like I'm losing my mind. I'm sure there is something simple I'm not seeing.
In the method below, it enters the Try, executes the db query and the If evaluates true and hits the return statement. It then moves directly to the Return in the Catch (skipping over the _logger) and exits.
I've stepped through the code and the data coming back from the query is correct. When I hover over ex, it doesn't exist. I've also tried a Watch for ex, which says the same thing.
The only other time I was seeing this kind of behavior is when I had a Return directly on the query and if the query returned NULL, it would jump directly to the Return in the Catch. But its not the case in this instance.
I don't know if it will help, but when I had the Using statement inside the Try it would execute both the If and Else. What the heck am I doing wrong?
public async Task<List<ResourceModel>> GetResourcesByTypeAsync(string resourceTypeName)
{
if(string.IsNullOrEmpty(resourceTypeName))
new ArgumentNullException(nameof(resourceTypeName));
await using var db = _dbFactory.CreateDbContext();
try
{
var result = await db.ProjectResources
.Where(x => x.ResourceType.Name == resourceTypeName)
.AsNoTracking()
.ToListAsync();
if (result != null)
{
return result;
}
else
{
return new List<ResourceModel>();
}
}
catch(Exception ex)
{
_logger.LogCritical(ex.Message);
return new List<ResourceModel>();
}
}

Why is a duplicate key error being thrown and value still inserted

A document is inserted into a collection using c#
{
"_id" : UUID("some_guid")
}
Via
db.collection.insert(new { id = a_guid });
We rely upon the uniqueness of the guid/uuid by specifying the id in the document meaning the mongo db driver is spared from doing this.
Now, all of this is wrapped in a try..catch where a duplicate key exception is caught. Calling code uses this routine for conflict checking. That is, if a guid hasnt been encountered before - insert it - next time around and on trying to insert the same value again, the exception lets us now there's a duplicate.
We appear to be getting into a situation where values are written but an exception is STILL thrown, indicating a conflict where there isnt one.
We have had this working in a 3 node replica set.
It is NOT working in a 5 node replica set, purporting to be healthy. The write concern is set to 1, indicating acknowledgement when the master is written to (but not the journal) just like the 3 node set.
Where should I dig deeper? The duplicate exception derives from a writeconcern exception, is something screwy going on here? Is the mongo driver correctly interpreting the error and raising the right exception?
Any leads would be great!
EDIT:
var database = this.client.GetServer().GetDatabase("A_Database");
var collection = database.GetCollection<object>("A_Collection");
try
{
collection.Insert(new { Id = paymentReference.ToGuid() });
}
catch (MongoDuplicateKeyException)
{
return false;
}
return true;
This is NOT called in a loop.
You can catch the exception base MongoWriteException and filter with when by the Category, example code:
var database = this.client.GetServer().GetDatabase("A_Database");
var collection = database.GetCollection<object>("A_Collection");
try
{
collection.Insert(new { Id = paymentReference.ToGuid() });
}
catch (MongoWriteException ex) when(ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
return false;
}
return true;
Hear's a fixed version of your code
var database = this.client.GetServer().GetDatabase("A_Database");
var collection = database.GetCollection<object>("A_Collection");
try
{
collection.Insert(new { Id = paymentReference.ToGuid() });
}
catch (Exception)
{
collection.Insert(new { Id = Guid.NewGuid(); });
return tru;
}
return true;

savechanges() not saving?

I have this C# code:
public object guardardinerohoy(float dinero,string comentario)
{
object dineromov1 = this.nuevodineromovimiento(dinero, variablesestaticas.usuarioglobal, DateTime.Now, null, claseenumeraciones.enumdineromovimiento.iniciosistema, comentario, DateTime .Now );
object resultado = "ok";
string abrirconexion = Conexion.conexion.abrirconexion();
if (dineromov1.GetType() != "".GetType() && abrirconexion == "ok")
try
{
Conexion.conexion.conect.AddTodineromovimiento((dineromovimiento)dineromov1);
Conexion.conexion.conect.SaveChanges();
return "ok";
}
catch (Exception ex)
{
resultado = ex.Message;
}
else
{
resultado = dineromov1.ToString() + abrirconexion;
return resultado;
}
}
I return "ok" if this saved successfully. Now when I checked if this was saved it was not. I do not understand why if it did not return an exception. This does not happen all the time. Sometimes it saves and sometime it does not.
I found this thread which says if it does not have exception, everything is ok.
Check if an insert or update was successful in Entity Framework
Entity Framework will throw an exception upon failure of Insert, Update or Delete.
Thus, you can assume with no exception that it's successful.

C# mysql one return last_insert_id

I am trying to create a method in which I can exequte mysql UPDATE, DELETE or INSERT query. The method must work when with an INSERT I ask or do not ask the last_insert_id(). Below is the code that I have at the moment:
public int executeUID(MySqlCommand msCommand)
{
try
{
this.Open();
msCommand.Connection = this.msCon;
return int.Parse(msCommand.ExecuteScalar().ToString());
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
this.Close();
}
}
The problem with this is is that when I use an insert query that returns a last_insert_id() the method works greatly. But when the query doesn't return an last_insert_id() the method malfunctions. How can I get this method to work?
why not u use OUTPUT parametres, it will return the last inserted id. SqlParamet
and if you know when LastInsertID can generate, then you can pass one more parameter to method, to tell that it is retriving insertedID, based on that parameter you can do some thing like this .
public int executeUID(MySqlCommand msCommand, bool Mode) //Mode==true means insertandRetriveLastID, false means =dont retrive last insertedit
{
try
{
this.Open();
msCommand.Connection = this.msCon;
if(Mode) //for getting last inserted id
{
SqlParameter outParams= new SqlParameter("#ID", SqlDbType.Int);
outParams.Direction = ParameterDirection.Output;
msCommand.Parameters.Add(outParams)
msCommand.ExecuteNonQuery();
var outputValue = cmd.Parameters["#ID"].Value;
}
else //if no inserted id is not there
{
return msComand.ExecuteNonQuery(); // it will return No of Rows Affected.
}
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
this.Close();
}
}
PS : you need to tune it some more for better efficiency, as i gave some basic ideas how we can do it with out parameter

Categories