Visual Studio DSL 入門 11---為狀態機設計器添加規則
上一節我們在設計器的顯示方面進行了完善,在這一節,我們將深入狀態機設計器的一些邏輯細節,給我們的設計器添加邏輯規則.為生成代碼做好準備.
在開始之前,我們先看一下Transition的幾個屬性之間的關系:
1.編輯Event,Condition,Action屬性時,Label屬性能夠自動計算顯示,計算邏輯為Event [Condition] / Action
2.當修改屬性Label時,Event,Condition,Action的值也能夠對應自動更新.
我們使用Vs.net Dsl的規則來實現:
1.在Dsl項目下新增CustomCode文件夾來存放我們的自定義的代碼,這是Dsl開發中的通用做法,Dsl再強大也不可能不一點代碼不用寫就能夠使滿足需求,一般情況下,無論是在開發Dsl還是在使用Dsl時,都需要結合生成的代碼和自定義代碼.在CustomCode文件夾下面新建文件夾Validation,用于存放手寫的自定義驗證類.
2.在Validation文件夾下面添加類TransitionLabelRule.
3.修改TransitionLabelRule繼承于ChangeRule,并使用RuleOn屬性標簽標識此規則應用到域關系Transition上面.
-
using Microsoft.VisualStudio.Modeling; -
namespace Company.LanguageSm -
{ -
[RuleOn(typeof(Transition))]
-
public sealed class TransitionLabelRule : ChangeRule
-
{ -
}
-
}
4.在規則類里面,我們需要實現ChangeRule唯一的一個方法ElementPropertyChanged(ElementPropertyChangedEventArgs e),從這個方法我們可以看出,當Transition的一些屬性發生變化時就會觸發這個規則,參數類型ElementPropertyChangedEventArgs,這個參數包含當前的模型元素ModelElement,編輯的屬性DomainProperty,原值OldValue,新值NewValue,我們只需要判斷當前的屬性,如果是以上的Event,Condition,Action,Lable時,修改后就計算其余的屬性.
-
public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
-
{ -
Transition t = e.ModelElement as Transition;
-
// Compute Label when Event changes -
if (e.DomainProperty.Id == Transition.EventDomainPropertyId)
-
t.Label = ComputeSummary(e.NewValue as string, t.Condition, t.Action); -
// Compute Label when Condition changes -
else if (e.DomainProperty.Id == Transition.ConditionDomainPropertyId)
-
t.Label = ComputeSummary(t.Event, e.NewValue as string, t.Action); -
// Compute Label when Action changes -
else if (e.DomainProperty.Id == Transition.ActionDomainPropertyId)
-
t.Label = ComputeSummary(t.Event, t.Condition, e.NewValue as string); -
// Compute Event, Condition, Action when Label changes -
else if (e.DomainProperty.Id == Transition.LabelDomainPropertyId)
-
ComputeProperties(e.NewValue as string, t); -
}
ComputeSummary是我們的輔助方法,通過Event,Condition,Action三個值來計算Lable的值,ComputeProperties方法是由Lable的值來分別匹配出另外三個屬性的值.最后可以直接對域類的屬性進入賦值. 這兩個輔助方法就不在這里列出來了,在下載代碼里可以看到.(在這里其實是默認提交,整個規則事件就在一個事務中).
5.重新運行項目,會發現,寫的規則沒有起作用,修改Transition的屬性時,也沒有跳到TransitionLabelRule的斷點里面來,這是怎么回事呢?這其實是和Vs.net dsl 的規則機制有關,我們還需要對這個Rule進行一下注冊, 在CustomCode下面添加LanguageSmDomainModel(GeneratedCode下面的DomainModel.tt生成的類)的一個partial類,在這里類的GetCustomDomainModelTypes方法里,添加我們的自定義的Rule的集合,這樣 vs.net在加載時,就會自動加載這個Rule,并添加到Rule集合中.
-
namespace Company.LanguageSm -
{ -
public partial class LanguageSmDomainModel
-
{ -
protected override Type[] GetCustomDomainModelTypes()
-
{ -
return new Type[]{typeof(TransitionLabelRule),};
-
}
-
}
-
}
參考資源
1. Visual Stuido DSL 工具特定領域開發指南
2. DSL Tools Lab http://code.msdn.microsoft.com/DSLToolsLab 系列教程 [本系列的入門案例的主要參考]
作者:孤獨俠客(似水流年)
出處:http://lonely7345.cnblogs.com/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

浙公網安備 33010602011771號