question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NullReferenceException in calls to Barrel.Current.Get for MonkeyCache.FileStore

See original GitHub issue

I’m getting a NullReferenceException on a call to Barrel.Current.Get<T>(key);

I have a very, very async console app that is retrieving a ton of data from our azure devops instance and caching it using MonkeyCache.FileStore. I wound up wrapping it in Polly retries just to get around it.

Stacktrace:

   System.NullReferenceException: Object reference not set to an instance of an object.
           at Interop.BCrypt.BCryptHashData(SafeBCryptHashHandle hHash, ReadOnlySpan`1 pbInput, Int32 cbInput, Int32 dwFlags)
           at System.Security.Cryptography.HashProviderCng.AppendHashData(ReadOnlySpan`1 source)
           at System.Security.Cryptography.HashProvider.AppendHashData(Byte[] data, Int32 offset, Int32 count)
           at System.Security.Cryptography.HashAlgorithm.ComputeHash(Byte[] buffer)
           at MonkeyCache.FileStore.Barrel.Hash(String input)
           at MonkeyCache.FileStore.Barrel.Get[T](String key, Func`2 deserialize)
           at MonkeyCache.FileStore.Barrel.Get[T](String key, JsonSerializerOptions options)
           at GITMigration.Core.Repositories.RepositoryService.<>c__DisplayClass12_0.<GetStatusReponseAndIndexingInformation>b__2() in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GITMigration.Core\Repositories\RepositoryService.cs:line 174
           at Polly.Policy.<>c__DisplayClass114_0`1.<Execute>b__0(Context _, CancellationToken _)
           at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Action`4 onRetry, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider)
           at Polly.Retry.RetryPolicy.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken)
           at Polly.Policy.Execute[TResult](Func`3 action, Context context, CancellationToken cancellationToken)
           at Polly.Policy.Execute[TResult](Func`1 action)
           at GITMigration.Core.Repositories.RepositoryService.GetStatusReponseAndIndexingInformation(String org, String project) in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GITMigration.Core\Repositories\RepositoryService.cs:line 171
           at GITMigration.Core.Repositories.RepositoryService.GetRepoItemsSummary(String org, String project) in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GITMigration.Core\Repositories\RepositoryService.cs:line 35
           at GITMigration.Core.Sheets.Master.MasterWorksheet.GetRow(String org, String project) in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GITMigration.Core\Sheets\Master\MasterWorksheet.cs:line 69
           at GITMigration.Core.Sheets.Master.MasterWorksheet.<>c__DisplayClass7_0.<<AddWorksheet>b__1>d.MoveNext() in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GITMigration.Core\Sheets\Master\MasterWorksheet.cs:line 47
        --- End of stack trace from previous location ---
           at GITMigration.Core.Sheets.Master.MasterWorksheet.AddWorksheet(IExcelBuilder builder, Organization[] orgs) in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GITMigration.Core\Sheets\Master\MasterWorksheet.cs:line 47
           at GitMigration.AsyncConsole.Worker.ExecuteAsync(CancellationToken stoppingToken) in C:\repos\ResearchAndDevelopment\archtools\gitmigration\GitMigration.AsyncConsole\Worker.cs:line 47
           at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)

My “fix” in the calls to the cache:

private async Task<GitPushesResponse> GetLatestGitPushes(string org, string project, string repoId)
{
    string key = $"{org}-{project}-{repoId}-gitpushes";
    var response =
        Policy
            .Handle<NullReferenceException>(ex => ex.Message.Any())
            .Retry((exception, retryCount) => _logger.LogWarning($"Retry Execute GetCache for {key}..."))
            .Execute(() => Barrel.Current.Get<GitPushesResponse>(key));

It’s failing inside of the hashprovider, but succeeds on future calls – so, repeatedly re-running the console app eventually gets me what I need. Happy to look into it if anyone has some ideas.

Issue Analytics

  • State:closed
  • Created 5 months ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
vcsjonescommented, Apr 20, 2023

👋 from dotnet/runtime.

Will that still always output the same data?

Yes.

It looks like you’re targeting .NET 6:

https://github.com/jamesmontemagno/monkey-cache/blob/master/src/MonkeyCache.FileStore/MonkeyCache.FileStore.csproj#L4

This API is new in .NET 5. The static HashData is strictly better than using the instances. I’d recommend you use it. The statics are thread safe, they don’t allocate (except the byte[] that gets returned if you use an allocating overload), and they will be faster.

1reaction
jamesmontemagnocommented, Apr 19, 2023

So,

I would test what is causing the issue via:

var hashAlgorithm = MD5.Create();

string Hash(string input)
{
	var data = hashAlgorithm.ComputeHash(Encoding.Default.GetBytes(input));
	return BitConverter.ToString(data);
}

Perhaps something is wrong with the input?

Read more comments on GitHub >

github_iconTop Results From Across the Web

jamesmontemagno/monkey-cache
Easily cache any data structure for a specific amount of time in any .NET application. Monkey Cache is comprised of one core package...
Read more >
Get Sharing violation exception · Issue #56
I just moved from MonkeyCache.LiteDB to MonkeyCache.FileStore since I had performance issues if the cache was getting too big.
Read more >
Data Caching Made Simple with Monkey Cache 🐒 for .NET
There is 1 barrel that items get stored in and Monkey Cache provides a singleton method that returns an IBarrel: var currentBarrel =...
Read more >
Improve Xamarin Forms App UX by Data Caching
In this article, I'm going to show you how to do data caching by using the Monkey-Cache library by James Montemagno. Let's explore...
Read more >
MonkeyCache step by step
MonkeyCache works on the premise that you have exactly one barrel at your disposal, and you throw everything you want to cache into...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found