在程序代码中从文件打开模型
可在任何应用程序中打开 DSL 模型。
从 Visual Studio 扩展中,可使用 ModelBus 来实现此目的。 ModelBus 提供了标准机制用于引用模型或模型中的元素,以及用于在模型移动后查找模型。 有关详细信息,请参阅使用 Visual Studio Modelbus 集成模型。
目标框架
将应用程序项目的“目标框架”设置为 .NET Framework 4 或更高版本。
打开要在其中读取 DSL 模型的应用程序的 Visual Studio 项目。
在解决方案资源管理器中,右键单击你的项目,再单击“属性” 。
在项目属性窗口的“应用程序”选项卡上,将“目标框架”字段设置为 .NET Framework 4(或更高版本) 。
注意
目标框架不应是 .NET Framework 4 客户端配置文件。
参考
将这些引用添加到 Visual Studio 应用程序项目:
Microsoft.VisualStudio.Modeling.Sdk.11.0
- 如果在“添加引用”对话框的“.NET”选项卡下没有看到此内容,请单击“浏览”选项卡并导航到
%Program Files%\Microsoft Visual Studio\2022\YourVSversionSKU\VSSDK\VisualStudioIntegration\Common\Assemblies
。
- 如果在“添加引用”对话框的“.NET”选项卡下没有看到此内容,请单击“浏览”选项卡并导航到
可在 DSL 项目的 bin 文件夹下找到 DSL 程序集。 其名称通常采用 YourCompany.YourProject 格式
.Dsl.dll
。
DSL 中重要的类
在编写读取 DSL 的代码之前,应知道 DSL 生成的某些类的名称。 在 DSL 解决方案中,打开 DSL 项目并查看 GeneratedCode 文件夹 。 或者,双击项目的“引用”中的 DSL 程序集,然后在对象浏览器中打开 DSL 命名空间 。
应确定以下类:
YourDslRootClass - 这是
DslDefinition.dsl
中的根类的名称。YourDslName
SerializationHelper
- 此类是在 DSL 项目的SerializationHelper.cs
中定义的。YourDslName
DomainModel
- 此类是在 DSL 项目的DomainModel.cs
中定义的。
从文件中读取
以下示例旨在读取 DSL,其中重要的类如下所示:
FamilyTreeModel
FamilyTreeSerializationHelper
FamilyTreeDomainModel
此 DSL 中的另一个域类是 Person。
using System;
using Microsoft.VisualStudio.Modeling;
using Company.FamilyTree; // Your DSL namespace
namespace StandaloneReadDslConsole
{ class Program
{ static void Main(string[] args)
{
// The path of a DSL model file:
string dslModel = @"C:\FamilyTrees\Tudor.ftree";
// Set up the Store to read your type of model:
Store store = new Store(
typeof(Company.FamilyTree.FamilyTreeDomainModel));
// The Model type generated by the DSL:
FamilyTreeModel familyTree;
// All Store changes must be in a Transaction:
using (Transaction t =
store.TransactionManager.BeginTransaction("Load model"))
{
familyTree =
FamilyTreeSerializationHelper.Instance.
LoadModel(store, dslModel, null, null, null);
t.Commit(); // Don't forget this!
}
// Now we can read the model:
foreach (Person p in familyTree.People)
{
Console.WriteLine(p.Name);
foreach (Person child in p.Children)
{
Console.WriteLine(" " + child.Name);
}
} } } }
保存到文件
向上述代码添加下列内容会更改模型,然后将其保存到文件中。
using (Transaction t =
store.TransactionManager.BeginTransaction("update model"))
{
// Create a new model element:
Person p = new Person(store);
// Set its embedding relationship:
p.FamilyTreeModel = familyTree;
// - same as: familyTree.People.Add(p);
// Set its properties:
p.Name = "Edward VI";
t.Commit(); // Don't forget this!
}
// Save the model:
try
{
SerializationResult result = new SerializationResult();
FamilyTreeSerializationHelper.Instance
.SaveModel(result, familyTree, @"C:\FamilyTrees\Tudor-upd.ftree");
// Report any error:
if (result.Failed)
{
foreach (SerializationMessage message in result)
{
Console.WriteLine(message);
}
}
}
catch (System.IO.IOException ex)
{ ... }