天天看點

新瓶舊酒ASP.NET AJAX(10) - 用戶端腳本程式設計(Sys.Services命名空間下的類)

新瓶舊酒ASP.NET AJAX(10) - 用戶端腳本程式設計(Sys.Services命名空間下的類)

介紹

ASP.NET AJAX的Sys.Services.AuthenticationService類、Sys.Services.ProfileService類、Sys.Services.ProfileGroup類完美地和ASP.NET 2.0的Membership和Profile進行了內建

關鍵

1、Sys.Services.AuthenticationService類的login()方法

    Sys.Services.AuthenticationService.login(userName, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext);

    ·userName - 使用者名

    ·password - 密碼

    ·isPersistent - 是否跨浏覽器儲存認證資訊(持久保留)

    ·customInfo - 保留字段,可能在将來使用

    ·redirectUrl - 登入成功後重定向到的URL

    ·loginCompletedCallback - 登入成功後的回調函數

    ·failedCallback - 登入失敗後的回調函數

    ·userContext - 使用者上下文

    WebService中與其對應的方法 - public bool Login()

2、登入成功後的回調函數

    function LoginComplete(bool validCredentials, userContext, methodName)

    ·validCredentials - 是否成功通過了驗證

    ·methodName - 調用的方法名

3、Sys.Services.AuthenticationService類的logout()方法

    Sys.Services.AuthenticationService.logout(redirectUrl, logoutCompletedCallback, failedCallback, userContext);

    ·redirectUrl - 登出成功後重定向到的URL

    ·logoutCompletedCallback - 登出成功後的回調函數

    ·failedCallback - 登出失敗後的回調函數

    WebService中與其對應的方法 - public void Logout()

4、登出成功後的回調函數

    function LogoutComplete(result, userContext, methodName)

    ·result - 保留字段,可能在将來使用,始終為null

5、Sys.Services.AuthenticationService類的屬性

    ·defaultLoginCompletedCallback - 登入成功後的回調函數

    ·defaultLogoutCompletedCallback - 登出成功後的回調函數

    ·defaultFailedCallback - 登入或登出失敗後的回調函數

    ·isLoggedIn - 目前使用者是否已經登入

    ·path - authentication service路徑

    ·timeout - 逾時時間

6、Sys.Services.ProfileService類的load()方法

    Sys.Services.ProfileService.load(propertyNames, loadCompletedCallback, failedCallback, userContext);

    ·propertyNames - Profile屬性名稱數組

    ·loadCompletedCallback - 成功後的回調函數

    ·failedCallback - 失敗後的回調函數

    WebService中與其對應的方法 - public IDictionary<string, object> GetAllPropertiesForCurrentUser()和public IDictionary<string, object> GetPropertiesForCurrentUser(string[] properties)

7、讀取Profile成功後的回調函數

    function onLoadCompleted(numProperties, userContext, methodName)

    ·numProperties - 傳回的Profile屬性個數

8、Sys.Services.ProfileService類的save()方法

    Sys.Services.ProfileService.load(propertyNames, saveCompletedCallback, failedCallback, userContext);

    ·saveCompletedCallback - 成功後的回調函數

    ·WebService中與其對應的方法 - public int SetPropertiesForCurrentUser(IDictionary<string, object> values)

9、儲存Profile成功後的回調函數

    onSaveCompleted(numProperties, userContext, methodName)

    ·numProperties - 儲存的Profile屬性個數

10、Sys.Services.ProfileService類的屬性

    ·讀取或設定某個Profile的屬性要這麼寫 - Sys.Services.ProfileService.properties.FieldName; 

    ·defaultLoadCompletedCallback - 讀取Profile成功後的回調函數

    ·defaultSaveCompletedCallback - 儲存Profile成功後的回調函數

    ·defaultFailedCallback - 讀取或儲存Profile失敗後的回調函數

    ·path - profile service路徑

11、Sys.Services.ProfileGroup類

    ·定義一個Profile組(同時需要在Web.config中定義)

12、登入或登出失敗、讀取或儲存Profile失敗後的回調函數

    function onFailed(error, userContext, methodName)

    ·error - Sys.Net.WebServiceError對象

13、如果要自動調用相關服務的話,則需要在web.config中的<configuration />節點下增加類似如下的配置

<webServices> 

        <authenticationService enabled="true" requireSSL="false"/> 

        <profileService enabled="true"    

                readAccessProperties="Age, Salary" 

                writeAccessProperties="Age, Salary"    

        /> 

</webServices>

示例

AuthenticationService.asmx

<%@ WebService Language="C#" Class="AuthenticationService" %> 

using System; 

using System.Web; 

using System.Web.Services; 

using System.Web.Services.Protocols; 

using System.Web.Script.Services; 

[WebService(Namespace = "http://tempuri.org/")] 

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 

[ScriptService] 

public class AuthenticationService : System.Web.Services.WebService 

        /// <summary> 

        /// 登入 

        /// </summary> 

        /// <param name="userName">使用者名</param> 

        /// <param name="password">密碼</param> 

        /// <param name="createPersistentCookie">是否跨浏覽器儲存認證資訊(持久保留)</param> 

        /// <returns></returns> 

        [WebMethod] 

        public bool Login(string userName, string password, bool createPersistentCookie) 

        { 

                //Place code here. 

                System.Web.Security.FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 

                return true; 

        } 

        /// 登出 

        public void Logout() 

}

ProfileService.asmx

<%@ WebService Language="C#" Class="ProfileService" %> 

using System.Collections.Generic; 

public class ProfileService : System.Web.Services.WebService 

        /// 擷取使用者的全部Profile 

        public IDictionary<string, object> GetAllPropertiesForCurrentUser() 

                Dictionary<string, object> dic = new Dictionary<string, object>(); 

                dic.Add("Age", 27); 

                dic.Add("Salary", 100); 

                Article article = new Article(); 

                article.Title = "Article Title From Server"; 

                article.PublishTime = DateTime.Now; 

                dic.Add("Article", article); 

                return dic; 

        /// 擷取使用者的指定的Profile 

        /// <param name="properties">屬性名稱數組</param> 

        public IDictionary<string, object> GetPropertiesForCurrentUser(string[] properties) 

                return null; 

        /// 儲存使用者的Profile 

        /// <param name="values">使用者的Profile的字典資料</param> 

        public int SetPropertiesForCurrentUser(IDictionary<string, object> values) 

                return values.Count; 

/// <summary> 

/// Article實體類 

/// </summary> 

/// <remarks> 

/// 示例而已,實際項目中要繼承自System.Web.Profile.ProfileBase 

/// </remarks> 

public class Article 

        private string _title; 

        /// 文章标題 

        public string Title 

                get { return _title; } 

                set { _title = value; } 

        private DateTime _publishTime; 

        /// 文章釋出日期 

        public DateTime PublishTime 

                get { return _publishTime; } 

                set { _publishTime = value; } 

Sample.aspx

<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Sample.aspx.cs" 

        Inherits="ClientScripting_SysServices_Sample" Title="Sys.Services命名空間下的類" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> 

        <div> 

                帳号:<input type="text" id="txtUserId" /></div> 

                密碼:<input type="password" id="txtPassword" /></div> 

                 </div> 

                <input type="button" id="btnLogin" value="登入" /> 

                <input type="button" id="btnLogout" value="登出" /></div> 

                年齡:<input type="text" id="txtAge" /></div> 

                薪水:<input type="text" id="txtSalary" /></div> 

                <input type="button" id="btnSave" value="儲存Profile" /> 

                <input type="button" id="btnLoad" value="讀取Profile" /> 

        </div> 

        <div id="result" /> 

        <script type="text/javascript"> 

                var userId; 

                var password; 

                var login; 

                var logout; 

                var age; 

                var salary 

                function pageLoad() 

                { 

                        userId = $get("txtUserId"); 

                        password = $get("txtPassword"); 

                        login = $get("btnLogin"); 

                        logout = $get("btnLogout"); 

                        age = $get("txtAge"); 

                        salary = $get("txtSalary"); 

                        // path - authentication service路徑 

                        $get("result").innerHTML = "AuthenticationService path:" + Sys.Services.AuthenticationService.get_path() + "<br />"; 

                        // timeout - 逾時時間 

                        $get("result").innerHTML += "AuthenticationService timeout:" + Sys.Services.AuthenticationService.get_timeout() + "<br />"; 

                        // path - profile service路徑 

                        $get("result").innerHTML += "ProfileService path:" + Sys.Services.ProfileService.get_path() + "<br />"; 

                        $get("result").innerHTML += "ProfileService timeout:" + Sys.Services.ProfileService.get_timeout() + "<br />"; 

                }                

                function btnLogin_click() 

                        // defaultLoginCompletedCallback - 登入成功後的回調函數 

                        Sys.Services.AuthenticationService.set_defaultLoginCompletedCallback(onLoginCompleted); 

                        // defaultFailedCallback - 登入或登出失敗後的回調函數 

                        Sys.Services.AuthenticationService.set_defaultFailedCallback(onFailed); 

                        Sys.Services.AuthenticationService.login 

                        ( 

                                userId.value, // 使用者名 

                                password.value, // 密碼 

                                false, // 是否跨浏覽器儲存認證資訊(持久保留) 

                                null, // 保留字段,可能在将來使用 

                                null, // 登入成功後重定向到的URL 

                                null, // 登入成功後的回調函數 

                                null, // 登入失敗後的回調函數 

                                "使用者上下文" // 使用者上下文 

                        ); 

                } 

                function btnLogout_click() 

                        // defaultLogoutCompletedCallback - 登出成功後的回調函數 

                        Sys.Services.AuthenticationService.set_defaultLogoutCompletedCallback(onLogoutCompleted); 

                        Sys.Services.AuthenticationService.logout 

                                null, // 登出成功後重定向到的URL 

                                null, // 登出成功後的回調函數 

                                null, // 登出失敗後的回調函數 

                                null // 使用者上下文 

                function onLoginCompleted(validCredentials, userContext, methodName) 

                        password.value = ""; 

                        // validCredentials - 是否成功通過了驗證 

                        // userContext - 使用者上下文 

                        // methodName - 調用的方法名 

                        if (validCredentials)    

                        { 

                                userId.value = ""; 

                                $get("result").innerHTML = "登入成功" + "<br />"; 

                                $get("result").innerHTML += "使用者上下文:" + userContext + "<br />"; 

                                $get("result").innerHTML += "調用的方法名為:" + methodName + "<br />"; 

                        } 

                        else 

                                $get("result").innerHTML = "登入失敗" + "<br />"; 

                        // isLoggedIn - 目前使用者是否已經登入 

                        var status = Sys.Services.AuthenticationService.get_isLoggedIn(); 

                        $get("result").innerHTML += "登入狀态:" + status + "<br />"; 

                function onFailed(error, userContext, methodName) 

                {         

                        // error - Sys.Net.WebServiceError對象 

                        $get("result").innerHTML += "錯誤資訊:" + error.get_message() + "<br />"; 

                function onLogoutCompleted(result, userContext, methodName)    

                        // result - 保留字段,可能在将來使用,始終為null 

                        alert("成功調用" + methodName) + "<br />"; 

                function btnLoad_click() 

                        // defaultLoadCompletedCallback - 讀取Profile成功後的回調函數 

                        Sys.Services.ProfileService.set_defaultLoadCompletedCallback(onLoadCompleted); 

                        // defaultFailedCallback - 讀取或儲存Profile失敗後的回調函數 

                        Sys.Services.ProfileService.set_defaultFailedCallback(onFailed); 

                        Sys.Services.ProfileService.load 

                                null, // Profile屬性名稱數組 

                                null, // 成功後的回調函數 

                                null, // 失敗後的回調函數 

                function btnSave_click() 

                        // defaultSaveCompletedCallback - 儲存Profile成功後的回調函數 

                        Sys.Services.ProfileService.set_defaultSaveCompletedCallback(onSaveCompleted); 

                        Sys.Services.ProfileService.properties.Age = age.value; 

                        Sys.Services.ProfileService.properties.Salary = salary.value; 

                        // 定義一個Profile組(同時需要在Web.config中定義) 

                        Sys.Services.ProfileService.properties.Article = new Sys.Services.ProfileGroup(); 

                        Sys.Services.ProfileService.properties.Article.Title = "Article Title"; 

                        Sys.Services.ProfileService.properties.Article.PublishTime = new Date(); 

                        Sys.Services.ProfileService.save 

                function onLoadCompleted(numProperties, userContext, methodName) 

                        // numProperties - 傳回的Profile屬性個數 

                        $get("result").innerHTML = "通過Profile讀取的屬性的數量為:" + numProperties.toString() + "<br />"; 

                        $get("result").innerHTML += "Age:" + Sys.Services.ProfileService.properties.Age + "<br />"; 

                        $get("result").innerHTML += "Article Title:" + Sys.Services.ProfileService.properties.Article.Title + "<br />";         

                        $get("result").innerHTML += "Article PublishTime:" + Sys.Services.ProfileService.properties.Article.PublishTime.format("yyyy-MM-dd") + "<br />"; 

                function onSaveCompleted(numProperties, userContext, methodName) 

                        // numProperties - 儲存的Profile屬性個數 

                        $get("result").innerHTML = "通過Profile儲存的屬性的數量為:" + numProperties.toString() + "<br />"; 

        </script> 

</asp:Content>

ScriptManager的設定

<asp:ScriptManager ID="ScriptManager1" runat="server"> 

                        <AuthenticationService Path="~/ClientScripting/SysServices/AuthenticationService.asmx" /> 

                        <ProfileService Path="~/ClientScripting/SysServices/ProfileService.asmx" /> 

                </asp:ScriptManager>

Web.config中的相關設定(在<system.web />節點下)

<profile enabled="true"> 

            <properties> 

                <group name="Article"> 

                    <add name="Title" type="System.String" /> 

                    <add name="PublishTime" type="System.DateTime" /> 

                </group> 

            </properties> 

        </profile>

運作結果

1、頁面加載後

AuthenticationService path:/Web/ClientScripting/SysServices/AuthenticationService.asmx

AuthenticationService timeout:0

ProfileService path:ProfileService.asmx

ProfileService timeout:0

2、單擊“登入”按鈕

登入成功

使用者上下文:使用者上下文

調用的方法名為:Sys.Services.AuthenticationService.login

登入狀态:true

3、單擊“登出”按鈕

彈出框,資訊:成功調用Sys.Services.AuthenticationService.logout

4、單擊“儲存Profile”按鈕

通過Profile儲存的屬性的數量為:4

5、單擊“讀取Profile”按鈕

通過Profile讀取的屬性的數量為:3

Age:27

Article Title:Article Title From Server

Article PublishTime:2007-07-12

     本文轉自webabcd 51CTO部落格,原文連結:http://blog.51cto.com/webabcd/344814,如需轉載請自行聯系原作者

繼續閱讀