Illogical NullReferenceException - c#

So in my normal course of getting some work done, i came across a generic System.NullReferenceException: 'Object reference not set to an instance of an object.'.
So no problem i'm thinking as I start looking for the culprit. After much debugging, I threw my hands up in the air and wanted to give up for the moment... My strategy for bypassing this was to just instantiate an array instead of calling some service for the data.
So i changed:
var data = service.GetData(someId);
to
var data = new DataType[]{};
to get my code compiling and debuggable so i can come back to this.
The kicker: upon doing so, i'm still getting the exception on that line. So JUST an array instantiation is yielding this exception. The exception has zero data to it. No inner exception or stack trace beyond pointing to this line. The class itself is just a poco with no methods (no constructor either) so nothing is happening internally. (see below for the class)
My next thought is that clearly, the code i'm seeing isn't what my debug session is using.
To test this thought I've
Cleaned in VS
manually deleted the bin
manually deleted obj
removed all package directories
restarted my computer
tried it in the new beta of VS
tried it in JetBrains' Rider
still i'm facing this.
Anyone have thoughts on how i can get more details on why this is happening, or is there something else I should be cleaning?
I've also looked at the output of git clean -xdn to see what kind of ephemeral stuff is hanging around that could be removed and nothing of interest there...
no matter what code is actually on the line, if i completely comment out this line and have completely different code there in it's place (as initially described), then that code throws the exception instead. i just had one of my colleagues grab this branch and run it and it was fine for them
3 hours deep so far... no fun
Edit:
as requested, here's a definition:
using System;
using Dapper.Contrib.Extensions;
namespace some_namespace
{
#pragma warning disable 1591
[Table ("CompanyOptions")]
public class CompanyOption
{
[ExplicitKey]
public Guid PKID { get; set; }
public Guid CompanyPKId { get; set; }
public string OptionName { get; set; }
public string OptionValue { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
public string UpdatedBy { get; set; }
}
}

So it seems there were issues with my installation of some microsoft packages.
I found that running Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r in the package management console to reinstall solved my problem. In looking at the diff that that yielded, the only meaningful thing is the following target framework bumps in my packages.config:
These package references haven't changed recently and the project has been targeting 4.7.1 for quite some time now so not sure why the sudden problem. Seems something became corrupted in the roslyn layer perhaps?
Going to slowly back away from my computer now.

Related

ReadSoft Invoices could not create instance of class name

I am currently trying to develop a custom ReadSoft Invoices plugin, nothing special.
I have gotten the plugin to work on two different machines, but the third machine I have, simply refuses to load the plugin.
The "funny" part about this, is that the third machine is a complete replica of the other two (they are all virtual machines).
The error shown when launching manager is: Plug-ins could not be loaded. (TESTPLUGIN(ClassName=TestPlugin.Test.Connect)).
I have run Regasm.exe on the dll so all the types are registered.
I have updated eilocal.ini with this:
;***********************
;* Manager *
;***********************
[Plugins::eimngr]
Plugin1=Common
Plugin2=DBMaintenance
Plugin3=ERPImport
Plugin4=InvoiceSelection
Plugin5=AutoValue
Plugin6=COLLECTOR
Plugin7=ReadSoft.InvoiceRules
Plugin8=TestPlugin
[eimngr::TestPlugin]
Name=TestPlugin
Type=COM
SupportIDispatch=TRUE
Classname=TestPlugin.Test.Connect
I have stripped all code from the plugin, just to make sure.
This is the code I am trying to run:
namespace TestPlugin
{
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[ProgId("TestPlugin.Test.Connect")]
public class TestConnect
{
public TestConnect()
{
}
public int Connect(object objEHIApp, string sIniFile, string sIniSection)
{
File.AppendAllText(#"C:\ProgramData\ScanSolutions\TestPlugin.txt", "Plugin Connected!");
return 0;
}
public int Disconnect(object objEHIApp)
{
return 0;
}
public int IsVistaConverted()
{
return 0;
}
}
}
Since the error message from manager really does not help me track down the problem, I have been looking for a log, but have not yet found one.
To debug my issue I have then attached a debugger to the manager module, which just tells me this, when trying to load my plugin:
Could not create instance of class name TestPlugin.Test.Connect with
clsid {B21CE504-ADDA-3174-BEB8-D359F85D9A63}.
Does anyone what is happening here?
Thanks in advance.

Adding class to EF Model cause compile error "The type or namespace name <className> could not be found"

Strange one, I've already added 5 tables with no problem. However, when I try and add my PostCodesUK table through my edmx model, it gives me this error message:
Error 1 The type or namespace name 'PostCodesUK' could not be found (are you missing a using directive or an assembly reference?) d:\Ben\documents\visual studio 2013\Projects\DogWalks\DogWalks\App_Code\WalksModel.Context.cs 33 30 DogWalks
Not sure what is happening but there are some subtle differences. For example, if I look under the WalksModel.tt classes, I can see the PostCodesUK class, but it hasn't generated the additional 'stub':
If I then double click the error above, it takes me to the WalksModel.Context.cs where I see this error:
I've looked at the namespace under the PostCodesUK.cs class, which matches the other classes. Does anyone know what the issue is? I have searched online for the issue but could not find a solution.
Update: This is what the PostCodeUK class looks like:
namespace DogWalks.App_Code
{
using System;
using System.Collections.Generic;
public partial class PostCodesUK
{
public int PostcodeID { get; set; }
public string Postcode { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string PostcodeNoSpace { get; set; }
}
}
Furthermore, I've added another temporary table (Person) to my model to test it and it's also giving me the same error message as PostCodesUK:
public virtual DbSet<Comment> Comments { get; set; }
...
public virtual DbSet<PostCodesUK> PostCodesUKs { get; set; } //error
public virtual DbSet<Person> People { get; set; } //error
Ok after spending countless hours trying to find a solution I may have actually solved it (touch-wood).
I got frustrated so I deleted my edmx model. Reading online, I found there was a bug with VS 2012 when the edmx model was saved in a subfolder (not in the root). So this might be something to try if my solution below doesn't work, although I managed to keep it in a subfolder.
Anyway, after deleting my model:
I readded the whole database model to a new folder called DAL. When I tried to compile, I noticed ALL of my classes were now throwing the same error.
I changed all of the build action for all the classes (From Content to Compile)
Rebuilt app and it worked.
So to put it to the test I tried:
Adding another table to my model, Person.
Tried to compile (it actually compiled ok) but when I looked at the Person.cs file under Model.tt I saw the stub was once again missing:
I changed the Build Action setting to Compile, saved, closed VS and reopened it and the stub appeared correctly:
I don't know if that was the issue, but it seems to be working. I didn't check my original case but I have a suspicion that I changed the .cs compile mode for my original classes, but not for the newly added classes.
I'm just glad I held off from turning my machine into scrap metal.

Table has no (public) columns only on real device

I have the simplest of apps that I thought I would try on my device before I got too engrossed. However, I am getting the strangest error message when I run it on my iPhone (as apposed to the the emulator on my macbook).
Table has no (public) columns .
I am using the SQLite.Net PCL and I have built it from git hub as I had some problems with it not having the platform dlls for IOS otherwise.
Relevant code.
In my models I have this:
public class Setting
{
[PrimaryKey, AutoIncrement]
public long Id { get; set; }
[Indexed]
public string Key { get; set; }
public string Value { get; set; }
}
The code that throws this error message is the simple:
using (SQLiteConnection db = GetCon ()) {
db.CreateTable<Setting> ();
}
but in my opinion the strangest thing is that this code works fine on the emulator but crashes the application on the iphone itself.
If anyone has some ideas that would be great.
EDIT:
This error is thrown on the SQLite.Net-PCL library on this file line 380 but only on the device and not on the emulator.
For others to whom this may concern, I found the answer to my problem. The issue was with the Type not having any properties (the type in question the simple model class). Knowing that to be rubbish I found the following links that gave more information which I will relate in this post in case the links go dead:
Type.GetProperties returning nothing
NOTE: Be careful with assembly linker
If you're building with linker enabled you may need to use the class
somewhere, so it will not be ripped off at compile time. Sometimes,
only instantiating the class in your code is not enough, the linker
may detect that the instance is never used and will remove it anyway.
http://developer.xamarin.com/guides/ios/advanced_topics/linker/
The linking process can be customized via the linker behavior
drop-down in Project Options. To access this double-click on the iOS
project and browse to iOS Build > Linker Options, as illustrated below
(see link for details)
I have for now left it to be unlinked, however, I will try before release to get the linker to ignore these classes. Thanks for all your help.
I found my problem was just a (not that subtle) programming error. I was working with the TypeInfo class and wanted to use the Sqlite Connection method:
CreateTable (Type type);
What I had in my hand was a TypeInfo instance which I needed to convert back to the System.Type. I accidentally without thinking used the GetType() method instead of AsType() method which is obvious when you think about it. The clue I got was in the exception message along with the OP message was does System.Runtime have public properties?
var type = table.TypeInfo.AsType();
// var type = table.TypeInfo.GetType(); *WRONG*
connection.CreateTable(type);

Deserializing json string into an object - Silverlight

I've spent a good while this afternoon trying to implement the deserialization of JSON within a string, at first I was using DataContractJsonSerializer as my environment is Silverlight however it does not appear to support using a Dictionary out of the box (Raised in many other SO questions).
As an alternative I decided to use JSON.NET for the time being (Based on the answers to the aforementioned SO questions) and i've hit the following problem.
I want to deserialize the JSON below:
{
"disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability or fitness for any purpose; use at your own risk. Other than that - have fun, and please share/watch/fork if you think data like this should be free!",
"license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given.",
"timestamp": 1334183999,
"base": "USD",
"rates": {
"AED": 3.6732,
"AFN": 48.400002,
"ALL": 106.669998,
}
}
and place it within the following object (the double within the dictionary is required):
public class ExchangeData
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string #base { get; set; }
public Dictionary<string, double> rates { get; set; }
}
My latest attempt at actually getting this to work is below:
StreamReader reader = new StreamReader(args.Result);
ExchangeData data = JsonConvert.DeserializeObject<ExchangeData>(reader.ReadToEnd());
But this results in the following exception:
Could not load type 'System.Dynamic.IDynamicMetaObjectProvider' from assembly 'System.Core, Version=3.7.0.0, Culture=neutral, PublicKeyToken=969DB8053D3322AC'.
Based on what you can see is my approach completely wrong or am I just making a schoolboy error (or both!)
Thanks for your time!
I think that would help you:
JavaScriptSerializer ser = new JavaScriptSerializer();
ExchangeData foo = ser.Deserialize<ExchangeData>(args.Result);
I am not really sure you need to use StreamReader, what do you use it anyway?
By the way I assume args.Result is json string.
The exception message itself appears to be a known problem as raised in this SO question:
Moving to JSON.NET 4.0.3 broke my app
After using Nuget to install the latest package with all necessary dependencies (I manually downloaded the .DLL's from the CodePlex project previously) the code worked with no additional changes.
Thank you to the users who provided solutions.
According to your exception: (a simple google search pulled up this answer)
It seems like your project is referencing to an older version of Silverlight runtime.
To check, bring up the project property in Visual Studio, and ensure the Silverlight version is set to 4.0.
You might also want to double check the System.Windows.Controls.Navigation assembly, make sure it's referencing to latest version which usually located in [Program Files]\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\System.Windows.Controls.Navigation.dll
And the following:
"rates": {
"AED": 3.6732,
"AFN": 48.400002,
"ALL": 106.669998,
}
Is not in JSON, an Array, it is an object. An Array would look like:
"rates": [
"AED": 3.6732,
"AFN": 48.400002,
"ALL": 106.669998,
]
So either you have to get the source to properly format it's JSON, or you need to manually setup the deserialization for this specific piece to populate a dictionary.

Warning “The type X in Y.cs conflicts with the imported type X in Z.dll”

The main.cs of my project returns the following warning:
Warning 1 The type 'Extensions.MessageDetails' in 'PATH\Extensions.cs' conflicts with the imported type 'Extensions.MessageDetails' in 'path\lib.dll'. Using the type defined in 'path\Extensions.cs'. path\main.cs
What is wrong with my project? How to get rid of the warning?
The code of my project has the following structure:
Extensions.cs
namespace Extensions
{
public class MessageDetails
{
public string message { get; set; }
public string link { get; set; }
public string picture { get; set; }
public string name { get; set; }
public string caption { get; set; }
public string description { get; set; }
public string userid { get; set; }
public string username { get; set; }
public object actions { get; set; }
public object privacy { get; set; }
public object targeting { get; set; }
}
}
lib.dll
namespace MyClassLib {
public class MyClassLibFoo {
public void foo(MessageDetails parameters) {
/* .. */
}
}
}
main.cs
using MyClassLib;
using Extensions;
class Program
{
static void Main(string[] args)
{
MessageDetails md = new MessageDetails();
}
}
In my case, with Visual Studio 2013, I found that one of my class libraries had developed a reference to itself. I think it happened when I added a new project to my solution or it was a bug, but either way it was causing this exact issue.
Check your project references for any circular references.
It seems like Extensions.cs is both part of the project that builds lib.dll and your main.exe
Remove it from one of the project to fix this issue.
I had this kind of issue where I had reverted from a target .NET Framework version of 4.5.2 to 4.0.
Classes in my App_Code folder had methods that called methods in other classes in that folder. When I created a standard folder I named "AppCode", and moved my classes into it, I no longer had the issue.
If I re-created the "App_Code" folder and move my classes back into it, I will have this issue again. I'm convinced it has to do with my .NET Framework version or that Visual Studio just doesn't deal well with changing it after being initially built/targeted to another version.
You can't have two copies of the extensions class, even though the code is the same they are not seen as the same object. Both your dll and main application will need to reference the exact same one.
You could try creating a 'Common Files' class library and add the extensions class to it, that way you will always be using the correct class
I had this problem with a project that is also hosted on NuGet. I checked all project references. Finally, the object browser revealed that the DLL of an older version of my NuGet package was somehow loaded in Visual Studio from the NuGet cache folder ("C:\Users\{username}\.nuget\packages"). I removed the package from the cache folder, it disappeared from the object browser and everything was working fine again.
I had a Shared Project, "Project A," which was included in both "Project B" and "Project C."
"Project A" was added as a Shared Project in "Project B" and "Project C."
"Project A" also included a traditional reference to "Project B."
To correct the problem, I removed the reference to "Project B" from "Project A."
If you really need to have both classes declared or referenced in two separate dll, you can mark your class as internal.
Internal types or members are accessible only within files in the same assembly, therefore it will prevent the collision.
After reading through many answers on SO the solution was still unclear. My situation was similar but the solution was found by:
Example project Name: My.Example.Project
Opening my project
Open the References dropdown
Finding My.Example.Project in the References section
Deleting the reference to My.Example.Project
That fixed it!
I had faced same problem. Just a simple solution for that.
Check your project references there must be same project reference. just remove that, it will work.
sometimes I get this error - it's a bug though in my case.. All I have to do to fix it is change the first letter of my script file name from upper case to lowercase in the file in Explorer /
(or in Unity Engine in my case)
and then change the name / class accordingly in my script. Idk why this happens.. just does - and Idk why this fix works .. but in my case it always does. - Otherwise you probably have 2 copies of the same script / same class name for 2 diff scripts. Hope this helps.
I fixed this error by deleting the .suo file in the directory sturcture vs directory. stop vs then delete restart vs. that worked for me.

Categories