オブジェクトアクセスの基礎
エクステンション開発でよく利用するオブジェクトやプロパティへのアクセス方法について説明します。
コマンドやイベントハンドラでのアクセス
コマンドやイベントではICommandContextやIEventContextのAppプロパティを用いてアクセスできます。
protected void SomeCommand(ICommandContext c,ICommandParams p)
{
    //アプリケーション
    var app = c.App;
    
    //ワークスペース(プロジェクトファイル操作)
    var workspace = c.App.Workspace;
    //現在のプロジェクト
    var currentProject = workspace.CurrentProject;
    //現在のモデル
    var currentModel = workspace.CurrentModel;
    //メタモデル
    var metamodels = currentProject.Profile.Metamodels;
    //ファイルを開くダイアログなどの標準UI
    var ui = app.Window.UI;
}
次のように実装できます。
public void SomeCommand(ICommandContext c,ICommandParams p)
{
    //プロジェクトファイルのパスを取得します
    var projectFilePath = c.App.Workspace.CurrentProject.ModelUnit.AbsolutePath;
    c.App.Output.WriteLine("sample",projectFilePath);
}
エクステンション(IExtension)でのアクセス
エクステンションのActivate/Deactivate実装では、IContextのAppプロパティでアプリケーションオブジェクトにアクセスできます。
public  class MyExtension : IExtension
{
    public void Activate(IContext context)
    {
        //アプリケーション
        var app = context.App;
        //ワークスペース(プロジェクトファイル操作)
        var workspace = context.App.Workspace;
        //...
    }
    public void Deactivate(IContext context)
    {
    }
}
DLLとスクリプトでのアクセス方法の違い
スクリプトのエクステンションではあらかじめ次のようなグローバルな変数が定義されています。
- App
- CurrentProject
- CurrentModel
- UI
- Output
- Workspace
- など
従ってDLLで次のように実装している場合、
//コマンドハンドラ
public void SayHello(ICommandContext c,ICommandParams p)
{
    //"App"に直接アクセスできます
    c.App.Window.UI.ShowInformationDialog("Hello !","Hello World");
    //現在のプロジェクト
    var project = c.App.Workspace.CurrentProject;
}
スクリプトではICommandContextを用いずにアクセスできます。
//コマンドハンドラ
public void SayHello(ICommandContext c,ICommandParams p)
{
    //"App"に直接アクセスできます
    App.Window.UI.ShowInformationDialog("Hello !","Hello World");
    //"CurrentProject"で現在のプロジェクト
    var project = CurrentProject;
}
詳しくはスクリプトで開発する > グローバルオブジェクトを参照して下さい。
ExtensionPointsライブラリからのアクセス
ExtensionPoitsライブラリを利用した場合は、次のようにコマンド、イベントハンドラ内でAppやOutputといったプロパティにアクセスできるため、よりシンプルでスクリプトに近い実装が可能です。ICommandContextやIEventContextプロパティを用いる場合はほぼなくなります。
public class HelloCommand : CommandHandlerBase
{
    ///<summary>
    ///コマンドの実行
    ///</summary>
    ///<param name="c"></param>
    ///<param name="p"></param>
    protected override void OnExecute(ICommandContext c, ICommandParams p)
    {
        //"CurrentProject"プロパティでアクセスできます
        if ( CurrentProject != null)
        {
            Output.WriteLine(ExtensionName, $"ProjectName : {CurrentProject.Name}");
        } else
        {
            Output.WriteLine(ExtensionName,$"Project is not opened");
        }
        //"App"プロパティでIApplicationにアクセスできます
        //アクティブにします
        App.Window.IsInformationPaneVisible = true;
        App.Window.CurrentOutputCategory = ExtensionName;
        App.Window.ActiveInfoWindow = "Output";
    }
}
アクセスできるプロパティの例
- App
- CurrentProject
- CurrentModel
- CurrentEditor
- UI
- Output
- Workspace
- Window
- など
詳しくはExtensionPoints > コマンドハンドラの実装を参照して下さい。