Error getting value from ... with JSon exception and nullException - c#

this is a pretty tough problem I got here, I don't get anything to it, I'll try to be as clear as possible
I'm working on a project which takes datas in a database and create Json files from it, here's the method that throws the Exception :
public async Task<int> RecupInters(List<string> fileExist)
{
List<JsonFile> ljf = (await myservice.getJsonFilesAsync(Switcher.pageSwitcher.currentUser, fileExist.ToArray())).ToList();
if (ljf.Count > 0)
{
float percentPerFile = 50 / ljf.Count;
string jsonFolder = Data.HelperDirectory.getFolderDocumentAndCreate("JSON");
float percent = 0.0f;
foreach (JsonFile jf in ljf)
{
this.changeValues("Récupération de nouveaux rapports", percent, "Sauvegarde des fichiers d'interventions");
File.WriteAllText(jsonFolder + jf.Name, jf.Content);
percent = percent + percentPerFile;
}
}
return ljf.Count;
}
It says "Error getting value from demandeAideFilledAndItsMine" and throws a JsonSerialization exception and a nullReferenceException. demandeAidefilledAndItsMine is a property of the FichePreDiag class :
public bool demandeAideFilledAndItsMine { get { return (this.NomDemandeAide != null && isMine()); } }
(here is the IsMine method if you want)
public bool isMine()
{
if (!String.IsNullOrEmpty(this.NomDemandeAide))
{
return this.NomDemandeAide.Equals(DAL.getUserByUsername(Environment.UserName).fullName);
}
else
return false;
}
And the FichePreDiag class is a DB Object generated by EntityFramework.
Anyway, actually the Exception is thrown when it calls the method getJsonFilesAsync so I digged deep into it, it comes from here :
public System.Threading.Tasks.Task<DAO.JsonFile[]> getJsonFilesAsync(DAO.User u, string[] fileExist) {
return base.Channel.getJsonFilesAsync(u, fileExist);
}
This method belongs to a partial class and calls the method of the same name in a reference :
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IService1/getJsonFiles", ReplyAction="http://tempuri.org/IService1/getJsonFilesResponse")]
System.Threading.Tasks.Task<DAO.JsonFile[]> getJsonFilesAsync(DAO.User u, string[] fileExist);
And I can't get deeper. I'm soooo confused right now, I need help.
Thanks for your time

Related

C# Dereference of a possibly null reference

I'm somewhat confused by the warning I'm getting. Here is the relevant code:
#nullable enable
public partial class FileTable<TItem> : ComponentBase, IDisposable
{
// bunch of class code
public async Task FilterColumn(Func<TItem, IComparable>? itemProperty, string? searchString)
{
ArgumentNullException.ThrowIfNull(ViewItems);
if (itemProperty == null)
return;
if (searchString == null)
searchString = string.Empty;
await Task.Run(() =>
{
foreach (var item in ViewItems)
{
var property = itemProperty(item.Item);
if (property == null)
continue;
item.IsVisible = property.ToString().ToLower().Contains(searchString.ToLower());
}
});
StateHasChanged();
}
}
I'm getting the warning for property.ToString() As you can see I have already added a bunch of null-checks, but none seems to get rid of the warning. As far as I can see it is impossible for property to be null at the this point. Obviously I'm missing something...so what could be triggering this warning?
The problem is that ToString() can return null; it is bad practice, but: it can:
namespace System
{
public class Object
{
// ...
public virtual string? ToString();
// ...
}
}
the error goes away if you rule that out:
var s = property.ToString() ?? "";
item.IsVisible = s.ToLower().Contains(searchString.ToLower());
Note also that it is more efficient to use a comparison that ignores case, rather than forcing additional string allocations:
item.IsVisible = s.Contains(searchString, StringComparison.CurrentCultureIgnoreCase);

Wrong value displayed

I'm learning C#, I have this code :
namespace foo
{
public class Personnes
{
string[] m_Noms;
int m_NbElt;
int m_Max;
public Personnes(int Max)
{
m_Max = Max;
m_NbElt = 0;
m_Noms = new string[Max];
}
public int this[string Nom]
{
get { return Array.IndexOf(m_Noms, Nom); }
}
public string this[int i]
{
get { return m_Noms[i]; }
set { m_Noms[i] = value;m_NbElt++; }
}
}
class Prog
{
static void Main(string[] args)
{
Personnes Tableau = new Personnes(4);
Tableau[0] = "Anna";
Tableau[1] = "Ingrid";
Tableau[2] = "Maria";
Tableau[3] = "Ulrika";
Console.WriteLine(Tableau[1]);
Console.WriteLine(Tableau["Maria"]);
Console.WriteLine(Tableau[10]);
Console.WriteLine(Tableau["Toto"]);
}
}
}
I've been told that Console.WriteLine(Tableau[10]); should display null and the next line -1 but it doesn't, instead I have an error IndexOutOfRange, why ?
It is displaying IndexOutOfRangeException because you have set Tableau to have only 4 strings and any array retrieval beyond the index range[0 to 3] will result in this.
public string this[int i]
{
get { return m_Noms[i]; } <-- displays error if outside the range
set { m_Noms[i] = value;m_NbElt++; }
}
If you have to display null, then you need to add conditions in the indexer logic to check for the index value and if it is out of range return null
See you have initialized your array Tableau with just 4 Personnes(4). And you are trying to get what is at Tableau[10], so your are correctly getting IndexOutOfRange exception. The index that you are seeking is out of the range specified.
I've been told that Console.WriteLine(Tableau[10]); should display null and the next line -1 but it doesn't, instead I have an error IndexOutOfRange, why ?
Because whoever told you that was wrong. Accessing an array with an index that does not exist should throw an exception.

Error on Value of Dictionary and List Declaration due to negative sign value C#

What does this error mean on my code i see while debugging some output are negative which triggers this error while also in the other hand i saw a Dictionary with two parameters int and decimal but then to be stored to a list of int declare could this be also triggering the crash? what are the possible remedy for this crash error?
Picture of the Error Message Crash
function is declared on a class called PriceTierModel
private Dictionary<int, decimal> _unitPrices = new Dictionary<int, decimal>(); // key == TurnTime
public void AddPrice(int turnTimeValue, decimal price)
{
_unitPrices[turnTimeValue] = price;
}
public List<int> TurnTimes
{
get
{
List<int> turnTimes = _unitPrices.Keys.ToList();
turnTimes.Sort();
return turnTimes;
}
}
which is used here in this other class
public override string Error
{
get
{
PriceTierModel priceTier = GetPriceTier();
try
{
if (priceTier != null && _desiredTurnTime < Math.Abs(priceTier.TurnTimes[0]))
{
return String.Format(CadFramework.Rm.GetString("TurnTimeTooSoon"), priceTier.TurnTimes[0]);
}
}
catch (Exception ei) { return String.Format(CadFramework.Rm.GetString("TurnTimeTooSoon"), Math.Abs(priceTier.TurnTimes[0])); }
return "";
}
}
Added Code for Showing implementation use of the function.
foreach (XElement tier in priceTiers)
{
// possible that the tier element is invalid
//<price_tier>
// <turn_time></turn_time>
// <unit_price>N/A</unit_price>
// <turn_time_days>None days</turn_time_days>
//</price_tier>
int turnTime;
// ReSharper disable once PossibleNullReferenceException
if (int.TryParse(tier.Element("turn_time").Value, out turnTime))
{
decimal unitPrice = decimal.Parse(!string.IsNullOrEmpty(tier.Element("unit_price").Value) ? tier.Element("unit_price").Value : "0", CultureInfo.InvariantCulture);
priceTier.AddPrice(turnTime, unitPrice); <-- Here
}
}
This error means, that the line:
try
{
/* --> */ if (priceTier != null && _desiredTurnTime < Math.Abs(priceTier.TurnTimes[0]))
{
return String.Format(CadFramework.Rm.GetString("TurnTimeTooSoon"), priceTier.TurnTimes[0]);
}
or the line:
public void AddPrice(int turnTimeValue, decimal price)
{
/* --> */ _unitPrices[turnTimeValue] = price;
}
is entering or accessing (thanks to commentator) an item that is not existing in one of the both list.
From MSDN (IndexOutOfRangeException):
The exception that is thrown when an attempt is made to access an
element of an array or collection with an index that is outside its
bounds.

ASP.NET Entity Framework property not loaded while ID filled

This is something that worked up to now and now it just, stopped working (I know, weird, there's probably some silly mistake..)
I have a TripsVM, which contains a list of trips. I load these in my service, returning a List<>.
The problem occurs when I iterate over the trips collection and try to get trip.TripCategory.Name, as the TripCategory is empty, even though TripCategoryID has a value.
This all happens at the backend, I load the trips and then try to iterate over them, they are not being send from the page.
I could probably just load the trip by trip itself, but it used to work and this bug just came up after months of usage.
Any suggestions of where to look for bugs would be really appreciated.
Thanks
Error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Where error occurs:
foreach (Trip trip in tripsVM.TripsList) {
var a = trip.TripCategory.Name;
TripsVM:
private List<Trip> _TripsList;
public List<Trip> TripsList
{
get
{
if (_TripsList == null)
{
_TripsList = TripsService.GetTrips();
if (_TripsList == null)
_TripsList = new List<Trip>();
}
return _TripsList;
}
set { _TripsList = value; }
}
Service:
public static List<Trip> GetTrips()
{
return DB.Trips.Where(...).OrderBy(...).ToList();
}
Trip class:
public partial class Trip
{
public int TripID { get; set; }
public int TripCategoryID { get; set; }
....
public virtual TripCategory TripCategory { get; set; }
}
Its looks like your DB context disposed before foreach code or LazyLoadingEnabled set to false in context.
In Service add using
using System.Data.Entity;
And modify loading method
public static List<Trip> GetTrips()
{ return DB.Trips.Where(...).Include(t=>t.TripCategory).OrderBy(...).ToList(); }
I think your code looks fine but you should add some if statements to avoid null exception, because you are returning something with where clause, so you might end up with empty query result and empty list, and in that list you are trying to reach an element of a list object:
if(tripsVM.TripsList != null){
foreach (Trip trip in tripsVM.TripsList) {
var a = trip.TripCategory.Name;
}
}
else
{
// handle empty list
}
private List<Trip> _TripsList;
public List<Trip> TripsList
{
get
{
_TripsList = new List<Trip>();
if(TripsService.GetTrips() != null)
{
_TripsList.add(TripsService.GetTrips());
}
return _TripsList;
}
set { _TripsList = value; }
}

Why does my Web API / REST / Windsor code get routed in this direction?

I probably will not be able to provide enough information/insight for anybody to answer this question absolutely, but I'm hoping, by giving the best overview I can of the dilemma, to get thrown a bone that will be crunchy and marrowful enough to be of help.
I'm trying to trace the path a REST call takes through my code so that I can see how I can get it, at a certain point, to go here instead of there (where it is going).
Specifically, I don't know why the GetCount() method here:
namespace NRBQ.Client
{
public class RESTNRBQDelivery : INRBQDelivery
{
INRBQClientSettings NRBQClientSettings;
IRESTAPIClient RESTAPIClient;
public RESTNRBQDelivery(IRESTAPIClient RESTAPIClient, INRBQClientSettings NRBQClientSettings)
{
this.NRBQClientSettings = NRBQClientSettings;
this.RESTAPIClient = RESTAPIClient;
}
public RESTNRBQDelivery(IRESTAPIClient RESTAPIClient, INRBQClientSettings NRBQClientSettings, AuthenticationHeaderValue AuthHeader)
{
this.NRBQClientSettings = NRBQClientSettings;
this.RESTAPIClient = RESTAPIClient;
this.RESTAPIClient.AuthHeader = AuthHeader;
}
public int GetCount()
{
var res = RESTAPIClient.GET<int>(0
, new Uri(NRBQClientSettings.NRBQAPI)
, "api/deliveries/Count"
);
if (res.status != RequestResultStatus.Success)
{
throw new Exception(res.message);
}
return res.result;
}
...calls this:
namespace SeaStore.Data.Legacy.NRBQ
{
public class NRBQSQLRepository : INRBQRepositoryInterface
{
private INRBQRepositorySettings Settings;
private IMSAccessHelper MSAccessHelper;
public NRBQSQLRepository(INRBQRepositorySettings settings, IMSAccessHelper MSAccessHelper)
{
this.Settings = settings;
this.MSAccessHelper = MSAccessHelper;
}
public int GetNRBQEntity()
{
. . . // this is the method that is called
I would prefer that it would call this class, which lives beneath the same folder as the code above:
namespace SeaStore.Data.Legacy.NRBQ
{
public class NRBQDeliveryRepository : INRBQDeliveryRepository
{
private INRBQRepositorySettings Settings;
private IMSAccessHelper MSAccessHelper;
public NRBQDeliveryRepository(INRBQRepositorySettings settings, IMSAccessHelper MSAccessHelper)
{
this.Settings = settings;
this.MSAccessHelper = MSAccessHelper;
}
public int GetCount()
{
return 42; // <= I want it to go to here, not to its sibling
}
Again, this is just the tip of the meltburg, and I know it's unreasonable to expect an answer from this tidbit of info, but: Is there some tool or procedure by which I can suss out just why the path through the code takes this fork rather than the other?

Categories