In 2sxc 9.13 we made it easier to create custom data sources - something that's been requested often lately. This is part 2 of 5 and shows how to create lists.
- Part 1: The most basic DataSource delivering 1 item
- Part 2: Creating lists which come from elsewhere
- Part 3: Unit Testing DataSources
- Part 4: Creating a distributable DNN package with your DataSource
- Part 5: Giving the admin a configuration UI
If you haven't read the previous parts, I recommend that you check that out first. This part builds upon that.
Creating a List DataSource
Here's the code - what a simple list DataSource can look like (full source in git here):
namespace ToSic.Tutorial.DataSource
{
// additional info so the visual query can provide the correct buttons and infos
[VisualQuery(
GlobalName = "10ebb0af-4b4e-44cb-81e3-68c3b0bb388d", // namespace or guid
NiceName = "DateTime-BasicList",
HelpLink = "https://github.com/2sic/2sxc/wiki/DotNet-DataSources-Custom"
)]
public class DateTimeDataSourceBasicList: ExternalDataDataSource
{
public const string DateFieldName = "Date";
public const string IdField = "Id";
public const int ItemsToGenerate = 7;
/// <summary>
/// Constructor to tell the system what out-streams we have
/// </summary>
public DateTimeDataSourceBasicList()
{
Provide(GetList); // default out, if accessed, will deliver GetList
}
/// <summary>
/// Get-List method, which will load/build the items once requested
/// Note that the setup is lazy-loading,
/// ...so this code will not execute unless it's really used
/// </summary>
/// <returns></returns>
private IEnumerable<IEntity> GetList()
{
var randomNumbers = new List<IEntity>();
for (var i = 0; i < ItemsToGenerate; i++)
{
var values = new Dictionary<string, object>
{
{IdField, i},
{DateFieldName, RandomDay()}
};
randomNumbers.Add(AsEntity(values, DateFieldName, id: i));
}
return randomNumbers;
}
// helper to randomly generate dates
private readonly Random _randomizer = new Random();
private readonly DateTime _start = new DateTime(1995, 1, 1);
private DateTime RandomDay()
=> _start.AddDays(_randomizer.Next((DateTime.Today - _start).Days));
}
}
This example shows:
- a basic setup analog to the basic 1-item data source with the VisualQuery attribute and the Provide in the constructor
- a GetList method which generates 7 items containing random dates
- ...which are added to a list called randomNumbers using the AsEntity command, also providing an Id just because we can.
Using it in Visual Query
If we build the DLL and add it to the bin folder, you can now use it in visual query:
If we then hit play, we can see that it generates 7 random items:
So now you can see how to create lists.
In the next part, we'll see how we can test our DataSources using unit tests with c# code.
Love from Switzerland,
iJungleboy