在我們添加到資料庫時要驗證資料是否符合我們所要求的格式。但我們又不知道有多少資料後資料驗證的方法,這樣我們舉可以用代理來完成,以達到我們的目的。在CommunityServer中的代理易於擴充,值得我們學習學習,下面我們來看看他是怎麼個執行過程。
1.CSApplication.cs:這個檔案中包含了所有代理事件,極其事件代理方法類的初始化。
1 Delegates#region Delegates
2 //Do we want one single delegate or a custom one for each type
3 //public delegate void CSEventHandler(object sender, CSEventArgs e);
4 public delegate void CSUserEventHandler(User user, CSEventArgs e);
5 public delegate void CSPostEventHandler(IContent content, CSPostEventArgs e);
6 public delegate void CSPostAttachmentEventHandler(IContent content, PostAttachment attachment, CSPostEventArgs e);
7 public delegate void CSSectionEventHandler(Section section, CSEventArgs e);
8 public delegate void CSGroupEventHandler(Group group, CSEventArgs e);
9 public delegate void CSRateEventHandler(Rating rating, CSEventArgs e);
10 public delegate void CSFavoriteEventHandler(Favorite favorite, CSEventArgs e);
11 public delegate void CSCategoryEventHandler(PostCategory category, CSEventArgs e);
12 public delegate void CSExceptionHandler(CSException csEx, CSEventArgs e);
13 public delegate void CSUserInvitationHandler(UserInvitation invitation, CSEventArgs e);
14 public delegate void CSAcceptUserInvitationHandler(UserInvitation invitation, CSAcceptUserInvitationEventArgs e);
15 #endregion
以上代理就是相對應事件的處理方法,而這些代理的方法類必須繼承ICSModule介面,以得到相對應得處理方法。在CSApplication的建構函式中我們可以看到,從設定檔中擷取"CommunityServer/csmodules"節點的資料並進行執行個體化,如果不成功將會拋出錯誤,並將得到的執行個體列表緩衝。
2.CSEventArgs.cs:這個檔案中包含了CSEventArgs,CSPostEventArgs,CSAcceptUserInvitationEventArgs事件。CSEventArgs是CommunityServer所有事件的基類,繼承於EventArgs;CAPostEventArgs是關於Post的事件,所有發布的文章或文章等所引發的事件,繼承於CSEventArgs類;CSAcceptUserInvitationEventArgs當邀請某個使用者加入會員是所引發的事件,繼承於CSEventArgs類。各個事件都包含各自的資料。
3.ICSModule.cs:這個檔案包含了ICSModule介面,只有一個方法,可以通過繼承這個介面定義事件處理方法,並在設定檔中的"CommunityServer/csmodules"節點標示,使得能夠被CSApplication類執行個體化。
4.CSEvents.cs:包含驗證的靜態方法,我們可以調用這裡的方法即可實現我們所想得到的結果。
下面我們來看一下執行的順序(比如我們要加入一個使用者):首先我們調用CSEvents.BeforeUser(User user, ObjectState state)來驗證我們的使用者資料;CSEvents.BeforeUser(User user, ObjectState state)有調用CSApplication.Instance().ExecutePreUserUpdate(user,state),從CSApplication類中文們可以知道:CSApplication.Instance()先從緩衝中搜尋CSApplication對象,如果不存在則載入設定檔中的"CommunityServer/csmodules"節點的資料並進行執行個體化,如果不成功將會拋出錯誤,並將得到的執行個體列表緩衝;初始化後我們可以知道ExecutePreUserUpdate(user,state)方法所對應的索引值在EventHandlerList處理方法中所對應的事件,因此把資料轉送給public event CSUserEventHandler PreUserUpdate事件在CSApplication中所對應的處理方法類public class CSValidationModule : ICSModule;從而得到了事件處理的方法:private void csa_PreUserUpdate(User user, CSEventArgs e),並執行。
小弟入道不久,學藝不精,如果有所錯誤,經脈逆轉,歡迎解救!