> For the complete documentation index, see [llms.txt](https://docs.spadnext.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.spadnext.com/extending-and-apis/scripting-interface/c-scripting-scriptstub.md).

# C# Scripting: ScriptStub

Starting with 0.9.18 SPAD.neXt.Interfaces contains an abstract ScriptStub which can be used for easier implementation:

```csharp
/// <summary>
/// A basic Script Stub for free use
/// </summary>
public abstract class ScriptStub : IScript, IScriptCreation
{
    /// <summary>
    /// String to prefix all datat with. Data will be available as LOCAL:[PREFIX]_[name]
    /// </summary>
    protected abstract string ScriptDataPrefix { get; }
    protected abstract void InitializeScript();
    protected abstract void DeinitializeScript();

    /// <summary>
    /// Interface to Application for this Script
    /// </summary>
    protected IApplication Application { get; private set; }
    /// <summary>
    /// Our logger for the script.
    /// </summary>
    protected ILogger ScriptLogger { get; private set; }
    protected CancellationTokenSource CancelTokenSource { get; private set; } = new CancellationTokenSource();
    protected CancellationToken CancelToken => CancelTokenSource.Token;
    
    /// <summary>
    /// The loaded SPAD.neXtprofile has changed
    /// </summary>
    protected EventHandler<IProfile, string> ProfileChanged;
    /// <summary>
    /// The active aircraft/vehicle has changed
    /// </summary>
    protected EventHandler<IAircraft, string> AircraftChanged;
    /// <summary>
    /// A flight has been started
    /// </summary>
    protected EventHandler<ISimulationInterface, IAircraft> FlightStarted;
    /// <summary>
    /// The flight ended
    /// </summary>
    protected EventHandler<ISimulationInterface, SimulationGamestate> FlightEnded;
    /// <summary>
    /// The Simulation gamestate has changed (NewState,OldState)
    /// </summary>
    protected EventHandler<ISimulationInterface,SimulationGamestate, SimulationGamestate> GameStateChanged; 

    private Dictionary<string, IDataDefinition> scriptDataValues = new Dictionary<string, IDataDefinition>(StringComparer.InvariantCultureIgnoreCase);
    public void Initialize(IApplication app)
    {
        Application = app;
        ScriptLogger = app.GetLogger("Script." + ScriptDataPrefix);
        scriptDataValues = new Dictionary<string, IDataDefinition>(StringComparer.InvariantCultureIgnoreCase);
        ScriptLogger.Debug("Initialize");
        Application.RegisterSimulationConnected(simulationConnected);
        Application.ActiveProfileChanged += (s, e) => ProfileChanged?.Invoke(Application.ActiveProfile, e.PropertyName);
        Application.AircraftChanged += (s, e) => AircraftChanged?.Invoke(Application.CurrentAircraft, e.PropertyName);
        SafeCall(() => InitializeScript());
    }

    private void simulationConnected(SimulationConfiguration sender, IValueProvider e)
    {
        if (sender != null && sender.SimulationInterface is ISimulationInterface simulationInterface)
        {
            simulationInterface.SimulationGamestateChanged -= SimulationInterface_SimulationGamestateChanged;
            simulationInterface.SimulationGamestateChanged += SimulationInterface_SimulationGamestateChanged;
        }
    }

    private void SimulationInterface_SimulationGamestateChanged(ISimulationInterface sender, SimulationGamestate newState, SimulationGamestate oldState)
    {
        SafeCall(() =>
        {
            if (newState != oldState)
            {
                if (newState == SimulationGamestate.Flying)
                {
                    FlightStarted?.Invoke(sender, Application.CurrentAircraft);
                }
                else
                {
                    FlightEnded?.Invoke(sender, newState);
                }
            }
            GameStateChanged?.Invoke(sender, oldState, newState);
        });
    }

    public void Deinitialize()
    {
        ScriptLogger.Debug("Deinitialize");
        CancelTokenSource.Cancel();
        SafeCall(() => DeinitializeScript());
        scriptDataValues?.Clear();
        scriptDataValues = null;
    }

    protected IDataDefinition GetOrCreateScriptDataValue(string name)
    {
        if (name.Contains(":"))
        {
            throw new InvalidCastException("Symbol ':' is not allowed in datanames");
        }
        var realName = "LOCAL:" + ScriptDataPrefix + "_" + name;
        if (scriptDataValues.TryGetValue(name, out var data))
            return data;
        data = EventSystem.GetDataDefinition(realName);
        scriptDataValues[name] = data;
        return data;
    }
    protected T GetScriptDataValue<T>(string name, T defaultValue = default)
    {
        var data = GetOrCreateScriptDataValue(name);
        return data.GetValueAs<T>(defaultValue);
    }
    protected void SetScriptDataValue(string name, object value)
    {
        var data = GetOrCreateScriptDataValue(name);
        if (data != null) { data.SetRawValue(value); }
    }

    private void SafeCall(Action _call)
    {
        try
        {
            _call();
        }
        catch (Exception ex)
        {
            ScriptLogger.Error(ex.ToString());
        }
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.spadnext.com/extending-and-apis/scripting-interface/c-scripting-scriptstub.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
