November Happy Hour will be moved to Thursday December 5th.

Adding items to a ContentArea programmatically

Nat
Nat
Vote:
 

I am trying to write some unit tests, which require a block/page to have some items added to a ContentArea, which I need to do in the code.

However, when I run the following code - it throws an error.

var page = repo.GetDefault<MyPageType>(ContentReference.EmptyReference);

var myContentArea = new ContentArea();

var cai = new ContentAreaItem{
   ContentGuid = Guid.NewGuid(),
   ContentLink = new ContentReference(123)
};

myContentArea.Items.Add(cai); // <-- throws error here complaining about object ref not set.

page.TheContentArea = myContentArea;

// ..etc

how can I add items to a ContentArea in the code.

thanks

#230241
Nov 02, 2020 14:09
Vote:
 

Hi Nat,

The code looks ok. You don't need to set the ContentGuid on your ContentAreaItem (as you're setting the ContentLink), but that shouldn't be related to the exception.

It's a NullReferenceException you're seeing, which probably means that your myContentArea is null. Is your code example the same as the sample you provided? If you set a breakpoint you should be easily able to identify the problem.

#230243
Nov 02, 2020 14:53
Vote:
 

From the top of my head, you should not create new content area like that, but 

var page = repo.GetDefault<MyPageType>(ContentReference.EmptyReference);

var cai = new ContentAreaItem{
   ContentGuid = Guid.NewGuid(),
   ContentLink = new ContentReference(123)
};

page.TheContentArea.Items.Add(cai);

Also ContentReference.EmptyReference does not make senses here.

of course I could be wrong thought

#230248
Nov 02, 2020 15:47
Nat
Vote:
 

It is a NullReferenceException, but not because the ContentArea is null.

at EPiServer.Core.ContentArea.AddContentAreaItemsToFragments(IList items, Int32 startIndex)
at EPiServer.Core.ContentArea.ModifyCollectionInternally(Action modification)
at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)

The ContentReference.EmtyReference is just a parent ref, so really doesnt matter what is used there as far as I can tell - and if I substitue that for a 'real' ContentReference, it falls over just the same.
This is for a unit test, so the repo will only have the items in that I add. 

Maybe the GetDefault<T> is not mocking/creating the necessary properties, but I have found very little information on how to write unit tests for Episerver, let alone what needs mocking as far as the repo is concerned.

#230250
Edited, Nov 02, 2020 16:38
Quan Mai - Nov 02, 2020 17:07
AH I see, missed the "unit test" part.
Vote:
 
#230252
Edited, Nov 02, 2020 16:46
* 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.