webParts與Web部件

来源:http://www.cnblogs.com/HopeGi/archive/2016/12/23/6214403.html
-Advertisement-
Play Games

web部件是ASP.NET WebForm裡面的伺服器控制項,它涵蓋的內容比較多,鑒於這種狀況的話鄙人不打算深究下去了,只是局限於瞭解web.config配置裡面的配置內容則可。 那麼也得稍微說說啥是Web部件。引用MSDN的話:ASP.NET Web 部件是一組集成控制項,用於創建網站使最終用戶可以直 ...


web部件是ASP.NET WebForm裡面的伺服器控制項,它涵蓋的內容比較多,鑒於這種狀況的話鄙人不打算深究下去了,只是局限於瞭解web.config配置裡面的配置內容則可。

那麼也得稍微說說啥是Web部件。引用MSDN的話:ASP.NET Web 部件是一組集成控制項,用於創建網站使最終用戶可以直接從瀏覽器修改網頁的內容、外觀和行為。這些修改可以應用於網站上的所有用戶或個別用戶。還有引用它上面的插圖

看了這個之後我就感覺就類似於QQ個人空間上的各個面板或者OA系統上的面板,可以按照每個用戶的個人喜好去更改顯示的內容,位置以及是否顯示

更多關於Web部件的內容可參考本篇後面的參考的MSDN文章。關於Web部件的的WebPartManager和webParetZone就不說了,接下來則看看webParts配置節的內容

配置分兩大塊,personalization的是關於個性化設置數據的提供以及用戶訪問許可權的;另一個是關於web部件連接的時候數據結構不一致需要轉換的配置。

下麵則先看看personalization的,這個例子是參考了MSDN。實現的效果大概是記錄用戶個性化數據,以及對數據的許可權控制,本例子包含一個登錄頁面,一個示例頁面,兩個用戶控制項。

首先示例頁面的內容如下

登錄頁面只是包含了一個登錄控制項

用於展現用戶個性化設置的自定義控制項 Color

 

<%@ Control Language="C#" %>

<script runat="server">
    // User a field to reference the current WebPartManager.
    private WebPartManager _manager;

    //  Defines personalized property for User scope. In this case, the property is
    //   the background color of the text box.
    [Personalizable(PersonalizationScope.User)]
    public System.Drawing.Color UserColorChoice
    {
        get
        {
            return _coloruserTextBox.BackColor;
        }
        set
        {
            _coloruserTextBox.BackColor = value;
        }
    }

    // Defines personalized property for Shared scope. In this case, the property is
    //   the background color of the text box.
    [Personalizable(PersonalizationScope.Shared) ]
    public System.Drawing.Color SharedColorChoice
    {
        get
        {
            return _colorsharedTextBox.BackColor;
        }
        set
        {
            _colorsharedTextBox.BackColor = value;
        }
    }


    void Page_Init(object sender, EventArgs e)
    {
       _manager = WebPartManager.GetCurrentWebPartManager(Page);       
    }

    protected void Page_Load(object src, EventArgs e) 
    {
     // If Web Parts manager scope is User, hide the button that changes shared control.
       if (_manager.Personalization.Scope == PersonalizationScope.User)
       {
           _sharedchangeButton.Visible = false;
                  if (!_manager.Personalization.IsModifiable)
                      _userchangeButton.Enabled = false;
       }
       else
       {
           _sharedchangeButton.Visible = true; 
                  if (!_manager.Personalization.IsModifiable)
                    {
                      _sharedchangeButton.Enabled = false;
                      _userchangeButton.Enabled = false;
                    }
       } 
    }

    // Changes color of the User text box background when button clicked by authorized user.
    protected void _userButton_Click(object src, EventArgs e)
    {
        switch(_coloruserTextBox.BackColor.Name)
        {
            case "Red":
                _coloruserTextBox.BackColor = System.Drawing.Color.Yellow;
                break;
            case "Yellow":
                _coloruserTextBox.BackColor = System.Drawing.Color.Green;
                break;
            case "Green":
                _coloruserTextBox.BackColor = System.Drawing.Color.Red;
                break;
        }
    }

    // Changes color of the Shared text box background when button clicked by authorized user.
    protected void _sharedButton_Click(object src, EventArgs e)
    {
        switch (_colorsharedTextBox.BackColor.Name)
        {
            case "Red":
                _colorsharedTextBox.BackColor = System.Drawing.Color.Yellow;
                break;
            case "Yellow":
                _colorsharedTextBox.BackColor = System.Drawing.Color.Green;
                break;
            case "Green":
                _colorsharedTextBox.BackColor = System.Drawing.Color.Red;
                break;
        }        
    }   

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>WebParts Personalization Example</title>
</head>
<body>
<p>
    <asp:LoginName ID="LoginName1" runat="server" BorderWidth="500" BorderStyle="none" />
    <asp:LoginStatus ID="LoginStatus1" LogoutAction="RedirectToLoginPage" runat="server" />
</p>
    <asp:Label ID="ScopeLabel" Text="Scoped Properties:" runat="server" Width="289px"></asp:Label>
    <br />
    <table style="width: 226px">

        <tr>
            <td>
                <asp:TextBox ID="_coloruserTextBox" Font-Bold="True" Height="110px" 
                runat="server" Text="User Property" BackColor="red" Width="110px" /> 
            </td>
            <td>       
                <asp:TextBox ID="_colorsharedTextBox" runat="server" Height="110px" 
                Width="110px" Text="Shared Property" BackColor="red" Font-Bold="true" />
            </td>
       </tr>
        <tr>
            <td>
                <asp:Button Text="Change User Color" ID="_userchangeButton" 
                runat="server" OnClick="_userButton_Click" />
            </td>
            <td >
                <asp:Button Text="Change Shared Color" ID="_sharedchangeButton" 
                runat="server" OnClick="_sharedButton_Click" />
            </td>
        </tr>
    </table>
</body>
</html>

 

 

   

用於顯示用戶個性化數據許可權的自定義控制項Persmode

 

  1 <%@ control language="C#" %>
  2 
  3 <script runat="server">
  4 
  5  // Use a field to reference the current WebPartManager.
  6   private WebPartManager _manager;
  7 
  8     protected void Page_Load(object src, EventArgs e)
  9     {
 10         // Get the current Web Parts manager.
 11         _manager = WebPartManager.GetCurrentWebPartManager(Page);
 12 
 13         // All radio buttons are disabled; the button settings show what the current state is.
 14         EnterSharedRadioButton.Enabled = false;
 15         ModifyStateRadioButton.Enabled = false;
 16 
 17         // If Web Parts manager is in User scope, set scope button.
 18         if (_manager.Personalization.Scope == PersonalizationScope.User)
 19             UserScopeRadioButton.Checked = true;
 20         else
 21             SharedScopeRadioButton.Checked = true;
 22 
 23         // Based on current user rights to enter Shared scope, set buttons.
 24         if (_manager.Personalization.CanEnterSharedScope)
 25         {
 26             EnterSharedRadioButton.Checked = true;
 27             No_Shared_Scope_Label.Visible = false;
 28             Toggle_Scope_Button.Enabled = true;
 29         }
 30         else
 31         {
 32             EnterSharedRadioButton.Checked = false;
 33             No_Shared_Scope_Label.Visible = true;
 34             Toggle_Scope_Button.Enabled = false;
 35         }
 36 
 37         // Based on current user rights to modify personalization state, set buttons.
 38         if (_manager.Personalization.IsModifiable)
 39         {
 40             ModifyStateRadioButton.Checked = true;
 41             Reset_User_Button.Enabled = true;
 42         }
 43         else
 44         {
 45             ModifyStateRadioButton.Checked = false;
 46             Reset_User_Button.Enabled = false;
 47         }
 48     }
 49   // Resets all of a user and shared personalization data for the page.
 50     protected void Reset_CurrentState_Button_Click(object src, EventArgs e)
 51     {
 52         // User must be authorized to modify state before a reset can occur.
 53         //When in user scope, all users by default can change their own data.
 54         if (_manager.Personalization.IsModifiable)
 55         {
 56             _manager.Personalization.ResetPersonalizationState();
 57         }
 58     }
 59 
 60     // Allows authorized user to change personalization scope.
 61     protected void Toggle_Scope_Button_Click(object sender, EventArgs e)
 62     {
 63         if (_manager.Personalization.CanEnterSharedScope)
 64         {
 65             _manager.Personalization.ToggleScope();
 66         }
 67 
 68     }
 69 </script>
 70 <div>
 71     &nbsp;<asp:Panel ID="Panel1" runat="server" 
 72     Borderwidth="1" 
 73     Width="208px" 
 74     BackColor="lightgray"
 75     Font-Names="Verdana, Arial, Sans Serif" Height="214px" >
 76     <asp:Label ID="Label1" runat="server" 
 77       Text="Page Scope" 
 78       Font-Bold="True"
 79       Font-Size="8pt"
 80       Width="120px" />&nbsp;<br />
 81 
 82 
 83       <asp:RadioButton ID="UserScopeRadioButton" runat="server" 
 84         Text="User" 
 85         AutoPostBack="true"
 86         GroupName="Scope"  
 87          Enabled="false" />
 88       <asp:RadioButton ID="SharedScopeRadioButton" runat="server" 
 89         Text="Shared" 
 90         AutoPostBack="true"
 91         GroupName="Scope" 
 92         Enabled="false" />
 93         <br />
 94         <asp:Label BorderStyle="None" Font-Bold="True" Font-Names="Courier New" ID="No_Shared_Scope_Label" Font-Size="Smaller" ForeColor="red"
 95            runat="server" Visible="false" Width="179px">User cannot enter Shared scope</asp:Label>
 96         <br />
 97         <asp:Label ID="Label2" runat="server" 
 98       Text="Current User Can:" 
 99       Font-Bold="True"
100       Font-Size="8pt"
101       Width="165px" />
102       <br />
103         <asp:RadioButton ID="ModifyStateRadioButton" runat="server" 
104         Text="Modify State" Width="138px" />
105         <br />
106         <asp:RadioButton ID="EnterSharedRadioButton" runat="server" 
107         Text="Enter Shared Scope" 
108         AutoPostBack="true"  />&nbsp;<br />
109         <br />
110         <asp:Button ID="Toggle_Scope_Button" OnClick="Toggle_Scope_Button_Click" runat="server"
111             Text="Change Scope" Width="186px" /><br />
112         <br />
113         <asp:Button ID="Reset_User_Button" OnClick="Reset_CurrentState_Button_Click" runat="server"
114             Text="Reset Current Personalization" Width="185px" /></asp:Panel>
115     &nbsp; &nbsp;
116 </div>

 

 

 

最後少不了的就是在web.config中添加配置

在這裡開始吹水了,首先MSDN上面例子沒提及到要添加認證的配置,使得我最開始的時候登錄了還沒看到效果。後來在懷疑是需要配置認證機制。接著這裡使用了一個Provider,AspNetSqlPersonalizationProvider並非類名,只是SqlPersonalizationProvider配置的名稱而已。預設配置如下,

在ASP.NET中實現了這個個性化提供者的就只有這個SqlPersonalizationProvider,這個我是看源碼還有MSDN中類的繼承結構中看出來的。不知有無其他地方明確指出,如需要其他的提供機制,則需要自定義擴展了。

您可以從其中 PersonalizationProvider ,並提供僅在此類中定義的抽象方法的實現。 抽象方法處理專門與保存和載入數據寫入物理數據存儲,以及數據存儲區管理。 自定義提供程式必須能夠處理可區分的方式的個性化信息 Shared 中的數據 User 數據。 此外,提供程式必須段個性化數據頁以及按應用程式。

實現 PersonalizationProvider 緊密耦合的實現與 PersonalizationState 由於某些個性化設置提供程式方法返回的實例 PersonalizationState的派生類。 為了便於開發自定義提供程式, PersonalizationProvider 基類包括個性化設置邏輯和序列化/反序列化邏輯,直接使用的預設實現WebPartPersonalization 類。 結果是,創作專門用於使用不同的數據存儲區的自定義提供只需要下列抽象方法的實現︰

  • GetCountOfState -此方法需要能夠在資料庫中為提供的查詢參數的個性化數據行的數目進行計數。
  • LoadPersonalizationBlobs -在給定路徑和用戶名的情況下,此方法從資料庫中載入兩個二進位大型對象 (Blob): 一個用於共用的數據,另一個用於用戶數據的 BLOB。 如果您提供的用戶名稱和路徑,則不需要 WebPartManager 控制項,用於訪問可以提供的用戶文件名/路徑信息的頁信息。
  • ResetPersonalizationBlob -在給定路徑和用戶名的情況下,此方法中刪除資料庫中相應的行。 如果您提供的用戶名稱和路徑,則不需要WebPartManager 控制項,用於訪問可以提供的用戶文件名/路徑信息的頁信息。
  • SavePersonalizationBlob --此方法在給定的路徑和用戶名稱,保存對資料庫所提供的 BLOB。 如果您提供的用戶名稱和路徑,則不需要 WebPartManager 控制項,用於訪問可以提供的用戶文件名/路徑信息的頁信息。

在所有這些方法中,如果只提供一個路徑,則表示正在操作頁上的共用的個性化設置數據。 如果用戶名和路徑傳遞到方法中,頁上的用戶個性化設置數據應得到處理。 情況下 LoadPersonalizationBlobs, ,應始終載入指定的路徑的共用的數據,並 (可選) 的路徑的用戶個性化設置數據也如果應載入的用戶名不是 null

所有抽象方法旨在僅用於管理應用程式,在運行時不使用由 Web 部件基礎結構。 個性化設置提供程式的實現的示例,請參閱SqlPersonalizationProvider 類。

說了這麼多看看這個示例的運行效果

經過登錄之後就可以看到界面如上所示,點擊Change xxx Color就可以改變方塊的顏色,這些顏色設置是存儲到資料庫的,用戶可以在註銷下次登錄時扔看到這些設置,包括對面板的關閉和最小化操作。下麵的面板是控制這些設置的作用域,一個是用戶個人的,一個是全局共用的。可以通過Change Scope去切換。這裡涉及到兩個方面內容,首先是數據保存,數據存儲在Web程式預設建立的SqlServer資料庫中,與MemberShip的庫相同。個人數據的放在PersonalizationAllUsers裡面,Share的則放在PersonalizationPerUser中。所有的數據都並非直接存放在表中,作為通用存儲的話這是不可能的。

另外關於許可權控制的,在配置文件中的personalization/authorization配置節跟system.web/authorization的結構很相像,區別在於verbs,這裡用的值僅以下兩種。

對於獲取設置信息是不阻攔的,但是需要更換作用域進入共用區時需要有enterSharedScope許可權,當需要更改任何一個作用域的數據時需要modeifyState。如果兩個許可權都被deny的話,用戶就只能傻傻地看了

personalization的結束到此完,接下來到transformers。這裡涉及到一個web部件連接的概念。不知我自己有否理解錯,這個web部件連接的雙方中提供數據的一方個人感覺就是一個數據源。數據源提供的數據可以給頁面上其他多個控制項使用,但是數據源提供的數據格式不一定符合其他所有控制項,因此這裡就需要一個轉換器來適配雙方的差異,這就是適配器模式嘛!嗎?但是要是說多弄一個數據源(或者叫Provider)的話,這樣的開銷比較大。那麼ASP.NET提供的轉換器就只有兩個RowToFieldTransformer和RowToParametersTransformer,如果需要其他的轉換就需要自己定義,還需要到配置文件中聲明一下這個轉換器,下麵也是借鑒了一個MSDN的例子來嘗試一下通過一個行轉換到字元串。

對於MSDN的例子我還是精簡了兩個控制項,大概可以看以下這裡建立了一個靜態的Web部件連接,通過一個rowtostringtransformer進行轉換。這個鏈接的提供者是rowproviderwebpart的自定義webPart,另一個stringconsumerwebpart的自定義webpart。這些類都定義在App_Code文件夾中,所以註冊命名空間的時候要註意一下

下麵就是各個文件的代碼IString

RowToStringTransformer

   

下麵這兩個類是參考了MSDN的代碼,自己根據當前的情況改過一下,不然運行不了,但不知道有否改錯,使之背離願意

    // This sample code creates a Web Parts control that acts as a provider 
    // of row data.
    [AspNetHostingPermission(SecurityAction.Demand,
      Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand,
      Level = AspNetHostingPermissionLevel.Minimal)]
    public sealed class RowProviderWebPart : WebPart, IWebPartRow
    {
        private DataTable _table;

        public RowProviderWebPart()
        {
            _table = new DataTable();

            DataColumn col = new DataColumn();
            col.DataType = typeof(string);
            col.ColumnName = "Name";
            _table.Columns.Add(col);

            col = new DataColumn();
            col.DataType = typeof(string);
            col.ColumnName = "Address";
            _table.Columns.Add(col);

            col = new DataColumn();
            col.DataType = typeof(int);
            col.ColumnName = "ZIP Code";
            _table.Columns.Add(col);

            DataRow row = _table.NewRow();
            row["Name"] = "John Q. Public";
            row["Address"] = "123 Main Street";
            row["ZIP Code"] = 98000;
            _table.Rows.Add(row);
        }

        [ConnectionProvider("String123")]
        public IWebPartRow GetConnection()
        {
            return new RowProviderWebPart();
        }

        public PropertyDescriptorCollection Schema
        {
            get
            {
                return TypeDescriptor.GetProperties(_table.DefaultView[0]);
            }
        }

        public void GetRowData(RowCallback callback)
        {
            foreach (var item in _table.DefaultView)
            {
                callback(item);
            }
        }

    } 



    [AspNetHostingPermission(SecurityAction.Demand,
        Level =
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 匿名方法 在 C# 2.0 之前的版本中,創建委托的唯一方式是使用命名方法。 從 C# 2.0 開始引入了匿名方法,而在 C# 3.0 以及更高的版本中,Lambda 表達式取代了匿名方法,從而作為編寫內聯代碼的首選方式。 不過,這裡有關匿名方法的信息同樣也適用於 Lambda 表達式。 需要註意的 ...
  • 很高興能再次和大家分享webapi介面的相關文章,本篇將要講解的是如何在應用中調用webapi介面;對於大部分做內部管理系統及類似系統的朋友來說很少會去調用別人的介面,因此可能在這方面存在一些困惑,希望本篇分享文章內容能給您們帶來幫助或者學習,希望大家喜歡,也希望各位多多掃碼支持和點贊謝謝: » 簡 ...
  • 吐槽…使用清理軟體整理電腦要註意,不要清理的“太狠”,不然你會受傷的! C#中的Substring() 示例 實現代碼 using System;using System.Collections.Generic;using System.Linq;using System.Text;using Sy ...
  • 支持並尊重原創!原文地址:http://jingyan.baidu.com/article/2c8c281deb79ed0008252af1.html 判斷一個字元是不是漢字通常有三種方法,第1種用 ASCII 碼判斷,第2種用漢字的 UNICODE 編碼範圍判 斷,第3種用正則表達式判斷,下麵是具 ...
  • 官網: "http://mahapps.com/" github: "https://github.com/MahApps/MahApps.Metro" ...
  • 一、借鑒說明 1.《Head First Design Patterns》(中文名《深入淺出設計模式》) 2.維基百科,觀察者模式,https://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F 3.MSDN,e... ...
  • public class WriteLog { /// /// 創建日誌文件 /// /// 異常類 public static void CreateLog(Exception ex) { string path = A... ...
  • private void button1_Click(object sender, EventArgs e) { double number1, number2; if (double.TryParse(txtNumber1.Text, out number1) == false) { Messag... ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...