Getting Null Reference Exception on contentRepository.Delete

Vote:
 

Hi,

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));
    }
}
#306084
Aug 01, 2023 23:04
Vote:
 

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?

#306085
Aug 02, 2023 8:23
Vote:
 

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 

#306099
Aug 02, 2023 13:16
Vote:
 

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? 

#306100
Aug 02, 2023 13:21
Vote:
 

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. 

#306101
Aug 02, 2023 13:25
Vote:
 

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 ?

#306102
Aug 02, 2023 13:31
Vote:
 

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.

#306233
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.