Getting Null Reference Exception on contentRepository.Delete



I have been trying to programmatically delete media files with contentRepository.Delete() and every time I run it I get a NullReference Exception. 

the code looks like something like this:

[TemplateDescriptor(Inherited = true)]
public class TestBlockComponent : AsyncBlockComponent<TestBlock>
    private readonly Injected<IContentRepository> _contentRepository;

 protected override async Task<IViewComponentResult> InvokeComponentAsync(TestBlock currentBlock)
        var mediafiles = _contentRepository.Service.GetChildren<CustomPdfFile>(new ContentReference(currentBlock.Folder));

        for (var i = 0; i < mediafiles.Count(); i++)
            var list = mediafiles.ToList();

            _contentRepository.Service.Delete(list[i].ContentLink, true, AccessLevel.NoAccess);

        return await Task.FromResult(View("~/Features/Blocks/TestBlock/TestBlock.cshtml", model));
Aug 01, 2023 23:04

first of all, as a side note, you should move var list = mediafiles.ToList(); to outside of the for loop

second of all, can you check if list[i].ContentLink is not throwing the null reference exception itself ? 

new ContentReference(currentBlock.Folder) - this also does not look right to me. how does currentBlock.Folder look like?

Aug 02, 2023 8:23

new ContentReference(currentBlock.Folder) is just where the folder id comes in because and that part is not null and neither is the list[i].ContentLink. Also thanks I missed that the list was being made inside the loop, but that change didnt fix the null exception. I also confirmed that the _contentRepository and the AccessLevel are not throwing null themsevles 

Aug 02, 2023 13:16

my (1) point was not meant to solve the problem, it's just a small thing that I spotted and can't keep quiet - old habit die hard.

so could you trace down there the null ref exception is thrown? 

Aug 02, 2023 13:21

Nope I am not still not sure why it is happening but I found  _contentRepository.Service.MoveToWasteBasket() is working fine with the same set up. So I may be able to work around it. 

Aug 02, 2023 13:25

Maybe you can debug it? or turn on debug mode (including the pdb to the bin folder) to see which line is throwing the exception ?

Aug 02, 2023 13:31

Could it be that your loop is trying to access content that was already deleted?

Maybe do a foreach-loop instead of a for-loop. That will simplify the code, and do forward-only iteration.

Aug 04, 2023 15:20
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.