# ASP.NET 1.1 Insider Solutions- P7

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
45
lượt xem
10

## ASP.NET 1.1 Insider Solutions- P7

Mô tả tài liệu

Tham khảo tài liệu 'asp.net 1.1 insider solutions- p7', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: ASP.NET 1.1 Insider Solutions- P7

1. 288 7 Design Issues for User Controls LISTING 7.23 Continued If (ScrollBars = True) Then sScroll = “yes” End If Dim sHelp As String = “no” If (HelpButton = True) Then sHelp = “yes” End If Because a couple of the features for dialog windows are available only in Internet Explorer 5.5 and higher, you next use the BrowserCapabilities object (exposed by the ASP.NET Request. Browser property) to check the browser type and version (see Listing 7.24). You create a Decimal (floating-point) value that contains the major and minor version numbers. Then, provided that you haven’t already done so in a previous instance of the control, you build the client-side script in a String variable (as you’ve done in previous examples). The client- side script here appears to be a bit more complex than that in earlier examples because you have to create the features string as you go along. When the script is complete, you can create the function name and parameters string and attach the whole thing to the target control in exactly the same way as in the two previous examples (the code for this is not repeated here; refer to Listing 7.15). LISTING 7.24 Sniffing the Browser Type and Creating the Client-Side Script ‘ get browser version, but only if it’s Internet Explorer Dim fVer As Decimal = 0 If Request.Browser.Browser = “IE” Then Try Dim iMajor As Integer = Request.Browser.MajorVersion Dim iMinor As Integer = Request.Browser.MinorVersion fVer = Decimal.Parse(iMajor.ToString() & “.” _ & iMinor.ToString()) Catch End Try End If ‘ create client-side script if not already registered If Not Page.IsClientScriptBlockRegistered(“AHHIEDlg”) Then ‘ decide whether position is specified or centered If (Center = True) Then sFeatures = “center:yes;” Else sFeatures = “dialogTop:” & Top.ToString() _ & “px;dialogLeft:” & Left.ToString() & “px;” End If
2. Integrating Internet Explorer Dialog Windows 289 LISTING 7.24 Continued sFeatures &= “dialogHeight:” & Height.ToString() _ & “px;dialogWidth:” & Width.ToString() _ & “px;edge:” & sBorder & “;scroll:” _ & sScroll & “;help:” & sHelp & “;” ‘see if it’s IE 5.5 or higher If fVer >= 5.5 Then sFeatures &= “resizable:” & sResize _ & “;status:” & sStatus & “;” End If sScript = “” & vbCrlf _ & “” & vbCrlf _ & “” & vbCrlf Page.RegisterClientScriptBlock(“AHHIEDlg”, sScript) End If ‘ create function name to attach to control ‘ must escape any single quotes in agruments string Dim sArgs As String = Arguments.Replace(“‘“, “\’”) Dim sFunctionName As String = “return IEDlgEvent(‘“ _ & SourceURL & “‘, ‘“ & sArgs & “‘, ‘“ _ & sFeatures & “‘, ‘“ & sHidFieldName & “‘, “ _ & (Not CancelEvent).ToString().ToLower() & “);” ‘ attach client-side event handler to element ... as in previous examples ... To make it easier to see the result, the client-side script function named IEDlgEvent that is gener- ated and injected into the page is shown in Listing 7.25. It takes as parameters the URL of the page to display, the arguments string to pass to the dialog, the features string, the name of the hidden control where the return value will be placed, and a Boolean value that specifies whether the underlying control event will be canceled. You can see that the return value from the showModalDialog method is simply placed into the hidden control when the dialog is closed, and the value of the bSubmit parameter is returned to the underlying control.
3. 290 7 Design Issues for User Controls LISTING 7.25 The Client-Side IEDlgEvent Function That Is Generated by the User Control function IEDlgEvent(sURL, sArgs, sFeatures, sField, bSubmit) { var oHidden = document.getElementById(sField); oHidden.value = window.showModalDialog(sURL, sArgs, sFeatures) return bSubmit; } The IEDlgEvent function, shown in Listing 7.25, is called by the event handler attribute attached to the target control—which, depending on the property settings made in the main page, should look something like this: return IEDlgEvent(‘dialogpage.aspx’, ‘S’, ‘center:yes; dialogHeight:300px;dialogWidth:500px;edge:Sunken;scroll:yes; help:yes;resizable:no;status:no;’, ‘AHHIEDlg$test1’, true); Returning a Value from the Modal Dialog The final issue to consider in the sample page is how to get the value selected in the dialog page back to the main page. In fact, all you need to do is assign it to the returnValue property of the window object that is hosting the main page and then close the dialog window by calling its close method: window.returnValue = sMyReturnVal; window.close(); The value assigned to the returnValue property then appears as the return value of the call to the showModalDialog method that originally opened the dialog window. Browser-Adaptive Dialog Windows As you discovered in the earlier examples in this chapter, it’s possible to build user controls that automatically adapt to suit different browsers. The following sections show you how to build a version of the Internet Explorer dialog window example that works in a similar way in other browsers. The sample page that contains the options you can set is shown in Figure 7.13, and you can see that the one extra property is ModalDialog, which you can set to True or False. When ModalDialog is set to True and the page is viewed in Internet Explorer, the result is the same as that in the previous example. A modal Internet Explorer dialog window is shown. If you change ModalDialog to False or view the page in a different browser, it seems at first that the result is the same (see Figure 7.14). However, this is actually a new browser window instance and not a modal dialog. By setting the appropriate features when you call the standard window.open method (which all browsers support), you get a similar appearance. 4. Browser-Adaptive Dialog Windows 291 FIGURE 7.13 The browser-adaptive dialog window sample page. FIGURE 7.14 The nonmodal (new window) dialog page. However, one major difference in this case is that you can no longer easily provide automatic postback (although it is possible, as you’ll see later in this chapter). The new window executes separately from the main window. However, you use script in the new window to insert the value the user selects into the hidden control in the main window, so it can be collected on a postback from the main window (exactly as shown in Figure 7.12). You just click the Get Result button after selecting a value (which closes the new window) to see this occur. How the Browser-Adaptive Dialog Window Example Works Much of the code in this example is the same as the code for the previous example. These are the important points where it differs: n In this example, you have to detect the browser type as before, but this time, you have to determine whether it is Internet Explorer or some other browser. n If the browser type is not Internet Explorer, you generate a features string that uses the syntax and names specific to the window.open method rather than to the window. showModalDialog method. Here’s an example: “top=150,left=150,height=320,width=500,scrollbars=yes, resizable=no,status=no,titlebar=yes,menubar=no,location=no, fullscrceen=no,toolbar=no,directories=no” 5. 292 7 Design Issues for User Controls n You must generate and inject a different client-side script function, which calls the window.open method rather than the window.showModalDialog method. In addition, when using the window.open method, you can’t assign the return value to the hidden control. n There is no arguments parameter for the window.open method, but you need to pass the optional argument to the new window. So that the dialog page can work in both versions, you append this value to the URL of the new page as a query string for both the window.open method and the window.showModalDialog method. You can extract it from the Request.QueryString collection within the new page by using the GetWindowArgument method (which is described shortly). These are the two functions you generate to open a new browser window and a modal dialog window: function IEDlgEvent(sURL, sArgs, sFeatures, sField, bSubmit) { window.open(sURL + ‘?arg=’ + escape(sArgs), ‘_blank’, sFeatures); return false; } function IEDlgEvent(sURL, sArgs, sFeatures, sField, bSubmit) { var oHidden = document.getElementById(sField); oHidden.value = window.showModalDialog(sURL + ‘?arg=’ + escape(sArgs), ‘’, sFeatures); return bSubmit;” & vbCrlf _ n You have to use a different technique in a new browser window to get the selected value back to the main window and then close the new window. You’ll see how this is achieved in the following section. As with the modal dialog window example, this chapter doesn’t list all the code for the page you see displayed in the new window (the list of customers). However, this example uses server- side (ASP.NET) data binding rather than the Internet Explorer–specific client-side data binding approach used in the modal window in the previous example. This means that the dialog page will work on non–Internet Explorer browsers as well as in Internet Explorer. You can use the [view source] link at the bottom of the page in the dialog window to see this code if you wish. Returning a Value from the New Window When you open a new browser window to act as a dialog, there is no facility to specify an optional arguments parameter when opening the window or for returning a value to the main window directly (as is possible with the Internet Explorer showModalDialog method). Instead, you expose two extra methods from this version of the user control, which are designed to be used in the page that is displayed in the dialog window. Using these methods means that you have to register the user control in the page that you show in the dialog window, as well as in the main page. Listing 7.26 shows the two methods. The GetWindowArgument method takes the ID of the control that the script for opening the dialog or new window was attached to, and it simply extracts the value from the Request.QueryString collection where it was placed by the client-side code that opened the dialog or new window. Recall that you pass the value in the query string in all cases, 6. Browser-Adaptive Dialog Windows 293 even when using the showModalDialog method because it is the only obvious way to allow the same page to work in the dialog window for all types of browsers. LISTING 7.26 The GetWindowArgument and SetWindowResult Methods Function GetWindowArgument(ControlID As String) As String ‘ get posted value from Request collection Return Server.UrlDecode(Request.QueryString(“arg”)) End Function Sub SetWindowResult(ControlID As String, ReturnValue As String) ‘ build hidden field name Dim sHidFieldName As String = “AHHIEDlg$” & ControlID ‘ create client-side script Dim sScript As String sScript = “” & vbCrlf _ & “” & vbCrlf _ & “” & vbCrlf Page.RegisterStartupScript(“AHHDlgReturn”, sScript) End Sub The SetWindowResult method, called within the dialog or new window page, accepts the ID of the control that the script to open the dialog or new window was attached to and the value to be returned to the main page. You first check the opener property of the current window to see if it contains a valid reference to the main page window that opened this window. If it does, this provides a reference to the window object where the code that opened the new window was located. You can reference the hidden control in that window and insert the return value into it. If the opener property is null, you know that the current window is a modal dialog window that was opened with the showModalDialog method. In this case, you can simply set the returnValue property of the current window. This value will automatically be returned to the main window and inserted into the hidden control by the code there that called the showModalDialog method. Then, in either case, you just have to call the close method of this window. The result is that the new window closes, and the value is available in the main page when the next postback
7. 294 7 Design Issues for User Controls occurs. As with the earlier examples, it can be Implementing AutoPostback when the extracted at this point, using the same Dialog Window Closes GetDialogResult function that is exposed by If you want to provide automatic postback all the versions of this user control. when the new window is closed, you can achieve this by adding code to the script injected by the SetWindowResult method. All The RegisterStartupScript Method you need to do is call the submit method of Notice that you build the script code as a the form on the main page before you call String in the SetWindowResult method and the close method of the new window. then insert it into the page by using the RegisterStartupScript method rather than the RegisterClientScriptBlock method used in other examples. The RegisterClientScriptBlock method is designed to insert complete functions into a page so that they can be called from control event handler attributes (as is done in earlier examples). The script section is inserted into the page at the start of the server-side form section, immediately after the opening element. The RegisterStartupScript method is designed to inject into the page client-side code that is not a function. If you refer to Listing 7.26, you’ll see that you inject inline code that will run as the page loads, following the postback. This is how the code inserts the return value into the hidden control on the main page and then closes the new window. This kind of code is often referred to as a startup script, and hence the ASP.NET method is called RegisterStartupScript. For the startup script to work properly, the best location is at the end of the page. The RegisterStartupScript method actually injects it at the end of the server-side form section, just before the closing element. Because the controls it references are likely to be on the form, this will work fine in most cases. The corresponding method named IsStartupScriptRegistered can be used to check whether this script section has already been registered (that is, already injected into the page). Summary This chapter concentrates on user controls and how you can take advantage of many of the features they offer to build reusable content that can implement useful controls or methods in a range of types of browsers. This chapter starts by looking at how user controls affect the design and implementation of your code and user interface. The main issue here is coping with the possibility that the control may be used more than once in the same page, and there are techniques and features of ASP.NET that help you to manage this. In particular, you can easily prevent duplicate script sections from being injected into a page. Then, to focus more closely on techniques for building user controls, this chapter shows how you can convert the MaskedEdit control you created in Chapter 6 into a user control. Along the way, this chapter looks at issues such as referencing separate script and image files and adding client-side and server-side validation with the ASP.NET validation controls.
8. Summary 295 Next, this chapter shows how to build a new user control—a SpinBox control—from scratch. While many of the techniques are the same as you used for the MaskedEdit control, this chapter looks at things like checking property value settings, throwing exceptions, and implementing AutoPostback from a composite control. The remainder of this chapter concentrates on a series of examples that have no visible user interface yet make it easy for you to add useful features to Web applications by taking advantage of client-side dialog boxes and dialog windows. While some of the features are specific to Internet Explorer, this chapter shows how you can quite easily build controls that adapt to different types of browsers. This last technique described in this chapter—providing graceful fallback for browsers that don’t implement features you want to take advantage of—leads neatly in to Chapter 8. You’ve already learned about and built a couple of these browser-adaptive controls, and you’ll see a lot more on this topic in Chapter 8. In particular, you’ll extend the SpinBox control introduced in this chapter into a full-fledged browser-adaptive server control.
9. 8 IN THIS CHAPTER The Advantages of Server Controls 298 The Basics of Building Server Controls 298 Building Building a MaskedEdit Server Control 305 Adaptive BEST PRACTICE: Providing a Default Constructor for a Class 307 Controls BEST PRACTICE: Specifying the Versions of Command- Line Tools 312 The previous three chapters discuss differ- Building a SpinBox Server Control 315 ent ways to provide useful reusable content Making the SpinBox Control Adaptive 335 for Web sites and Web applications, while taking advantage of the features of more Installing a SpinBox Control recent browser versions to achieve the best in the GAC 348 in interactivity and performance. Those Summary 352 chapters concentrate mainly on user controls, which provide an ideal environ- ment to achieve reusability while being rela- tively quick and easy to build. This chapter concentrates on an approach mentioned a few times in this book— building server controls. This is, in many ways, the ultimate technique for reusable content because it avoids the issues related to user controls that can limit their useful- ness. This chapter looks at two different server controls, both developed from user controls built in previous chapters. You’ll see how you can easily convert the MaskedEdit control into a server control—effectively a TextBox control with extra behavior added. Then this chapter looks at the SpinBox control, again taking it from the user control stage shown in Chapter 7, “Design Issues for User Controls,” to a full-fledged server control. The SpinBox control is a
10. 298 8 Building Adaptive Controls composite control in that it contains more than one element; it therefore requires some addi- tional implementation. You’ll learn how to take this control beyond the first stage of being a basic server control to make it adapt its output for different browsers. You’ll also install it in the global assembly cache (GAC) to make it available machinewide to all applications. The Advantages of Server Controls Before we dive into implementation of server controls, it’s probably a good idea just to reiterate the advantages they provide over other types of reusable content: n Server controls hide their implementation from the user in a far more comprehensive manner than user controls—The source file is compiled into Intermediate Language (IL) code and does not have to be present in order for the control to be used. User controls, on the other hand, are like ordinary ASPX pages in that they have to be present on the machine. They can be opened and the source code viewed, just like an ASPX page. (Code-behind files that are created by Visual Studio .NET are compiled.) n Server controls raise events that can be handled in the hosting page—In fact, this is often a major requirement for a control. Microsoft recommends that event handlers for user controls should only be placed within the user control, which can limit their usefulness in some scenarios. n Server controls can be installed in the GAC—This means that they are available to any application running on the machine. Remember that user controls can be used only within the application where they reside, so they require you to maintain multiple copies if you want to use them in more than one application. These are three significant features and should convince you that it’s worth the extra effort involved in building controls this way. It’s certainly not as quick or as easy as building a user control, but you’ll find that as you build more, you’ll really start to appreciate the advantages. This book doesn’t have room for a full reference or tutorial on building server controls. Besides, you might have already started building your own controls. Therefore, the aim of this chapter is to demonstrate how you can get the most The ASP .NET QuickStart Server Control from the techniques involved in building Tutorial server controls. However, this chapter shows A useful guide for starting to create server how to get started, the basic features you controls is included in the QuickStart samples need to implement for a server control, and provided with ASP.NET and is available online how you can achieve the appearance and at www.dotnetjunkies.com/quickstart/ behavior you want. aspplus/doc/webctrlauthoring.aspx. The Basics of Building Server Controls The first step in building a control of any kind is to decide exactly what you want from it—just as you have done with user controls in earlier chapters. You can even take advantage of the
11. The Basics of Building Server Controls 299 same technique you sometimes use when building user controls. It’s not unusual to identify sections of code or user interface in ASPX pages that you want to reuse, so you pull them out and package them up as a user control. From there, you develop the code interface and the user interface, often adapting the content as you go to achieve the result you want. When you do this, you actually complete much of the design process for the equivalent server control. For example, you already know how the user interface should be constructed (which elements and attributes are required), which properties and methods must be exposed, and the implementation of the code within the control. Of course, you still need to consider how the move to a server control might change things. For example, the ability to expose events might make some tasks much easier to perform in a server control. You might want to raise an event when some values change, and you can then pass those values to the hosting page as properties of an event object—in the same way that many of the built-in ASP.NET controls do. The Process of Building a Server Control The following is a list of steps involved in building a server control: n Design the user interface that the control will implement. This might be as simple as a single control (such as the MaskedEdit control you’ll see shortly), or it might be a compound control involving multiple elements (such as the SpinBox control covered later in this chapter). n Design the code interface that will be exposed by the control, including the properties, methods, and events that you want the control to provide. n Figure out which existing class to inherit from. This class can provide many of the features and behavior that a server control must exhibit, and it saves you from having to imple- ment all the basic features yourself. You just override existing features that you don’t want, in order to remove them or change their behavior, and add any extra features you need. n Plan where and how the control must handle the events raised by the ASP.NET page framework so that you know when and where you need to interact with the framework and the base class to create the required output in the page. n Create the class file to implement the control, compile it, test it, and then deploy it. In this chapter you’ll work through all these steps for two server controls. However, because you’ve already built them both as user controls, you already roughly know what the code inter- face, user interface, and implementation should look like. The Life Cycle of ASP.NET Controls When you build server controls, the life cycle (that is, the way that the controls are instantiated, the events that they react to, and the point at which they are destroyed) is relatively simple. As you have seen in earlier chapters, the ASP.NET page framework creates an instance of the user