WebParts and Web Parts

Source: Internet
Author: User

The Web Part is a server control inside ASP. NET WebForm, it covers a lot of content, in view of this situation, I do not intend to delve into it, but only limited to understand the configuration inside the Web. config configuration content can be.

Then you have to say a little bit about what a Web Part is. Quote MSDN: The ASP. NET Web Part is a set of integrated controls that are used to create a Web site that enables end users to modify the content, appearance, and behavior of a Web page directly from the browser. These modifications can be applied to all users or individual users on the site. and a reference to the illustrations above it.

After watching this I feel like QQ personal space on the various panels or OA system on the panel, you can follow each user's personal preferences to change the display of the content, location and whether the display

For more information about Web Parts, refer to the MSDN article later in this article. WebPartManager and webparetzone about Web Parts don't talk, and then look at the contents of the WebParts configuration section

The configuration is divided into two chunks, personalization is about the provision of personalization data and user access, and the other is about the Web Parts connection when the data structure inconsistency needs to be transformed configuration.

The following is a look at personalization, this example is reference to MSDN. The effect of the implementation is probably to record the user personalization data, as well as the permission control of the data, this example contains a login page, a sample page, two user controls.

The content of the sample page begins with the following

The login page contains only a login control

Custom control Color for displaying user personalization

<%@ Control language= "C #"%><script runat= "Server" >//User A field to reference the current WebPartManager    .    Private WebPartManager _manager; Defines personalized property for User scope.    The 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.    The 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 th       At 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>

Custom control to display user personalization data Permissions Persmode

  1 <%@ Control language= "C #"%> 2 3 <script runat= "Server" > 4 5//Use a field to reference the Curren  T WebPartManager.  6 private WebPartManager _manager;         7 8 protected void Page_Load (Object src, EventArgs e) 9 {ten//Get the current Web Parts manager. 11 _manager = Webpartmanager.getcurrentwebpartmanager (Page); //All radio buttons is disabled; The button settings show what's the current state is. entersharedradiobutton.enabled = false; modifystateradiobutton.enabled = false; Parts/If Web Manager is in User scope, set scope button. if (_manager. Personalization.Scope = = Personalizationscope.user) userscoperadiobutton.checked = true; else sharedscoperadiobutton.checked = true; Based on current user rights to enter Shared scope, set buttons. if (_manager. Personalization.canentersharedscope) 25 {Entersharedradiobutton.checked = true; No_shared_scope_label.visible = false; Toggle_scope_button.enabled = true; {entersharedradiobutton.checked = false; no_shared_ Scope_label.visible = true; toggle_scope_button.enabled = false; A//Based on the current user rights to modify personalization state, set buttons. if (_manager. personalization.ismodifiable) modifystateradiobutton.checked = true; reset_user _button.enabled = true; (modifystateradiobutton.checked = false; Reset_user _button.enabled = false; *//Resets all of a user and GKFX personalization data for the page. protected void Reset_currentstate_button_click (Object src, EventArgs e) {//User must be authOrized to modify state before a reset can occur. //when in user scope, the all users by default can change their own data. if (_manager. personalization.ismodifiable) (_manager). Personalization.resetpersonalizationstate (); Allows authorized user to change personalization scope. protected void Toggle_scope_button_click (object sender, EventArgs e) (_manager. Personalization.canentersharedscope) (_manager). Personalization.togglescope ();     &nbsp;<asp:panel id= "Panel1" runat= "Server 72" ($ </script>) Borderwidth= "1" width= "208px" backcolor= "Lightgray" font-names= "Verdana, Arial, Sans Serif" Hei        ght= "214px" > <asp:label id= "Label1" runat= "Server" "text=" page Scope "font-bold=" True "79 Font-size= "8pt" width= "120px"/>&nbsp;<br/> Bayi <asp:radiobutton id= "Userscoperadiobutton" runat= "Server" text= "User" 85 Autopostback= "true" Groupname= "Scope" enabled= "false"/> <asp:radiobutton id= " Sharedscoperadiobutton "runat=" Server "text=" Shared "autopostback=" true "Groupname=" Sco  PE "enabled=" false "/> <br/> 94 <asp:label borderstyle=" None "font-bold=" True " font-names= "Courier New" id= "No_shared_scope_label" font-size= "Smaller" forecolor= "Red" runat= "Server" Visi Ble= "false" Width= "179px" >user cannot enter Gkfx scope</asp:label> (<br/>) <asp:l       Abel id= "Label2" runat= "Server" 98 text= "current User Can:" font-bold= "True" 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=" serv ER "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_butto N "onclick=" Reset_currentstate_button_click "runat=" Server "text=" Reset Current Personalization "width=" 185 PX "/></asp:panel>115 &nbsp; &nbsp;116 </div>

The last thing to do is add the configuration in Web. config

Started blowing water here, first of all the MSDN above example did not mention to add the authentication configuration, so I started the time to log in and did not see the effect. Later in the suspicion is the need to configure the authentication mechanism. Then a provider,aspnetsqlpersonalizationprovider is used instead of the class name, just the name of the SqlPersonalizationProvider configuration. The default configuration is as follows

This is the only sqlpersonalizationprovider that has been implemented in ASP. This is what I see in the source code and the inheritance structure of the class in MSDN. It is not clear that there are other places that require custom extensions if other delivery mechanisms are required.

You can personalizationprovider from it and provide an implementation of an abstract method that is defined only in this class. Abstract methods are handled specifically with saving and loading data written to the physical data store, as well as data store management. A custom provider must be able to handle personalization information in a distinguishable manner in the data User data in Shared. Additionally, the provider must segment the personalization data page and press the application.

Implement PersonalizationProvider tightly coupled implementations with personalizationstate derived classes that are returned by instance personalizationstate due to certain personalization settings provider methods. To facilitate the development of custom providers, the PersonalizationProvider base class includes personalization logic and serialization/deserialization logic, directly using the default implementation of the Webpartpersonalization class. As a result, authoring a customization that is dedicated to using different data stores only requires an implementation of the following abstract methods:

    • Getcountofstate-This method requires the ability to count the number of personalization data rows in the database for the supplied query parameters.
    • Loadpersonalizationblobs-In the case of a given path and user name, this method loads two binary large objects (BLOBs) from the database: one for shared data and another BLOB for user data. If you provide a user name and path, you do not need the WebPartManager control to access the page information that can provide the user file name/path information.
    • Resetpersonalizationblob-In the case of a given path and user name, the corresponding row in the database is deleted in this method. If you provide a user name and path, you do not need the WebPartManager control to access the page information that can provide the user file name/path information.
    • Savepersonalizationblob--This method saves the BLOB that is provided to the database at the given path and user name. If you provide a user name and path, you do not need the WebPartManager control to access the page information that can provide the user file name/path information.

In all of these methods, if only one path is provided, the shared personalization data is being manipulated on the page. If the user name and path are passed to the method, the user personalization data on the page should be processed. In case of Loadpersonalizationblobs, the specified path should always be loaded with the shared data, and (optionally) the path of the user personalization data also if the user name should be loaded is not null.

All abstract methods are designed to be used only for managing applications that are not used by the WEB part infrastructure at run time. For an example of the implementation of a personalization provider, see the SqlPersonalizationProvider class.

Having said so much to see how this example works

After logging in you can see the interface as shown above, click on the change of XXX color can be changed the color of the box, these color settings are stored in the database, the user can log off the next time to throw see these settings, including the panel of the closure and minimize the operation. The following panel controls the scope of these settings, one for the user and one for the global share. You can switch by changing scope. There are two aspects involved, first of all the data is saved, and the data is stored in the SQL Server database established by the Web program by default, the same as the membership library. The personal data is placed in the personalizationallusers, share is placed in the Personalizationperuser. None of the data is stored directly in the table, which is not possible as a generic store.

In addition to the rights control, in the configuration file personalization/authorization configuration section is similar to the structure of system.web/authorization, the difference is verbs, here the value of only the following two kinds.

It is not blocked to get the provisioning information, but requires entersharedscope permission when the scope needs to be replaced and needs to be modeifystate when the data for any one scope needs to be changed. If all two permissions are denied, the user will only be able to look innocently

The end of the personalization, and then to Transformers. Here comes the concept of a Web Parts connection. I do not know whether I understand the wrong, this Web part of the two sides of the connection to provide data on the side of the personal feeling is a data source. Data sources provide data that can be used by multiple other controls on the page, but the data source provides a format that does not necessarily conform to all other controls, so there is a need for a converter to match the differences between the two sides, which is the adapter pattern! It? But it's a lot more expensive to say that you get a data source (or provider). Then there are only two RowToFieldTransformer and RowToParametersTransformer for the converter provided by ASP, if you need to define the other conversions, you need to declare the converter in the configuration file, and the following is an example of MSDN To try to convert to a string by a line.

For the MSDN example, I've streamlined two controls, and I'm probably looking at the following here a static Web Part connection is created, which can be converted through a rowtostringtransformer. The provider of this link is Rowproviderwebpart custom webpart, another Stringconsumerwebpart custom WebPart. These classes are defined in the App_Code folder, so be aware when registering namespaces

Here is the code for each file istring

Rowtostringtransformer

The following two classes are reference to the MSDN code, according to the current situation of the change, or can not run, but do not know whether there is a mistake to make it deviate from the willing

    This is 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 s        Ealed 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 Rowpro        Viderwebpart (); Public PropertyDescriptorCollection Schema {get {return Typedescrip Tor. GetProperties (_table.            Defaultview[0]); }} public void GetRowData (RowCallback callback) {foreach (var item in _table.            DefaultView) {callback (item);    }}} [AspNetHostingPermission (SecurityAction.Demand, level = Aspnethostingpermissionlevel.minimal)] [AspNetHostingPermission (SecurityAction.InheritanceDemand, level = Aspnethostingpermissionlevel.minimal)] Publi     C Sealed class Stringconsumerwebpart:webpart {private istring _provider;   private string _stringdata;        private void GetRowData (object rowdata) {_stringdata = Rowdata.tostring ();                } protected override void OnPreRender (EventArgs e) {if (_provider! = null) { _provider.            GetStringValue (New Stringcallback (GetRowData)); }} protected override void RenderContents (HtmlTextWriter writer) {if (!string. IsNullOrEmpty (_stringdata)) {writer.                Write (_stringdata); Writer.                Writebreak (); Writer.            WriteLine (); } else {writer.            Write ("No data");            }} [ConnectionConsumer ("String123")] public void SetConnection (Istring provider) {        _provider = provider; }    }

Find _provider when debugging. GetStringValue (New Stringcallback (GetRowData)); This line of code is the most around, with several delegates embedded, and the interesting part is that when Get/set is connected, it uses something like dependency injection, The display parameter of the attribute connection Get/set two methods, completely ignoring the name of the method, but this connectionconsumer and ConnectionProvider can only describe the method, Otherwise you can use the properties to go.

Almost forgot to add the configuration of the Web. config

The end result, for example, is that a single table in provider is specifically made into a string.

WebParts and Web Parts

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.