Create Custom DataSources
If you want to create your own DataSource and use it in C# or the VisualQuery designer, this is for you.
Simple Example
Here's an example of a complete data-source, which just delivers 1 item with the current date:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ToSic.Eav.Data;
using ToSic.Eav.DataSources;
using ToSic.Eav.DataSources.Queries;
namespace ToSic.Tutorial.DataSource.Basic
{
// Additional info so the VisualQuery can provide the correct buttons and infos
[VisualQuery(
NiceName = "Demo DateTime Basic",
GlobalName = "7aee541c-7188-429f-a4bb-2663a576b19e" // random & unique Guid
)]
public class DateTimeDataSourceBasic: ExternalData
{
public const string DateFieldName = "Date";
/// <summary>
/// Constructor to tell the system what out-streams we have
/// </summary>
public DateTimeDataSourceBasic()
{
Provide(GetList); // "Default" out; when 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 only execute when used
/// </summary>
private ImmutableArray<IEntity> GetList()
{
var date = DateTime.Now;
var values = new Dictionary<string, object>
{
{DateFieldName, date},
{"Weekday", date.DayOfWeek},
{"DayOfWeek", (int) date.DayOfWeek}
};
// Construct the IEntity and return as ImmutableArray
var entity = DataBuilder.Entity(values, titleField: DateFieldName);
return new [] {entity}.ToImmutableArray();
}
}
}
This code demonstrates:
- The VisualQuery attribute, so that this data-source will be shown in VisualQuery
- The constructor
DateTimeDataSourceBasic()
, which tells the source what Out-streams it has using Provide, in this case it's just theDefault
- A method
GetList()
which gets the items if ever requested - The
DataBuilder.Entity(...)
helper to construct IEntity objects from value-dictionaries
Use in VisualQuery Designer
This is what the DataSource would appear like in VisualQuery
...and this is what the test-run would look like
Demo App and further links
- DataSource API: VisualQuery Attribute
- DataSource API: Provide(...)
- DataSource API: DataBuilder.Entity(...)
- Basic DataSources for EAV and 2sxc
- Blog about this feature
- Blog post about custom DataSources
History
- Introduced in 2sxc ca. 4 but with a difficult API
- API strongly enhanced and simplifield in 2sxc 09.13
- Another API rework ca. 2sxc 10.25 (but we're not exactly sure)