Pro Server Controls and AJAX Components phần 7 pot

77 394 0
Pro Server Controls and AJAX Components phần 7 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 9 ■ ASP.NET AJAX CONTROLS AND EXTENDERS 437 // Control properties get_highlightCssClass : function() { return this._highlightCssClass; }, set_highlightCssClass : function(value) { if (this._highlightCssClass !== value) { this._highlightCssClass = value; this.raisePropertyChanged('highlightCssClass'); } }, get_nohighlightCssClass : function() { return this._nohighlightCssClass; }, set_nohighlightCssClass : function(value) { if (this._nohighlightCssClass !== value) { this._nohighlightCssClass = value; this.raisePropertyChanged('nohighlightCssClass'); } } } // Optional descriptor for JSON serialization. ControlsBook2Lib.Ch09.HighlightedHyperlink.descriptor = { properties: [ {name: 'highlightCssClass', type: String}, {name: 'nohighlightCssClass', type: String} ] } // Register the class as a type that inherits from Sys.UI.Control. ControlsBook2Lib.Ch09.HighlightedHyperlink.registerClass('ControlsBook2Lib.Ch09. HighlightedHyperlink', Sys.UI.Control); if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); Notice that the HighlightedHyperlink client-side component doesn’t need to know the CSS class names in advance. The client-side component also contains an optional descriptor for JSON serialization support. Figure 9-1 shows HighlightedHyperLink ASP.NET AJAX-enabled server control in action in the HighlightedHyperLink web form. Cameron_865-2C09.fm Page 437 Monday, February 18, 2008 4:15 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 438 CHAPTER 9 ■ ASP.NET AJAX CONTROLS AND EXTENDERS Figure 9-1. The rendered HighlightedHyperLink web form in Firefox The source code for the HighlightedHyperLink web form and code-behind file is shown in Listings 9-13 and 9-14. Listing 9-13. The HighlightedHyperLink Web Form .aspx Page File <%@ Page Language="C#" MasterPageFile="~/MasterPage/ControlsBook2MasterPage.Master" AutoEventWireup="true" CodeBehind="HighlightedHyperlink.aspx.cs" Inherits="ControlsBook2Web.Ch09.HighlightedHyperlink" Title="HighlightedHyperLink Demo" %> <%@ Register TagPrefix="apress" Namespace="ControlsBook2Lib.Ch09" Assembly="ControlsBook2Lib" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeadSection" runat="server"> <style type="text/css"> .Highlight { color: navy; font-weight: bolder; } .NoHighlight { color: Green; font-weight: lighter; } </style> </asp:Content> Cameron_865-2C09.fm Page 438 Monday, February 18, 2008 4:15 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 9 ■ ASP.NET AJAX CONTROLS AND EXTENDERS 439 <asp:Content ID="Content2" ContentPlaceHolderID="ChapterNumAndTitle" runat="server"> <asp:Label ID="ChapterNumberLabel" runat="server Width="14px">9</asp:Label>&nbsp;&nbsp;<asp:Label ID="ChapterTitleLabel" runat="server" Width="360px"> ASP.NET AJAX Controls and Extenders</asp:Label> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="PrimaryContent" runat="server"> <br /> <apress:HighlightedHyperLink ID="HighlightedHyperLink1" HighlightCssClass="Highlight" NoHighlightCssClass="NoHighlight" runat="server" NavigateUrl="http://www.microsoft.com">Microsoft </apress:HighlightedHyperLink><br /> <apress:HighlightedHyperLink ID="HighlightedHyperLink2" HighlightCssClass="Highlight" NoHighlightCssClass="NoHighlight" runat="server" NavigateUrl="http://apress.com">Apress </apress:HighlightedHyperLink><br /> <apress:HighlightedHyperLink ID="HighlightedHyperLink3" HighlightCssClass="Highlight" NoHighlightCssClass="NoHighlight" runat="server" NavigateUrl="http://ajax.asp.net"> ASP.NET AJAX</apress:HighlightedHyperLink><br /> <apress:HighlightedHyperLink ID="HighlightedHyperLink4" HighlightCssClass="Highlight" NoHighlightCssClass="NoHighlight" runat="server" NavigateUrl="http://msdn.microsoft.com"> MSDN Online</apress:HighlightedHyperLink><br /> <br /> </asp:Content> Listing 9-14. The HighlightedHyperLink Web Form Code-Behind Class File using System; namespace ControlsBook2Web.Ch09 { public partial class HighlightedHyperlink : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } This concludes our discussion of the HighlightedHyperLink ASP.NET AJAX server control. Cameron_865-2C09.fm Page 439 Monday, February 18, 2008 4:15 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 440 CHAPTER 9 ■ ASP.NET AJAX CONTROLS AND EXTENDERS Summary In this chapter, we provided an overview of ASP.NET AJAX, both the server-side and client-side functionality. ASP.NET AJAX includes a powerful client-side script library that provides cross- browser compatibility, as well as a powerful client-side programming model that mimics object-oriented behavior in JavaScript. We covered the server-side programming model that requires implementation of the GetScriptDescriptors and GetScriptReferences methods. We also explained how the server- side configuration is passed to the client-side component utilizing the ScriptBehaviorDescriptor class. Finally, we demonstrated how to implement both an ASP.NET AJAX server control by implementing IScriptControl, as well as how to implement an extender control by inheriting from the ExtenderControl base class. For additional examples of ASP.NET AJAX server controls and extenders, we recommend downloading and reviewing the ASP.NET AJAX Control Toolkit available at http://asp.net/ ajax/ajaxcontroltoolkit/samples/. Cameron_865-2C09.fm Page 440 Monday, February 18, 2008 4:15 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 441 ■ ■ ■ CHAPTER 10 Other Server Controls Up to this chapter, we have focused on providing the necessary background to create powerful ASP.NET server controls that support custom styling, templating, data binding, client-side script, and ASP.NET AJAX. These development techniques and features can be put to work in many different ways. In this part of the book, we begin to move on to advanced topics such web part development and design-time support. In this chapter, we begin our advanced topic journey by covering web part development and adaptive control programming. We will start off with a discussion on building web parts for both ASP.NET and Microsoft Office SharePoint Server 2007. Next, we will focus on adaptive control development, including the mobile controls for devices. In the next section, we begin our journey with web parts. ■Note For information on building custom validator controls, the MSDN documentation contains a nice set of cross-browser validator control samples that also comply with the WWW Consortium DOM Level 1 specification; the samples are located here: http://msdn2.microsoft.com/en-us/library/aa719624(VS.71).aspx. Web-Part-Based Web Site Development This chapter won’t attempt to provide a complete overview of the web part infrastructure and development model available in ASP.NET, because the documentation does a very good job of explaining what functionality is available. What I will do is provide a discussion on various web part topics encountered while building out the example web parts in this chapter to help you understand the moving parts available when building web parts. If you find that you need more background information on a particular area, here is the top-level link to the ASP.NET web parts documentation at MSDN Online: http://msdn2.microsoft.com/en-us/library/e0s9t4ck(VS.90).aspx From the preceding link, you can navigate to these sections for more detail on a partic- ular topic: • ASP.NET Web Parts Overview • Web Parts Control Set Overview Cameron_865-2C10.fm Page 441 Thursday, February 21, 2008 1:01 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 442 CHAPTER 10 ■ OTHER SERVER CONTROLS • Web Parts Page Display Modes • Web Parts Personalization • Web Parts Connections Overview For an idea of what’s possible, look no further than Microsoft Office SharePoint Server (MOSS) 2007, which is built on top of ASP.NET and the web part infrastructure. A public-facing Internet site built on top of MOSS with custom web parts is http://www.glu.com. Here is a link to the first of a three-part series on how this site was built by Allin Consulting on MOSS and ASP.NET web parts: http://blogs.msdn.com/sharepoint/archive/2007/06/14/ moss-has-got-game-glu-mobile-s-website-www-glu-com-how-we-did-it-part-1-of-3.aspx With that background out of the way, we’ll dive into a discussion on web part development in the next section. Web Part Development Web parts have existed in SharePoint for many years. Initially, the web part development model was based on VBScript, which is not what most developers would call their favorite development language or environment. In SharePoint Server 2003, Microsoft more closely integrated SharePoint with ASP.NET, providing namespaces for supporting web part develop- ment in .NET. With .NET Framework 2.0, the ASP.NET team integrated the web part infrastructure and development model within ASP.NET itself. However, the two web part models remained separate. Building web parts that targeted both ASP.NET 2.0 and SharePoint Server 2003 required custom compilation, since different namespaces and base classes where required. In Microsoft Office SharePoint Server (MOSS) 2007, SharePoint is completely integrated with and built on ASP.NET 2.0. This means that you can build web parts for MOSS using the ASP.NET WebPart base class. ■Note Microsoft recommends inheriting from the ASP.NET WebPart base class whether developing for pure ASP.NET or SharePoint. The next section provides a brief overview of the ASP.NET web part infrastructure to set the state for building web parts that take advantage of this framework. Web Part Infrastructure One of the features of WebPart-based applications is personalization. WebParts can have attributes configured with the PersonalizableAttribute so that a user can create a unique view on the page. Personalization for an ASP.NET web site requires that the SQL personalization provider is configured for the site. Cameron_865-2C10.fm Page 442 Thursday, February 21, 2008 1:01 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 10 ■ OTHER SERVER CONTROLS 443 ■Note Personalization requires that the <trust level="" /> element is configured for Medium in order to access members in the SqlClient namespace. The SqlPersonalizationProvider class is used to configure the personalization in SQL Server. The ASP.NET SQL Server Registration Tool (Aspnet_regsql.exe) can be used to set up the database location for web part personalization, among other databases such as the ASP.NET membership database. The tool is located at \%windir%\Microsoft.NET\Framework\v2.0.50727, or at the same location for a later version of the framework. There is a section in the web.config file to declaratively configure web part personalization via the WebPartsPersonalization class under <system.web> <WebParts> <personalization. . . > that can be used to configure the web part environment. Refer to the MSDN documentation for more information on the WebPartsPersonalization class. Web parts are hosted within the rich web part infrastructure, so as you would expect, there are additional customizations available for web part developers. Table 10-1 provides a list of the most common overrides when creating a WebPart server control. With that background out of the way, let’s move on to creating web parts in the next section. Creating Web Parts In this section, we create two server controls and demonstrate them in a basic ASPX page. Next, we convert the server controls to web parts and then demonstrate them in a web part portal page. Table 10-1. WebPart Common Overrides WebPart Member Overview "Allow" properties These are behavior-focused properties that control developers may want to manage for the logic of their custom WebPart control. Examples are AllowClose, AllowConnect, and AllowEdit. CreateChildControls It is quite common to build web parts based on composite server controls to encapsulate chunks of functionality as a WebPart control. CreateEditorParts Web parts can have custom editor web parts based on EditorPart to enable users to edit custom web part properties. Override CreateEditorParts to incorporate the custom EditorPart control. PersonalizableAttribute This attribute is applied to properties of the custom web part that the user may want to save unique settings to. Rendering methods As with custom server controls, sometimes you may need to override Render or RenderContents to completely change the outputted HTML or to simply customize it by also calling the base method. Verbs Add custom WebPartVerb objects to the Verbs collection to allow custom menu actions to appear along with the standard verbs such as close or minimize. Cameron_865-2C10.fm Page 443 Thursday, February 21, 2008 1:01 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 444 CHAPTER 10 ■ OTHER SERVER CONTROLS This may seem like the long road to building web parts, but we believe it is more realistic. In many situations, developers will create server controls and statically code the page layout and what server controls appear on a page as part of an application. Initially, there are perhaps just a couple of server controls, but after a couple of cycles where users ask for additional func- tionality or views on data, developers may find themselves with a library of server controls with different users requesting multiple combinations of server controls, resulting in multiple, hand- coded, statically linked and created web forms. At this point, the developer may ask, “Why not create a web part portal page where users can pick which controls display on the page, how the controls are laid out, and which controls are linked?” Regarding what type of scenario may fit this model, a reporting web portal or business intelligence application comes to mind, so our focus for this demonstration is providing a reporting page focused on the famous Northwind database with NorthWind customers as the theme for the site. In the next section, we build the server controls web form with two server controls reporting NorthWind customer data. The Server Controls As mentioned in the previous section, we start out by creating server control versions of the web parts and then show how to turn them into web parts in the next section. The two server controls retrieve data from the NorthWind database. The first server control displays a list of customers and allows editing of existing customers but not insertion or deletion. The second server control takes a customer ID and displays invoice highlights for the customer based on the provided customer ID. Both server controls allow sorting and paging, as well as provide a simple style to show row highlighting. If you have read this book straight through, you can probably guess that each of the two server controls detailed here is a composite control containing a GridView and a DataSource control and inheriting from CompositeControl. All of those guesses would be correct. Listing 10-1 contains the CustomerList custom server control. Listing 10-1. The CustomerList Server Control using System; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; namespace ControlsBook2Lib.Ch10 { [ToolboxData("<{0}:CustomerList runat=server></{0}:CustomerList>")] public class CustomerList : CompositeControl { private const string strSelectCmd = @"Select * from [Customers]"; private const string strUpdateCmd = @"UPDATE [Customers] SET " + @"[CompanyName] = @CompanyName, [ContactName] = @ContactName, " + @"[Phone] = @Phone WHERE [CustomerID] = @CustomerID"; Cameron_865-2C10.fm Page 444 Thursday, February 21, 2008 1:01 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 10 ■ OTHER SERVER CONTROLS 445 public CustomerList() { } public String CustomerID { get { object customerID = ViewState["CustomerID"]; if (customerID == null) return String.Empty; else return (String)customerID; } set { ViewState["CustomerID"] = value; } } // Allow page developers to set the connection string. public String ConnectionString { get { object connectionString = ViewState["ConnectionString"]; if (connectionString == null) return String.Empty; else return (String)connectionString; } set { ViewState["ConnectionString"] = value; } } public Boolean AllowCustomerEditing { get { object allowEditing = ViewState["AllowCustomerEditing"]; if (allowEditing == null) return false; else return (Boolean)allowEditing; } Cameron_865-2C10.fm Page 445 Thursday, February 21, 2008 1:01 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 446 CHAPTER 10 ■ OTHER SERVER CONTROLS set { ViewState["AllowCustomerEditing"] = value; } } protected override void CreateChildControls() { Controls.Clear(); SqlDataSource ds = new SqlDataSource(this.ConnectionString, strSelectCmd); ds.ID = "dsCustomers"; ds.DataSourceMode = SqlDataSourceMode.DataSet; ds.UpdateCommandType = SqlDataSourceCommandType.Text; ds.UpdateCommand = strUpdateCmd; ParameterCollection updateParams = new ParameterCollection(); updateParams.Add(_createParameter("CustomerID", TypeCode.String)); updateParams.Add(_createParameter("CompanyName", TypeCode.String)); updateParams.Add(_createParameter("ContactName", TypeCode.String)); updateParams.Add(_createParameter("Phone", TypeCode.String)); Controls.Add(ds); Label title = new Label(); title.Text = "Customer list"; Controls.Add(title); LiteralControl br = new LiteralControl("<br/>"); Controls.Add(br); GridView grid = new GridView(); grid.ID = "customerGrid"; grid.Font.Size = 8; grid.AllowPaging = true; grid.AllowSorting = true; grid.AutoGenerateColumns = false; String[] fields = { "CustomerID" }; grid.DataKeyNames = fields; grid.DataSourceID = "dsCustomers"; CommandField controlButton = new CommandField(); //Only show Edit button if control configured to allow it if (AllowCustomerEditing) controlButton.ShowEditButton = true; Cameron_865-2C10.fm Page 446 Thursday, February 21, 2008 1:01 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... form are provided in Listings 10-6, 10 -7, 10-8, and 10-9 respectively Listing 10-6 The CustomerListWebPart Server Control using using using using using System; System.Drawing; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; namespace ControlsBook2Lib.Ch10 { [ToolboxData(" ")] Simpo PDF MergePage 4 67 Split Unregistered... disconnect, and so on to the ConnectionZone control We also override OnPreRender in CustomerInfoWebPart aspx.cs and set properties for the connection verbs and UI to customize the connection functionality This completes the work necessary to wire up our server controls and link them the web-part way 463 Simpo PDF MergePage 464 Split Unregistered Version - http://www.simpopdf.com Cameron_865-2C10.fm and Thursday,... with all composite server controls, CreateChildControls does all of the heavy lifting to build out the server control hierarchy The controls include a Label for the title, a LiteralControl to contain a br tag, a SqlDataSource, and, of course, the GridView control The CreateChildControls override attaches two events to the GridView control, one for the SelectedIndexChanged event and the other for the... else return (String)connectionString; } set { ViewState["ConnectionString"] = value; } } 471 Simpo PDF MergePage 472 Split Unregistered Version - http://www.simpopdf.com Cameron_865-2C10.fm and Thursday, February 21, 2008 1:01 PM 472 CHAPTER 10 ■ OTHER SERVE R CONTROLS protected override void CreateChildControls() { Controls. Clear(); SqlDataSource ds = new SqlDataSource(this.ConnectionString, String.Format(strSelectCmd,... dataTypeCode); return theParm; } } } Both controls have two helper methods for building out the control hierarchy; they are named _createBoundField and _createParameter, and they help to create the bound fields and parameters for the GridView control The demonstration web form for the two server controls is CustomerInfo.aspx The source code is shown in Listings 10-3 and 10-4 451 Simpo PDF MergePage 452... WebPartPageController Server Control using using using using using using System; System.ComponentModel; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; Simpo PDF MergePage 4 57 Split Unregistered Version - http://www.simpopdf.com Cameron_865-2C10.fm and Thursday, February 21, 2008 1:01 PM C HAPTE R 10 ■ OTHER S ERVER C ONTR OLS namespace ControlsBook2Lib.Ch10... //this method as the mechanism for connecting with // the provider [ConnectionConsumer("CustomerID Consumer", "CustomerIDConsumer")] public void GetICustomerID(ICustomerID Provider) { _customerIDProvider = Provider; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (this._customerIDProvider != null) { CustomerID = _customerIDProvider.CustomerID.Trim(); } Title = "Customer Invoices... override ControlCollection Controls { get { EnsureChildControls(); return base .Controls; } } public override Unit Height { 459 Simpo PDF MergePage 460 Split Unregistered Version - http://www.simpopdf.com Cameron_865-2C10.fm and Thursday, February 21, 2008 1:01 PM 460 CHAPTER 10 ■ OTHER SERVE R CONTROLS get { return base.Height; } set { EnsureChildControls(); Unit min = new Unit( 87) ; if (value.Value > min.Value)... enable connections between web parts Connecting Web Parts In the previous sections, we created server controls and then converted them to web parts We also added a handy web page controller web part to expose web part page functionality to end users In the server control versions of the web parts, we added a border and a label to contain a title for the control If you view the screen shots in Figures 10-1... ICustomerID and assigns it to the private variable customerIDProvider Finally, we override OnPreRender for the CustomerInvoicesWebPart so that the CustomerID can be retrieved from the provider and set on the CustomerInvoicesWebPart’s CustomerID property Wiring Up the Page To allow connections between the web parts, we first add a ConnectionZone web control to the CustomerInfoWebPart.aspx markup and add . additional examples of ASP.NET AJAX server controls and extenders, we recommend downloading and reviewing the ASP.NET AJAX Control Toolkit available at http://asp.net/ ajax/ ajaxcontroltoolkit/samples/. Cameron_865-2C09.fm. second server control takes a customer ID and displays invoice highlights for the customer based on the provided customer ID. Both server controls allow sorting and paging, as well as provide. Web Parts In this section, we create two server controls and demonstrate them in a basic ASPX page. Next, we convert the server controls to web parts and then demonstrate them in a web part portal

Ngày đăng: 12/08/2014, 23:20

Mục lục

  • Pro ASP.NET 3.5 Server Controls and AJAX Components

  • Contents at a Glance

  • Contents

  • About the Authors

  • About the Technical Reviewer

  • Acknowledgments

  • Introduction

    • Who This Book Is For

    • How This Book Is Structured

    • Prerequisites

    • Downloading the Code

    • Contacting the Authors

    • Server Control Basics

      • Source Code

      • The Heart and Soul of ASP.NET

      • A .NET Framework fiHelo, WorldflWeb Form

      • Control Properties

      • Control Methods

      • Control Events

      • The Web Page As a Control Tree

      • The Root Controls

        • The System.Web.UI Namespace

        • System.Web.UI.HtmlControls Namespace

          • An HTML Controls Demonstration

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan