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=
StackTrace:
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.

Sachin SinghRank #66 · 26.2K reputationPosted Jun 4, 2022, 3:05 PM EDT
what is apiInstance? is it an object name? if yes then have you instantiated it (ex:- new apiInstance)?
or if its a class name then is the method GetReportBalanceSheetAsync() static?
Basically, I want to ask, what are you doing in the console app that is working there? The only difference could be the way the method is called.
Roustam Akhmetov18 reputationPosted Jun 6, 2022, 6:26 AM EDT
I use this method to return apiInstance:
public async Task Xero_Connect(string clientId, string clientSecret, int entityID)
{
XeroConfiguration xconfig = new XeroConfiguration();
xconfig.ClientId = clientId;
xconfig.ClientSecret = clientSecret;
xconfig.CallbackUri = new Uri("some url"); //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);