### Loading Test Files for Scenario Setup
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/abyss/contribute/code/backend/tests/tests-with-files.md
Example demonstrating how to use the `TestFiles` helper class to load files and configure a `TestScenario` for testing purposes.
```csharp
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using ToSic.Eav.StartupTests;
using ToSic.Sys.TestHelpers.Testing;
namespace ToSic.Eav.StartupTests.ConfigurationOverride
{
[TestClass]
public class ScenarioOverrideFancybox3
{
[TestMethod]
public void TestScenario() {
var scenario = new TestScenario(TestFiles.Get("ScenarioData\Fancybox3"));
Assert.IsNotNull(scenario);
}
}
}
```
--------------------------------
### Example Default Web API Endpoint
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/web-api/custom-web-api-files.html
An example of a file path and URL for a 'PersonController' in a default 2sxc Web API setup.
```text
File: /Portals/0/2sxc/DemoApp/api/PersonController.cs
Url: GET: /api/2sxc/auto/app/auto/api/Person/List
```
--------------------------------
### turnOn Configuration Examples
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/js-code/turn-on/specs.md
Examples demonstrating how to configure the turnOn attribute with different options.
```APIDOC
## turnOn Configuration Examples
### Description
Examples demonstrating how to configure the `turnOn` attribute with different options, including basic execution, data passing, and awaiting dependencies.
### Method
N/A (Attribute Configuration)
### Endpoint
N/A (Client-side JavaScript)
### Parameters
#### Request Body (turn-on attribute value)
- **run** (string) - Required - The JavaScript function to call once conditions are met.
- **data** (any) - Optional - Data to pass to the `run` function.
- **await** (string[]) - Optional - An array of strings representing objects on the window or functions to call to determine readiness.
- **debug** (boolean) - Optional - If true, enables console logging for debugging.
### Request Example
```html
```
### Response
N/A (Client-side execution)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Example Web API Endpoint with Edition
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/web-api/custom-web-api-files.html
An example of a file path and URL for a 'PersonController' within the 'staging' edition in an advanced 2sxc Web API setup.
```text
File: /Portals/0/2sxc/DemoApp/staging/api/PersonController.cs
Url: GET: /api/2sxc/auto/app/auto/staging/api/Person/List
```
--------------------------------
### Prefill Parameter Examples
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/basics/edit/edit-ux/toolbars/customize.md
Examples of using prefill parameters to initialize fields when creating new content items.
```text
add?contentType=Book&prefill:Title=This is nice title
```
```text
add?contentType=Book&prefill:Title=Please enter name&prefil:Author=unknown
```
--------------------------------
### Pagination Example
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/web-api/odata/index.md
Example demonstrating how to paginate results using $skip and $top query options.
```APIDOC
## GET /app/auto/data/[ContentType]
### Description
Retrieves a specific subset of data from a content type, enabling pagination.
### Method
GET
### Endpoint
`/app/auto/data/[ContentType]`
### Query Parameters
- **$orderby** (string) - Optional - Sorts the results by one or more fields. Format: `Field1 [asc|desc], Field2 [asc|desc]`.
- **$skip** (integer) - Optional - Skips a specified number of results from the beginning.
- **$top** (integer) - Optional - Limits the number of results returned.
```
--------------------------------
### Markdown Syntax Example
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/contribute/docs/edit/markdown.html
A basic example demonstrating headers, bold/italic text, and list formatting in Markdown.
```markdown
# This is a header
This is some text. You can make text **bold** or _italic_.
* This is a list
* With some items
```
--------------------------------
### SetupModel(IEntity?)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.ModelFromEntityClassic.html
Initializes the wrapper with the provided IEntity source.
```APIDOC
## SetupModel(IEntity?)
### Description
Add the contents to use for the wrapper. This is performed outside the constructor to support DI-compatible initialization.
### Parameters
#### Request Body
- **source** (IEntity) - Required - The entity source to wrap.
### Response
#### Success Response (200)
- **result** (bool) - Returns true if setup is successful, false otherwise.
```
--------------------------------
### Example: Search Results from Predefined Query
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/web-api/odata/index.html
Executes a predefined query named 'SearchResults' and filters the results to include items where the Title starts with 'Getting Started', returning specific fields.
```odata
/app/auto/query/SearchResults?$filter=startswith(Title,'Getting Started')&$orderby=Title&$select=Title,Description,Url
```
--------------------------------
### Get GUID value
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sxc.Code.ITypedRazorModel.html
Retrieves a GUID value from the data object, returning an empty GUID if not found.
```csharp
Guid Guid(string name, NoParamOrder npo = default, Guid? fallback = null, bool? required = null)
```
--------------------------------
### Basic Setup: ExampleBase Class with Dependencies
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/conventions/dependencies/index.html
This C# code demonstrates a typical base class setup using ServiceBase and a nested Dependencies class. It's designed to allow the base class to change its dependencies without affecting the constructor, promoting maintainability.
```csharp
///
/// Class inheriting from ServiceBase, which expects dependencies to be of type ExampleBase.Dependencies.
/// This is a convention which allows the base class to change its dependencies without breaking the constructor.
///
public abstract class ExampleBase: ServiceBase
{
///
/// Public ExampleBase.Dependencies which actually gets all the dependencies.
/// Must be registered in DI.
///
public class Dependencies
{
public Dependencies(ISomething something, IElse somethingElse)
: DependenciesBase(connect: [something, somethingElse]) // This will make sure the logs are connected
{
internal ISomething Something { get; } = something;
internal IElse SomethingElse { get; } = somethingElse;
}
}
///
/// The normal constructor of ExampleBase, asking for these services
///
protected ExampleBase(Dependencies services): base(services, "My.Example")
{
// You can now use Services.Something and Services.SomethingElse to access the dependencies
}
}
```
--------------------------------
### Example: Prefill Related Entity by GUID
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/basics/edit/edit-ux/toolbars/customize.html
This example demonstrates prefilling a related entity field using its GUID. IDs are not supported due to potential changes during app export/import.
```text
prefill:Category=b7c1c2e1-4896-4999-a0bc-87ddf3ce31cb
```
--------------------------------
### SetupModel Method
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.ModelOfEntityClassic.html
Initializes the model with an IEntity source.
```APIDOC
## SetupModel(IEntity? source)
### Description
Adds the contents to use for the wrapper. This is used instead of a constructor to ensure DI compatibility.
### Parameters
#### Request Body
- **source** (IEntity) - Required - The entity source to initialize the model.
### Response
#### Success Response (200)
- **result** (bool) - Returns true if the setup was successful, false otherwise.
```
--------------------------------
### Get Entity by GUID (C#)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Data.EntityListExtensions.html
Retrieves an entity from a list using its unique GUID. Returns null if an entity with the specified GUID is not found.
```csharp
public static IEntity? GetOne(this IEnumerable list, Guid guid)
```
--------------------------------
### SetupModel(IEntity?)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sxc.Data.Models.ModelFromEntity.html
Initializes the wrapper with an entity source.
```APIDOC
## SetupModel(IEntity?)
### Description
Add the contents to use for the wrapper. This is used instead of a constructor to support DI-compatible initialization.
### Parameters
- **source** (IEntity) - The entity source to wrap.
### Returns
- **bool** - True if successful, false otherwise.
```
--------------------------------
### Setup Method
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.ModelExtensions.html
A helper method to initialize data wrapping, supporting method chaining.
```APIDOC
## Setup(TWrapper, TSource?)
### Description
Helper to set up the data being wrapped, returning the wrapper for easy chaining.
### Parameters
- **wrapper** (TWrapper) - The wrapper object implementing IModelSetup.
- **source** (TSource) - The source data to be wrapped.
### Returns
- **TWrapper** - The initialized wrapper object.
```
--------------------------------
### Get Single Item by GUID
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sxc.Apps.IAppDataTyped.html
Retrieves a single item from the app using its unique GUID.
```APIDOC
## GET /api/app/data/one/{id}
### Description
Gets a single item from the app with the specified GUID.
### Method
GET
### Endpoint
`/api/app/data/one/{id}`
### Parameters
#### Path Parameters
- **id** (Guid) - Required - The unique identifier (GUID) of the item to retrieve.
#### Query Parameters
- **skipTypeCheck** (bool) - Optional - Allows retrieval even if the Content-Type of the item with the ID does not match the type specified in the parameter T. Defaults to false.
### Type Parameters
- **T** - The type to convert the retrieved item to. Usually inherits `Custom.Data.CustomItem` or `CustomModel`.
### Returns
- **T** - The requested item, converted to the specified type T, or null if not found.
### Remarks
Released in v17.03.
```
--------------------------------
### IEntity EntityGuid Property
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Data.IEntity.html
Gets the unique GUID identifier for the entity. Returns a Guid object.
```csharp
Guid EntityGuid { get; }
```
--------------------------------
### Accessing Settings and Resources
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/api-compare/settings-resources.html
Examples showing the syntax differences between dynamic, typed, and strongly typed access for settings and resources.
```csharp
Settings.Color
```
```csharp
AllSettings.String("Color")
```
```csharp
Resources.Title
```
```csharp
AllResources.String("Title")
```
```csharp
App.Settings.Color
```
```csharp
App.Settings.String("Color")
```
```csharp
App.Resources.Title
```
```csharp
App.Resources.String("Title")
```
```csharp
AllSettings.Int("Images.Content.Width")
```
--------------------------------
### DI Setup with Startup Class by Namespace
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/abyss/contribute/code/backend/tests/dependency-injection.md
This C# code defines a startup class for dependency injection. Tests within the same namespace or sub-namespaces will automatically use this DI configuration.
```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ToSic.Sys.DI.Tests.SwitchableServices
{
public class Startup
{
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services)
=> {
// Add services here
// Example:
// services.AddTransient();
});
}
}
}
```
--------------------------------
### CustomItem.Guid
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sxc.Apps.AppFileTyped.html
Gets the globally unique identifier (GUID) of the item.
```APIDOC
## CustomItem.Guid
### Description
Gets the globally unique identifier (GUID) of the item.
### Method
`Guid`
### Parameters
None
### Request Example
```json
{
"example": "Not applicable for this method"
}
```
### Response
#### Success Response (200)
- **Guid** - The GUID of the item.
#### Response Example
```json
{
"example": ""a1b2c3d4-e5f6-7890-1234-567890abcdef""
}
```
```
--------------------------------
### Example: Prefill Multiple Related Entities
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/basics/edit/edit-ux/toolbars/customize.html
This example shows how to prefill a field that accepts multiple related entities, separating their GUIDs with commas.
```text
prefill:Category=b7c1c2e1-4896-4999-a0bc-87ddf3ce31cb,91753b4d-4932-4b22-af1c-f6ac2b76c67a
```
--------------------------------
### BootCoordinator.StartUp() Method
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sys.Boot.BootCoordinator.html
Documentation for the StartUp method of the BootCoordinator class.
```APIDOC
## Method StartUp()
### Description
Initiates the startup process coordinated by the BootCoordinator.
### Method
public void StartUp()
### Endpoint
N/A (This is a class method, not an API endpoint)
### Parameters
None
### Request Body
None
### Response
#### Success Response (void)
This method does not return a value.
### Response Example
N/A
```
--------------------------------
### Get Sxc with an HTML Tag (jQuery)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/js-code/2sxc-api/basics/get-sxc.md
Example of getting the Sxc object using jQuery. Note: jQuery is not recommended for new projects.
```javascript
// the same thing in 1 line
var sxc = $2sxc($("#myApp")[0]);
```
--------------------------------
### Unit Test with DI Setup by Attribute
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/abyss/contribute/code/backend/tests/dependency-injection.md
This C# code shows how to specify a custom DI setup for a test class using the `Startup` attribute. This is the preferred method for DI configuration in tests.
```csharp
using Xunit;
using ToSic.Eav.Data;
using ToSic.Eav.Services;
// Assuming StartupTestsEavCore is a class that configures services
// [Startup(typeof(StartupTestsEavCore))]
public class LookUpEngineTests
{
// Constructor injection for DataBuilder
public LookUpEngineTests(DataBuilder dataBuilder)
{
// Use dataBuilder for test setup or assertions
}
// Test methods would go here
}
```
--------------------------------
### Get Sxc with an HTML Tag (JavaScript)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/js-code/2sxc-api/basics/get-sxc.md
Obtain the Sxc object by passing a DOM element. This example shows getting an element by ID and then initializing Sxc.
```javascript
var x = document.getElementById("myApp"); // get a dom element inside this 2sxc app
var sxc1 = $2sxc(x); // use it
// the same thing in 1 line
var sxc2 = $2sxc(document.getElementById("myApp"));
```
--------------------------------
### Setup Method Definition
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sys.Services.IServiceWithSetup-1.html
The method used to apply configuration options to the service.
```csharp
void Setup(TOptions options)
```
--------------------------------
### Manual Unit Test Instantiation
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/contribute/code/backend/tests/dependency-injection.html
Example of a unit test that does not require any Dependency Injection setup.
```csharp
public void ManualListOfFunctions()
{
var result = new FunFactString(null,
[
("", _ => "Hello"),
("", s => s + " World"),
("", s => s + "!")
])
.CreateResult();
Equal("Hello World!", result);
}
```
--------------------------------
### Toolbar Command Examples
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/basics/edit/edit-ux/toolbars/customize.md
Demonstrates specific commands for setting toolbar templates and configurations. 'toolbar=default' loads all standard buttons, while 'toolbar=empty' loads an empty toolbar.
```plaintext
toolbar=default
```
```plaintext
toolbar=empty
```
--------------------------------
### Example: Prefill Title and Author for New Book
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/basics/edit/edit-ux/toolbars/customize.html
This example shows how to prefill the 'Title' and 'Author' fields when creating a new book. Prefill parameters start with 'prefill:' followed by the field name.
```text
add?contentType=Book&prefill:Title=This is nice title
```
--------------------------------
### Toolbar Settings Examples
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/basics/edit/edit-ux/toolbars/customize.md
Shows examples of build parameters for toolbar settings, such as changing button color, hover behavior, adding CSS classes, and controlling the auto-add behavior for more buttons.
```plaintext
&color=red
```
```plaintext
&hover=left
```
```plaintext
&class=my-class
```
```plaintext
&autoAddMore=auto
```
```plaintext
&autoAddMore=end
```
```plaintext
&autoAddMore=start
```
```plaintext
&autoAddMore=never
```
--------------------------------
### Toolbar Build Instruction Syntax Examples
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/basics/edit/edit-ux/toolbars/customize.md
Illustrates various build instructions for customizing toolbars, including adding, removing, modifying buttons, and creating button groups. Comments are also shown.
```plaintext
"toolbar=empty"
```
```plaintext
"new?contentType=Person"
```
```plaintext
"edit?entityId=5593"
```
```plaintext
"/this is just a comment"
```
```plaintext
"new"
```
```plaintext
"+new"
```
```plaintext
"-edit"
```
```plaintext
"%delete&show=true"
```
```plaintext
"group=my-group"
```
```plaintext
"+group=my-group"
```
```plaintext
"+group=my-group&pos=2"
```
```plaintext
"new-quote=new?contentType=Quote"
```
```plaintext
"%more&color=red"
```
--------------------------------
### GetSource()
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sxc.Services.IDataService.html
Creates a DataSource object using its type. This is the preferred method for getting DataSources starting from v15.06+.
```APIDOC
## POST /api/datasets/typed
### Description
Creates a DataSource object using its type. This is the new, preferred way to get DataSources in v15.06+.
### Method
POST
### Endpoint
/api/datasets/typed
### Parameters
#### Query Parameters
- **npo** (NoParamOrder) - Optional - See [Convention: Named Parameters](../../net-code/conventions/named-parameters.html)
- **attach** (IDataSourceLinkable) - Optional - Link to one or more other DataSources / streams to attach upon creation.
- **parameters** (object) - Optional - Parameters to use - as anonymous object like `new { Count = 7, Filter = 3 }`
- **options** (object) - Optional - Options how to build/construct the DataSource.
### Type Parameters
- **T** - The type of DataSource, usually from [ToSic.Eav.DataSources](ToSic.Eav.DataSources.html) or [ToSic.Sxc.DataSources](ToSic.Sxc.DataSources.html)
### Response
#### Success Response (200)
- **T** - The created DataSource object of type T.
#### Response Example
{
"example": "DataSource object of type T"
}
```
--------------------------------
### Loose TOC Structure Example
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/abyss/contribute/docs/edit/docfx-toc.md
Demonstrates a non-hierarchical TOC setup where multiple files reference the same index.
```yaml
- name: Home
href: index.md
- name: Abyss
href: abyss/index.md
- name: Guides
items:
- name: Guide 1
href: guide1.md
- name: Guide 2
href: guide2.md
```
```yaml
- name: Abyss
href: index.md
- name: Something in the Abyss
href: something.md
```
--------------------------------
### Method: SetupModel
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.IModelSetup-1.html
Initializes the wrapper with the provided data source. This method is used instead of a constructor to support DI-compatible object creation.
```APIDOC
## SetupModel(TSource? source)
### Description
Adds the contents to use for the wrapper. This is typically used for custom data classes that wrap an entity.
### Parameters
- **source** (TSource) - The data source to be wrapped. Must be IEntity or ITypedItem.
### Returns
- **bool** - Returns true if the setup was successful, false otherwise.
```
--------------------------------
### Data API Endpoint (v13+)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/web-api/specs/url-schema.md
Starting with 2sxc v13, the data API follows this structure. Ensure you have the correct version for your installation.
```URL
.../app/.../data/TYPENAME
```
--------------------------------
### SetupModel Method for ModelFromEntityClassic
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.ModelFromEntityClassic.html
Adds content to be used for the wrapper. This method is not in the constructor to allow for empty or DI-compatible constructors. It returns true if setup is successful, false otherwise.
```csharp
public bool SetupModel(IEntity? source)
```
--------------------------------
### Get All and Get One with Strong Typing
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/api-typed-strong/app-data-typed.html
Use `GetAll()` to retrieve all items of a specific type and `GetOne(id)` to fetch a single item by its integer ID or GUID. These methods automatically map to the corresponding data stream based on the class name.
```csharp
var people = App.Data.GetAll();
```
```csharp
var person72 = App.Data.GetOne(72);
```
```csharp
var personFromGuid = App.Data.GetOne(Guid.Parse("..."));
```
--------------------------------
### Configuration Attribute Examples
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/data-sources/custom/configuration-attribute.html
Demonstrates applying the Configuration attribute to properties for external configuration. Includes examples with and without fallback values.
```csharp
///
/// Should the Modified date be included in serialization
///
[Configuration]
public string IncludeModified => Configuration.GetThis();
///
/// Should the Relationships be included as CSV like "42,27,999".
/// Default is `false` in which case they are sub-objects.
///
[Configuration(Fallback = false)]
public string IncludeRelationshipsAsCsv => Configuration.GetThis();
///
/// Will filter duplicate hits from the result.
///
[Configuration(Fallback = true)]
public bool FilterDuplicates => Configuration.GetThis(true);
```
--------------------------------
### Set Add-On Type
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/contribute/tutorials/create-tab.html
Select this type to instruct the tutorial system to load and display the source code of the specified file.
```text
file source (any file)
```
--------------------------------
### Lax Content Security Policy Example
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/abyss/security/csp/guide.md
A permissive CSP configuration allowing broad access to resources, often used as a starting point for the Lax-First method.
```text
default-src * data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval' 'unsafe-dynamic' ;
script-src * data: blob: 'unsafe-inline' 'unsafe-eval' ;
connect-src * data: blob: 'unsafe-inline' ;
img-src * data: blob: 'unsafe-inline' ;
frame-src * data: blob: ;
style-src * data: blob: 'unsafe-inline' ;
font-src * data: blob: 'unsafe-inline' ;
frame-ancestors * data: blob: 'unsafe-inline' ;
```
--------------------------------
### Configure EAV Startup in Startup.cs
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/abyss/integration/scenario-01.md
Initializes the EAV system by setting the connection string, global folder path, and triggering the SystemLoader startup.
```c#
///
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
///
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ----- Start EAV stuff #2sxcIntegration -----
var serviceProvider = app.ApplicationServices;
// Set Connection String
serviceProvider.Build().ConnectionString = _connStringFromConfig;
// Set global path where it will find the .data folder
var globalConfig = serviceProvider.Build();
globalConfig.GlobalFolder = Path.Combine(env.ContentRootPath, "sys-2sxc");
// Trigger start where the data etc. will be loaded & initialized
serviceProvider.Build().StartUp();
// ----- End EAV stuff #2sxcIntegration -----
// ...
}
```
--------------------------------
### Access Parent Item with TypeItem.Parent
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/releases/history/v16/_all.html
Example of using the new `.Parent(...)` method on `TypeItem` to access parent data, including the option to get the current item if `current: true` is specified.
```csharp
.Parent(current: true)
```
--------------------------------
### Implement SetupModel Method
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.IModelSetup-1.html
The SetupModel method is part of the IModelSetup interface. It is used to add the contents for the wrapper. It returns a boolean indicating success or failure, for example, if the wrapper cannot function without a source.
```csharp
bool SetupModel(TSource? source)
```
--------------------------------
### Example: Latest Published Blog Posts with Title Filter
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/web-api/odata/index.html
Retrieves the 5 most recent blog posts that are marked for display on the start page and contain '2sxc' in their title, returning only specific fields.
```odata
/app/auto/data/BlogPost?$filter=ShowOnStartPage eq true and contains(Title,'2sxc')&$orderby=Created desc&$top=5&$select=Title,Created,UrlKey
```
--------------------------------
### Configure 2sxc Services in Oqtane Startup
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/integration/scenario-future-wip.html
Registers essential 2sxc and EAV services within the IServiceCollection. Only include the specific services required by your implementation to minimize overhead.
```csharp
public void ConfigureServices(IServiceCollection services)
{
// 1. Initial code to do things not related to EAV/2sxc
// ...
// 2. Register all 2sxc services
services
.AddSxcOqtane() // Always first add your override services
.AddSxcRazor() // this is the .net core Razor compiler
.AddAdamWebApi() // This is used to enable ADAM WebAPIs
.AddSxcWebApi() // This adds all the standard backend services for WebAPIs to work
.AddSxcCore() // Core 2sxc services
.AddEav() // Core EAV services
.AddOqtWebApis() // Oqtane App WebAPI stuff
.AddRazorBlade(); // RazorBlade helpers for Razor in the edition used by Oqtane
// 3. Other stuff in your Configure Services
// ...
}
```
--------------------------------
### Retrieve, Create, Update, or Delete a Specific Item
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/web-api/specs/url-schema.html
Access a specific item by its ID or GUID using HTTP GET, POST, or DELETE. POST can be used for both creation and updates. Permissions must be configured.
```plaintext
.../data/[your-content-type]/[item-id]
```
--------------------------------
### Generate BlogPost Auto-Generated C# Class
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/net-code/copilot/data-model-generator.md
This is an example of an auto-generated C# class for a 'BlogPost' content type. It includes comments guiding users on how to extend it with a partial class and provides accessors for common properties.
```csharp
// DO NOT MODIFY THIS FILE - IT IS AUTO-GENERATED
// See also: https://go.2sxc.org/hotbuild-autogen
// To extend it, create a "BlogPost.cs" with this contents:
/*
namespace AppCode.Data
{
public partial class BlogPost
{
// Add your own properties and methods here
}
}
*/
// Generator: DataModelGenerator v17.01.08
// User: 2sichost
// Edition: /staging
// When: 2024-01-31 17:59:00
namespace AppCode.Data
{
// This is a generated class for BlogPost
// If you wish to modify it, create a partial class for "BlogPost" in a separate "BlogPost.cs" file.
///
/// BlogPost Data.
/// Default properties such as ".Title" or ".Id" are provided in the base class.
/// Most properties have a simple access, such as ".TermsAndGdprCombined".
/// For other properties or uses, the common method such as
/// `IsNotEmpty("FieldName")`, `String("FieldName")`, `Children(...)`, `Picture(...)`, ".Html(...)` and more can be used.
///
public partial class BlogPost: AppCode.Data.AutoGen.ZagBlogPostAutoGenerated
{
}
}
namespace AppCode.Data.AutoGen
{
///
/// Auto-Generated base class for BlogPost.
///
public abstract class ZagBlogPostAutoGenerated : Custom.Data.Item16
{
public bool TermsAndGdprCombined => Bool("TermsAndGdprCombined");
public bool TermsEnabled => Bool("TermsEnabled");
public bool GdprEnabled => Bool("GdprEnabled");
public string Description => String("Description", fallback: "");
public string Link => Url("Link");
public ToSic.Sxc.Adam.IFile LinkFile => File("File");
public ToSic.Sxc.Adam.IFolder LinkFolder => Folder("Folder");
}
}
```
--------------------------------
### ServiceWithSetup Class Overview
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Sys.Services.ServiceWithSetup-1.html
Details regarding the internal ServiceWithSetup class, its constructors, and methods for managing service options.
```APIDOC
## Class: ServiceWithSetup
### Description
An internal abstract base class for services that require configuration options. Note: This is an internal API and should not be used in custom code as it is subject to change.
### Constructors
- **ServiceWithSetup(string logName, NoParamOrder protect, object[] connect)** - Initializes a new instance of the service.
### Properties
- **Options** (TOptions) - Read-only property providing the current options for the service.
### Methods
- **Setup(TOptions options)** - Configures the service with the provided options.
- **GetDefaultOptions()** (TOptions) - Returns the default options for the service. Can be overridden to provide custom defaults.
```
--------------------------------
### Get Sxc Object from DOM Element (Inline JS)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/js-code/2sxc-api/index.md
This example demonstrates how to retrieve the Sxc object by passing an HTML element (like an anchor tag) to the $2sxc function, useful for event handlers.
```javascript
alert($2sxc(this))
```
--------------------------------
### Getting and Using the Query Service
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/js/SxcQuery.html
Demonstrates how to obtain an instance of the Query Service for a specific query and then use its methods like getAll.
```APIDOC
## Get a Query Service
### Description
Get the Sxc Instance of the current module and then call `.query(queryName)` to get the service for a specific query.
### Example
```javascript
const modId = @CmsContext.Module.Id;
const sxc = $2sxc(modId);
const authorsSvc = sxc.query('BlogPosts');
authorsSvc.getAll().then(data => console.log(data));
```
### Query Service Factory Parameters
The `query(...)` factory takes one parameter: the `queryName`. The returned service will perform actions for this specified query.
### Query Service APIs
Query Services always return a [modern Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing data. The service has the following commands:
* `getAll()` - No parameters. Returns an object with all streams, each containing an array of data.
* `getAll(urlParams)` - Same as above but with URL parameters as a string or object.
* `getAll(urlParams, data)` - Same as above but with POST data.
* `getStream(streamName)` - Retrieves a single stream by its name.
* `getStream(streamName, urlParams)` - Retrieves a single stream with additional URL parameters.
* `getStream(streamName, urlParams, data)` - Retrieves a single stream with URL parameters and POST data.
* `getStreams(streamNames)` - Retrieves multiple streams by their names (comma-separated string).
* `getStreams(streamNames, urlParams)` - Retrieves multiple streams with additional URL parameters.
* `getStreams(streamNames, urlParams, data)` - Retrieves multiple streams with URL parameters and POST data.
### Returned Data Structure
`getAll` and `getStreams` return an object with stream names as keys and arrays of items as values:
```json
{
"Default": [
{ ... },
{ ... }
],
"NextStreamName": [
{ ... },
{ ... }
]
}
```
`getStream` returns an array of items for the specified stream:
```json
[
{ ... },
{ ... }
]
```
```
--------------------------------
### Razor Example: Dynamic Object Method Call (Valid)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/errors/cannot-perform-runtime-binding-on-a-null-reference.html
Demonstrates a valid method call on a dynamic object 'Settings' in a Razor environment (e.g., Razor14). This code works because the 'Get' method exists.
```csharp
// Settings is a dynamic object in Razor14 or similar
// This works, because the method "Get(...)" exists
Settings.Get("SomeSetting");
```
--------------------------------
### StartupEavCore - AddAllLibAndSys
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Run.Startup.StartupEavCore.html
Adds all necessary EAV Core, Lib, and Sys services to the IServiceCollection. This is an internal API and should not be used directly.
```APIDOC
## AddAllLibAndSys(IServiceCollection)
### Description
Adds all necessary EAV Core, Lib, and Sys services to the IServiceCollection.
### Method
POST
### Endpoint
/api/startup/eav/core/addAllLibAndSys
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **services** (IServiceCollection) - Required - The service collection to add services to.
### Request Example
```json
{
"services": "Microsoft.Extensions.DependencyInjection.IServiceCollection"
}
```
### Response
#### Success Response (200)
- **services** (IServiceCollection) - The modified service collection.
#### Response Example
```json
{
"services": "Microsoft.Extensions.DependencyInjection.IServiceCollection"
}
```
```
--------------------------------
### Setup Method for ModelExtensions
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/dot-net/ToSic.Eav.Models.ModelExtensions.html
This is a helper method to set up data being wrapped and returns the wrapper for chaining. It's an internal API and should not be used directly.
```csharp
[InternalApi_DoNotUse_MayChangeWithoutNotice]
public static class ModelExtensions
public static TWrapper? Setup(this TWrapper wrapper, TSource? source) where TWrapper : IModelSetup where TSource : class
```
--------------------------------
### Fixing SexyContent.Interfaces.IApp Removal
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/releases/history/v17/_brc17-planned.html
This example shows how to update code that previously used the deprecated SexyContent.Interfaces.IApp namespace. It demonstrates accessing application configuration properties using the current App object and the Get method.
```csharp
using SexyContent.Interfaces;
IApp app = App;
var version = app.Configuration.Version;
```
```csharp
var app = App;
var version = App.Configuration.Get("Version");
```
--------------------------------
### Run 'new' CMS Command with Instance API
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/js-code/commands/index.html
Example of using the instance-specific `$2sxc(tag).cms.run` method to create a new 'Project' entity. It demonstrates handling the returned promise to show a confirmation message.
```javascript
function addProject(tag) {
$2sxc(tag).cms.run({ action: "new", params: { contentType: "Project"} })
.then(function () {
alert("Thanks - we'll review your entry and publish it.")
});
}
```
--------------------------------
### Get Stream of Business Units with data.content$() - Full Component
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/js-code/angular/dnn-sxc-angular/data-content-dollar.md
This is a full component example demonstrating how to inject the Data service and use data.content$() to fetch a stream of BusinessUnit objects. The stream is then assigned to a component property.
```typescript
@Component({ /* ... */ })
export class BusinessUnitSelectorComponent {
/** Stream of business units, provided back the backend */
businessUnits$: Observable;
constructor(private data: Data) {
// Query backend for stream of BusinessUnit[]
// #ExampleData
this.businessUnits$ = data.content$('BusinessUnit');
}
}
```
--------------------------------
### turnOn with Awaiting Multiple Dependencies
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/js-code/turn-on/specs.html
Specify an array of dependencies in the 'await' property. The 'run' function will execute only after all listed dependencies are available.
```html
```
--------------------------------
### Basic Razor Template Example
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/net-code/razor/index.html
A simple Razor template that iterates over a list of persons from App.Data and displays their names in an unordered list. Ensure your Razor file starts with `@inherits Custom.Hybrid.Razor12` to use the latest features.
```cshtml
@inherits Custom.Hybrid.Razor12
@foreach(var person in AsList(App.Data["Persons"])) {
- @person.Name
}
```
--------------------------------
### Working with REST / HTTP Async Stuff
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/api/js/ZzzSxcWebApiDeprecated.html
This section details how to use the $2sxc(...).webApi object for asynchronous HTTP requests using jQuery promises. It covers the available commands: get, post, delete, and put, along with their parameters and usage examples.
```APIDOC
## Working with REST / HTTP Async Stuff
These WebAPIs work using jQuery promises, supporting `.then(...)`, `.error(...)`, etc.
The `$2sxc(...).webApi` object provides the following commands:
* `.webApi.get(url, ...)`
* `.webApi.post(url, ...)`
* `.webApi.delete(url, ...)`
* `.webApi.put(url, ...)`
Each command accepts the following parameters:
1. `url` or `settings` (string | object) - Required: The URL for the endpoint or a settings object.
2. `params` (object) - Optional: URL parameters (e.g., `{ id: 27, name: "hello" }`).
3. `data` (object) - Optional: Data for POST/PUT requests (e.g., `{ ... }`).
4. `preventAutoFail` (boolean) - Optional: If true, prevents automatic error message display, allowing custom error handling.
### Request Example
```javascript
var sxc = $2sxc(27);
sxc.webApi.post("Form/ProcessForm", {}, data, true)
.success(function() {
// ...
})
.error(function() {
// ...
});
```
This example calls the `FormController`'s `ProcessForm` command in the `api` folder, using no URL parameters but providing a `data` object in the body and custom error handling.
```
--------------------------------
### Basic Custom DataSource Example
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/extensions/app-extensions/create/app-code/datasources.html
A simple C# DataSource that inherits from DataSource16 and provides a single 'Hello World' message. Ensure the namespace matches your extension's structure and always call the base constructor.
```csharp
using Custom.DataSource;
namespace AppCode.Extensions.HelloWorld
{
///
/// Simple DataSource example that returns a single "Hello World" message.
///
public class HelloWorldDataSource : DataSource16
{
///
/// Constructor receives dependencies from the 2sxc/Custom framework.
/// Always call base(services) to properly initialize the DataSource.
///
/// Injected services from 2sxc / Custom.DataSource
public HelloWorldDataSource(Dependencies services) : base(services)
{
// Register the output function of this DataSource.
ProvideOut(GetData);
}
///
/// Function that returns the data from this DataSource.
///
private object GetData()
{
return new
{
// This is the actual content that will be available in Razor
Message = "Hello from my DataSource"
};
}
}
}
```
--------------------------------
### Export/Import Data Format Example (XML)
Source: https://github.com/2sic/2sxc-docs/blob/master/docs/abyss/data-formats/xml/table/index.html
This XML structure represents data entities for export and import, suitable for mass editing in tools like Excel. Each 'Entity' tag defines a data item with its properties, including GUID, language, and specific fields.
```xml
9e751a94-4335-48fa-b1f8-44ca97a06ab8
en-US
AHV de
30
5543
de
AHV
9e751a94-4335-48fa-b1f8-44ca97a06ab8
fr-FR
AVS de
[]
[]
[]
AVS
9e751a94-4335-48fa-b1f8-44ca97a06ab8
it-IT
AVS de
[]
[]
[]
AVS
```
--------------------------------
### turnOn Configuration for Map Initialization
Source: https://github.com/2sic/2sxc-docs/blob/master/docs-src/pages/js-code/turn-on/index.md
This example shows how to use turnOn to initialize a map with specific configuration data. It includes dynamic values for map ID, coordinates, zoom level, and company information, and conditionally shows a warning.
```html
```