Object reference not set to an instance of an object.

Roust_m

Member
Joined
May 29, 2022
Messages
9
Programming Experience
Beginner
Hi,

I have this code which is running fine in my console project:
C#:
       public async Task Insert_BalanceSheet(DateTime reportDate, int entityID, DateTime periodStart, DateTime periodEnd, string timeFrame, AccountingApi apiInstance, string xeroTenantId, string accessToken, string dataDB)
        {
            ...
            try
            {
                Xero.NetStandard.OAuth2.Model.Accounting.ReportWithRows pal = await apiInstance.GetReportBalanceSheetAsync(accessToken, xeroTenantId, startDate, 1, timeFrame, null, null, true, false);           
                fullReport = JsonSerializer.Serialize(pal);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to obtain Xero Balance Sheet report for entity: " + entityID + " start date: " + startDate + " end date: " + endDate);
                Console.WriteLine("IOException source: {0}", e.Source);
                Console.WriteLine(e.ToString());
            }
            ...
        }
When I call it from a console project it works fine. When I call this from a web project, it crashes on this line:
Xero.NetStandard.OAuth2.Model.Accounting.ReportWithRows pal = await apiInstance.GetReportBalanceSheetAsync(accessToken, xeroTenantId, startDate, 1, timeFrame, null, null, true, false);
with this error:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

It does not even go the catch part of the exception, so I don't get an insight of what is going on there.

Any ideas?

Thanks.
 
Where does apiInstance come from? Does it look the same in both cases?
In fact I have another method which calls Insert_BalanceSheet, which in turn calls the failing one of GetReportBalanceSheetAsync:
C#:
public async Task Call_BalanceSheet(DateTime reportDate, int entityID, DateTime periodStart, DateTime periodEnd, AccountingApi apiInstance, string xeroTenantId, string accessToken, string connectDB, string dataDB)
{
    int delay_ms = 1000;
    string timeFrame = "MONTH";
    int reportStatus = CheckReportStatus("Balance Sheet", connectDB);
    if (reportStatus == 1)
    {
        DateTime monthStartDate = periodStart;
        DateTime monthEndDate = monthStartDate.AddMonths(1).AddSeconds(-1);
        while (monthEndDate < periodEnd)
        {
            await Insert_BalanceSheet(reportDate, entityID, monthStartDate, monthEndDate, timeFrame, apiInstance, xeroTenantId, accessToken, dataDB);
            monthStartDate = monthStartDate.AddMonths(1);
            monthEndDate = monthStartDate.AddMonths(1).AddSeconds(-1);
            System.Threading.Thread.Sleep(delay_ms);
        }
    }
}
In both console and web app I call Call_BalanceSheet which gets the apiInstance as a parameter and passes it to Insert_BalanceSheet and is used with GetReportBalanceSheetAsync. So everyting seems the same.
 
Last edited by a moderator:
So everyting seems the same.
But are they actually the same? Don't assume. Actually look. If things were always as we expected them to be then there'd be no bugs in the first place. Look at the two objects and see if there are any differences.
 
Between lines 5 and 6 of the code in post #1, I would suggest putting a System.Diagnostics.Debug.Assert(apiInstance != null);. If you are assuming that it is not null, document then enforce that assumption in your code.

Also, you don't need the catch to determine the details of your problem. You have a very powerful IDE at your fingertips: Visual Studio. Just let Visual Studio catch the first chance exception. You can then inspect the variables as well as look up the callstack to determine where that null object is coming from.
 
Last edited:
Between lines 5 and 6 of the code in post #1, I would suggest putting a System.Diagnostics.Debug.Assert(apiInstance != null);. If you are assuming that it is not null, document then enforce that assumption in your code.

Also, you don't need the catch to determine the details of your problem. You have a very powerful IDE at your fingertips: Visual Studio. Just let Visual Studio catch the first chance exception. You can then inspect the variables as well as look up the callstack to determine where that null object is coming from.

I've put this in, it still crashed on the same command. apiInstance is not null, I could see it when hovering my mouse over the variable.

How can I catch the exception using VS?
 
Where does apiInstance come from? Does it look the same in both cases?
I use this method to return apiInstance:

C#:
        public async Task<AccountingApi> Xero_Connect(string clientId, string clientSecret, int entityID)
        {

            XeroConfiguration xconfig = new XeroConfiguration();
            xconfig.ClientId = clientId;
            xconfig.ClientSecret = clientSecret;
            xconfig.CallbackUri = new Uri("http://localhost:8080/callback"); //default for standard webapi template
            xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts accounting.reports.read accounting.settings accounting.settings.read";
            var client = new XeroClient(xconfig);
            var connectDB = ConfigurationManager.AppSettings["ConnectDB"];
            XeroOAuth2Token newXeroToken = await RefreshToken(clientId, xconfig, entityID, connectDB);
            var apiInstance = new AccountingApi();
            return apiInstance;

        }

It is a way to connect to Xero and call Xero methods such as: await apiInstance.GetReportBalanceSheetAsync(accessToken, xeroTenantId, startDate, 1, timeFrame, null, null, true, false);
 
I've put this in, it still crashed on the same command. apiInstance is not null, I could see it when hovering my mouse over the variable.

How can I catch the exception using VS?
Debug > Windows > Exception Settings...
In the Exception Settings window/pane find and expand "Common Language Runtime Exceptions".
Make sure that "System.NullReferenceException" has a check mark beside it.

Then:
Tools > Options
Under "Debugging" select "General".
On the right hand pane, uncheck "Enable Just My Code".
 

Latest posts

Back
Top Bottom