Unit test throwing NullReferenceException - c#

I've been trying to run a test on a method that loads data from an xml file and returns it as a list, however, I keep getting a NullReferenceException when it runs. I've checked and my filepath is fine.
[TestCase(1)]
public void firstTest(int num)
{
var studentList = StudentListGenerator.CreateStudentList(#"../../TestReport/TestData.xml");
Assert.IsTrue(studentList.Count() > num);
}
The stack trace points back to a line of code in my CreateStudentList method that works just fine if I insert it directly into the test itself (the method as a whole works well when I run it normally).
String xData = File.ReadAllText(filePath);
var x = new XmlSerializer(typeof (Report));
Report dataConverted = (Report) x.Deserialize(new StringReader(xData));
// the last line is where the stack trace ends
Anyone have a guess as to where I'm going wrong?
EDIT:
Here's a link to some of the StudentListGenerator class, which contains the CreateStudentList method: https://gist.github.com/jekrch/eecdd1c8de8a11268be0
And here's the full stacktrace:
at PFdata.Dashboard.Data.StudentListGenerator.CreateStudentList(String
filePath) in
C:\Users\CodeCamp\Desktop\StudentDataDashboard\StudentDataDashboard\Dashboard.Data\StudentListGenerator.cs:line
41 at DashboardTests.StudentDataCalcTests.firstTest(Int32 num) in
C:\Users\CodeCamp\Desktop\StudentDataDashboard\DashboardTests\StudentDataCalcTests.cs:line
22 Result Message: System.NullReferenceException : Object reference
not set to an instance of an object.

So the stacktrace on the original error was misleading. The real source of the NullReferenceException in the CreateStudentList method that I was testing was the following line:
Application.Current.Properties["reportMonth"] = reportMonth;
The problem was that the Application class was not being instantiated by the test. So the solution was to simply instantiate the application at the beginning of the test like so,
var app = new Application();
I got the idea to try this from a comment by Ben Raupov regarding a question about a similar issue. Many thanks to Unicorn2 for helping me factor out a number of other possibilities.

Related

Sudden Problems With Dynamic Not Working On (Only) My Machine

My basic setup is this:
//caller
dynamic thingThatEndsUpBeingAJObject = JsonConvert.DeserializeObject(await httpClientResponse.Content.ReadAsStringAsync());
var parsedThing = Parse(thingThatEndsUpBeingAJObject);
//elsewhere...
private async Task<ParsedThing> Parse(dynamic json)
{
dynamic referenceToThingIWant = json.ThingIWant;
return new ParsedThing{ SomeProp = referenceToThingIWant; }
}
...where I end up getting a RuntimeBinderException on the reference to json.ThingIWant.
Oddly, if I put a watch on:
((JObject)json)["ThingIWant"]
I can see darn well that it's there!
Even more perplexing is that the code runs fine on everyone else's machine (and I believe it ran fine on mine till days ago)!
What on earth could cause such a strange quirk?!?
I've gone as far as restarting the computer, FWIW.
Specific error/stack trace is:
'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'ThingIWant'
at Microsoft.CSharp.RuntimeBinder.RuntimeBinderController.SubmitError(CError pError)

How to get ExpandEnvironmentVariables to return custom variables?

I have added a custom environment variable and I'm unable to get it to return in the ExpandEnvironmentVariables.
These 2 calls work fine:
string s = Environment.GetEnvironmentVariable("TEST", EnvironmentVariableTarget.Machine);
// s = "D:\Temp2"
string path = Environment.ExpandEnvironmentVariables(#"%windir%\Temp1");
// path = "C:\Windows\Temp1"
However, this call returns the same input string:
var path = Environment.ExpandEnvironmentVariables(#"%TEST%\Temp1");
// path = "%TEST%\\Temp1"
I expect to get D:\Temp2\Temp1
What am I missing to correctly get the custom EnvironmentVariable in this last call?
Hans and Evk were correct in their comments. Since no one wanted to add an answer I'll close this question out.
For whatever reason ExpandEnvironmentVariables will not get any keys which were added after an application started. I also tested this with a running Windows Service. It was only after I restarted the service that new keys were found and populated.
This behavior is not documented in the Microsoft Documentation.

Getting MissingMethodException when using Manatee.trello to get list of users

I have the following code which is intended to fetch a list of all the user of an organisation.
public static IEnumerable<Member> ListTrelloUsers()
{
var serializer = new ManateeSerializer();
TrelloConfiguration.Serializer = serializer;
TrelloConfiguration.Deserializer = serializer;
TrelloConfiguration.JsonFactory = new ManateeFactory();
TrelloConfiguration.RestClientProvider = new RestSharpClientProvider();
TrelloAuthorization.Default.AppKey = ApplicationKey;
TrelloAuthorization.Default.UserToken = GrandToken;
var myOrganization = Member.Me.Organizations.FirstOrDefault().Id; //Exception thrown here.
var orgToAddTo = new Organization(myOrganization);
return orgToAddTo.Members.AsEnumerable();
}
But I'm getting a
System.MissingMethodException
thrown on
RestSharp.IRestRequest RestSharp.RestRequest.AddFile(System.String, Byte[], System.String)
So why is this exception thrown and what should the correctly working code look like?
Clarifications
I will also accept working C#/ASP.Net MVC code that isn't based on Manatee.Trello as an answer. (Including pure API-calls.)
I have tried using the Organisation ID directly as
var orgToAddTo = new Organization(OrganisationId);
but that just caused the same exception to be thrown later when I make a call to the method's returned object (e.g. using Count()).
UPDATE: I tried setting the build to Release instead of Debug and now the (same) exception is instead thrown at
TrelloConfiguration.RestClientProvider = new RestSharpClientProvider();
This is an issue with RestSharp that I reported quite some time ago, though they deny that it's a problem. If you're using .Net 4.5+, you can try the Manatee.Trello.WebApi package instead of Manatee.Trello.RestSharp.
TrelloConfiguration.RestProvider = new WebApiClientProvider();
Here's my Trello card for tracking the issue. This and this are the RestSharp issues I created.
I have been able to recreate this as well, but have received no help from them to resolve it.
Apperently, the class with missing method is located in an assembly, which differ from the one, which you used while compiling the project. Double check and make sure both at compiling and at execution you use the same assembly with the aforementioned class.
That is my best clue based on the info you've provided.
basically, check project references and make sure, you use correct ones for the class-holding assembly.

DbGeography.PointFromText error Exception has been thrown by the target of an invocation

I am starting my first project using spacial data. Im using VS 2012 and SQL 2012 I have referenced System.Data.Entity and can use DbGeography in my code but when I try to create a point I get the above error and don't understand why
here is my code
var text = string.Format(CultureInfo.InvariantCulture.NumberFormat,
"POINT({0} {1})", submitted.Long, submitted.Lat);
// 4326 is most common coordinate system used by GPS/Maps
try
{
var wkb = DbGeography.PointFromText(text, 4226);
}
catch (Exception exc)
{
}
the syntax that OP has used is correct, the actual issue that caused this error was the SRID, 4226 is not a known SRID, But you already knew this. because it is in your comment :)
A one line example of the correct usage in your scenario would be:
var wkb = DbGeography.PointFromText($"POINT({submitted.Long} {submitted.Lat})", 4326);
Where did you go wrong though? Whenever you get a
System.Reflection.TargetInvocationException
With a message of
Exception has been thrown by the target of an invocation
You must immediately check the Inner Exception for the details on the actual error, in this case it is outlined clearly for you:
24204: The spatial reference identifier (SRID) is not valid. The specified SRID must match one of the supported SRIDs displayed in the sys.spatial_reference_systems catalog view.
I realise that this is an old thread, but IMO this is an example of second most common .Net developer issue that people keep posting on SO. Please read through your full exception stack before pulling your hair out.
I'm just guessing, but I reckon NullReferenceException issues would be the most common :)
is wrong to order the lat and long
the correct is:
DbGeography.PointFromText(POINT(lat long), 4226);
Complete class:
public static DbGeography CreatePoint(double latitude, double longetude, int srid = 4326)
{
var lon = longetude.ToString(CultureInfo.InvariantCulture);
var lat = latitude.ToString(CultureInfo.InvariantCulture);
var geo = $"POINT({lat} {lon})";
return DbGeography.PointFromText(geo, srid);
}
Call:
CreatePoint(-46.55377, 23.11817)

DotNetCharting exception thrown

I am using DotNetCharting version 4.2. I am trying to create a chart, save it to disk and return the path as a string. Here is a simplified version of my code thus far.
Chart aChart = new Chart();
aChart aChart.Title = "Some Title";
aChart aChart.ChartArea.Background = new Background(Color.White);
aChart.TempDirectory = "C:\\temp\\"
aChart.Width = chartWidth;
aChart.Height = chartHeight;
imageName = aChart.FileManager.SaveImage();
I got this from this dotnetCharting support page. It is very straightforward code.
Here is the problem: The code above actually DOES create an image in the appropriate directory. This is NOT a directory permissions issue. When I add my actual data to the aChart, it actually DOES add it and an image is created. However, the SaveImage() method always throws an exception of "Failed to map the path '/'." The SaveImage() method is supposed to return a String, however, it always returns "" and the exception is thrown.
More Info: I am doing this in a WCF Service. Is it possible that since it's in a service the dotNetCharting DLL is having trouble with some internal MapPath?
I just upgraded the DotNetCharting to the latest version (7.0) and now it works fine. I believe that it was an issue with the old version of the DLL. I'll leave this here in case anyone else has this issue.

Categories

Resources