如何:在程式碼中開啟檔案的模型
如需 Visual Studio 2017 的最新文件請參閱 Visual Studio 2017 文件。
您可以在任何應用程式開啟 DSL 模型。
從Visual Studio延伸模組,您可以使用 ModelBus,針對此目的。 ModelBus 提供參考模型或項目在模型中,以及尋找模型,如果它已移動的標準機制。 如需詳細資訊,請參閱整合的模型,使用 Visual Studio Modelbus。
目標 Framework
設定目標 framework應用程式專案的**.NET Framework 4**。
若要設定目標 framework
開啟Visual Studio應用程式,您要讀取的 DSL 模型專案。
在方案總管 中,以滑鼠右鍵按一下專案,然後按一下屬性。
在專案屬性 視窗中,在應用程式索引標籤上,設定目標 framework欄位**.NET Framework 4**。
注意
您可能需要執行這項操作,即使您選取.NET Framework 4在專案建立對話方塊。 目標架構不應該.NET Framework 4 Client Profile。
參考
您必須加入這些參考您Visual Studio應用程式專案︰
Microsoft.VisualStudio.Modeling.Sdk.11.0
- 如果看不到這下**.NET索引標籤中加入參考**對話方塊中,按一下 [瀏覽] 索引標籤上,並瀏覽至
%Program Files%\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\
。
- 如果看不到這下**.NET索引標籤中加入參考**對話方塊中,按一下 [瀏覽] 索引標籤上,並瀏覽至
DSL 組件,您將 [bin] 資料夾下找到您的 DSL 專案。 其名稱的格式通常是︰ YourCompany。排入
.Dsl.dll
。
在 DSL 中的重要類別
您可以撰寫會讀取您的 DSL 的程式碼之前,您應該知道部分 DSL 產生之類別的名稱。 在 DSL 方案中,開啟Dsl專案,並查看GeneratedCode資料夾。 或者,按兩下專案中的 DSL 組件參考,並開啟中的 DSL 命名空間物件瀏覽器。
這些是您應該識別出的類別︰
YourDslRootClass -這是根類別中的名稱您
DslDefinition.dsl
。E
SerializationHelper
-此類別定義於SerializationHelper.cs
DSL 專案中。E
DomainModel
-此類別定義於DomainModel.cs
DSL 專案中。
從檔案讀取
下列範例被設計來讀取的 DSL 的重要類別是,如下所示︰
FamilyTreeModel
FamilyTreeSerializationHelper
FamilyTreeDomainModel
在此 DSL 的其他網域類別是人員。
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)
{ ... }